blob: 04ec67f5b397b9f9bcdd6edcf820158d307746aa [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 +0000123void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000124 print(dbgs());
125 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000126}
127
Dan Gohman4ce32db2010-11-17 22:27:42 +0000128void SCEV::print(raw_ostream &OS) const {
129 switch (getSCEVType()) {
130 case scConstant:
131 WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false);
132 return;
133 case scTruncate: {
134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
135 const SCEV *Op = Trunc->getOperand();
136 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
137 << *Trunc->getType() << ")";
138 return;
139 }
140 case scZeroExtend: {
141 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
142 const SCEV *Op = ZExt->getOperand();
143 OS << "(zext " << *Op->getType() << " " << *Op << " to "
144 << *ZExt->getType() << ")";
145 return;
146 }
147 case scSignExtend: {
148 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
149 const SCEV *Op = SExt->getOperand();
150 OS << "(sext " << *Op->getType() << " " << *Op << " to "
151 << *SExt->getType() << ")";
152 return;
153 }
154 case scAddRecExpr: {
155 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
156 OS << "{" << *AR->getOperand(0);
157 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
158 OS << ",+," << *AR->getOperand(i);
159 OS << "}<";
160 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
161 OS << ">";
162 return;
163 }
164 case scAddExpr:
165 case scMulExpr:
166 case scUMaxExpr:
167 case scSMaxExpr: {
168 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
169 const char *OpStr;
170 switch (NAry->getSCEVType()) {
171 case scAddExpr: OpStr = " + "; break;
172 case scMulExpr: OpStr = " * "; break;
173 case scUMaxExpr: OpStr = " umax "; break;
174 case scSMaxExpr: OpStr = " smax "; break;
175 }
176 OS << "(";
177 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
178 I != E; ++I) {
179 OS << **I;
180 if (llvm::next(I) != E)
181 OS << OpStr;
182 }
183 OS << ")";
184 return;
185 }
186 case scUDivExpr: {
187 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
188 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
189 return;
190 }
191 case scUnknown: {
192 const SCEVUnknown *U = cast<SCEVUnknown>(this);
193 const Type *AllocTy;
194 if (U->isSizeOf(AllocTy)) {
195 OS << "sizeof(" << *AllocTy << ")";
196 return;
197 }
198 if (U->isAlignOf(AllocTy)) {
199 OS << "alignof(" << *AllocTy << ")";
200 return;
201 }
202
203 const Type *CTy;
204 Constant *FieldNo;
205 if (U->isOffsetOf(CTy, FieldNo)) {
206 OS << "offsetof(" << *CTy << ", ";
207 WriteAsOperand(OS, FieldNo, false);
208 OS << ")";
209 return;
210 }
211
212 // Otherwise just print it normally.
213 WriteAsOperand(OS, U->getValue(), false);
214 return;
215 }
216 case scCouldNotCompute:
217 OS << "***COULDNOTCOMPUTE***";
218 return;
219 default: break;
220 }
221 llvm_unreachable("Unknown SCEV kind!");
222}
223
224const Type *SCEV::getType() const {
225 switch (getSCEVType()) {
226 case scConstant:
227 return cast<SCEVConstant>(this)->getType();
228 case scTruncate:
229 case scZeroExtend:
230 case scSignExtend:
231 return cast<SCEVCastExpr>(this)->getType();
232 case scAddRecExpr:
233 case scMulExpr:
234 case scUMaxExpr:
235 case scSMaxExpr:
236 return cast<SCEVNAryExpr>(this)->getType();
237 case scAddExpr:
238 return cast<SCEVAddExpr>(this)->getType();
239 case scUDivExpr:
240 return cast<SCEVUDivExpr>(this)->getType();
241 case scUnknown:
242 return cast<SCEVUnknown>(this)->getType();
243 case scCouldNotCompute:
244 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
245 return 0;
246 default: break;
247 }
248 llvm_unreachable("Unknown SCEV kind!");
249 return 0;
250}
251
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000252bool SCEV::isZero() const {
253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
254 return SC->getValue()->isZero();
255 return false;
256}
257
Dan Gohman70a1fe72009-05-18 15:22:39 +0000258bool SCEV::isOne() const {
259 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
260 return SC->getValue()->isOne();
261 return false;
262}
Chris Lattner53e677a2004-04-02 20:23:17 +0000263
Dan Gohman4d289bf2009-06-24 00:30:26 +0000264bool SCEV::isAllOnesValue() const {
265 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
266 return SC->getValue()->isAllOnesValue();
267 return false;
268}
269
Owen Anderson753ad612009-06-22 21:57:23 +0000270SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000271 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000272
Chris Lattner53e677a2004-04-02 20:23:17 +0000273bool SCEVCouldNotCompute::classof(const SCEV *S) {
274 return S->getSCEVType() == scCouldNotCompute;
275}
276
Dan Gohman0bba49c2009-07-07 17:06:11 +0000277const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000278 FoldingSetNodeID ID;
279 ID.AddInteger(scConstant);
280 ID.AddPointer(V);
281 void *IP = 0;
282 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000283 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000284 UniqueSCEVs.InsertNode(S, IP);
285 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
Chris Lattner53e677a2004-04-02 20:23:17 +0000287
Dan Gohman0bba49c2009-07-07 17:06:11 +0000288const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000289 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000290}
291
Dan Gohman0bba49c2009-07-07 17:06:11 +0000292const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000293ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000294 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
295 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000296}
297
Dan Gohman3bf63762010-06-18 19:54:20 +0000298SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000299 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000300 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000301
Dan Gohman3bf63762010-06-18 19:54:20 +0000302SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000303 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000304 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000305 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
306 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000307 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
Chris Lattner53e677a2004-04-02 20:23:17 +0000309
Dan Gohman3bf63762010-06-18 19:54:20 +0000310SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000311 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000312 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000313 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
314 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316}
317
Dan Gohman3bf63762010-06-18 19:54:20 +0000318SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000319 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000320 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000321 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
322 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000323 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000324}
325
Dan Gohmanab37f502010-08-02 23:49:30 +0000326void SCEVUnknown::deleted() {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000327 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000328 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000329
330 // Remove this SCEVUnknown from the uniquing map.
331 SE->UniqueSCEVs.RemoveNode(this);
332
333 // Release the value.
334 setValPtr(0);
335}
336
337void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000338 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000339 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000340
341 // Remove this SCEVUnknown from the uniquing map.
342 SE->UniqueSCEVs.RemoveNode(this);
343
344 // Update this SCEVUnknown to point to the new value. This is needed
345 // because there may still be outstanding SCEVs which still point to
346 // this SCEVUnknown.
347 setValPtr(New);
348}
349
Dan Gohman0f5efe52010-01-28 02:15:55 +0000350bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000351 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000352 if (VCE->getOpcode() == Instruction::PtrToInt)
353 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000354 if (CE->getOpcode() == Instruction::GetElementPtr &&
355 CE->getOperand(0)->isNullValue() &&
356 CE->getNumOperands() == 2)
357 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
358 if (CI->isOne()) {
359 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
360 ->getElementType();
361 return true;
362 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000363
364 return false;
365}
366
367bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000368 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000369 if (VCE->getOpcode() == Instruction::PtrToInt)
370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000371 if (CE->getOpcode() == Instruction::GetElementPtr &&
372 CE->getOperand(0)->isNullValue()) {
373 const Type *Ty =
374 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
375 if (const StructType *STy = dyn_cast<StructType>(Ty))
376 if (!STy->isPacked() &&
377 CE->getNumOperands() == 3 &&
378 CE->getOperand(1)->isNullValue()) {
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
380 if (CI->isOne() &&
381 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000382 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000383 AllocTy = STy->getElementType(1);
384 return true;
385 }
386 }
387 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000388
389 return false;
390}
391
Dan Gohman4f8eea82010-02-01 18:27:38 +0000392bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000393 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000394 if (VCE->getOpcode() == Instruction::PtrToInt)
395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
396 if (CE->getOpcode() == Instruction::GetElementPtr &&
397 CE->getNumOperands() == 3 &&
398 CE->getOperand(0)->isNullValue() &&
399 CE->getOperand(1)->isNullValue()) {
400 const Type *Ty =
401 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
402 // Ignore vector types here so that ScalarEvolutionExpander doesn't
403 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000404 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000405 CTy = Ty;
406 FieldNo = CE->getOperand(2);
407 return true;
408 }
409 }
410
411 return false;
412}
413
Chris Lattner8d741b82004-06-20 06:23:15 +0000414//===----------------------------------------------------------------------===//
415// SCEV Utilities
416//===----------------------------------------------------------------------===//
417
418namespace {
419 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
420 /// than the complexity of the RHS. This comparator is used to canonicalize
421 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000422 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000423 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000424 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000425 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000426
Dan Gohman67ef74e2010-08-27 15:26:01 +0000427 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000428 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman67ef74e2010-08-27 15:26:01 +0000429 return compare(LHS, RHS) < 0;
430 }
431
432 // Return negative, zero, or positive, if LHS is less than, equal to, or
433 // greater than RHS, respectively. A three-way result allows recursive
434 // comparisons to be more efficient.
435 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000436 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
437 if (LHS == RHS)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000438 return 0;
Dan Gohman42214892009-08-31 21:15:23 +0000439
Dan Gohman72861302009-05-07 14:39:04 +0000440 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000441 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
442 if (LType != RType)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000443 return (int)LType - (int)RType;
Dan Gohman72861302009-05-07 14:39:04 +0000444
Dan Gohman3bf63762010-06-18 19:54:20 +0000445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
Dan Gohman67ef74e2010-08-27 15:26:01 +0000448 switch (LType) {
449 case scUnknown: {
450 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000451 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000452
453 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
454 // not as complete as it could be.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000455 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000456
457 // Order pointer values after integer values. This helps SCEVExpander
458 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000459 bool LIsPointer = LV->getType()->isPointerTy(),
460 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000461 if (LIsPointer != RIsPointer)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000462 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000463
464 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000465 unsigned LID = LV->getValueID(),
466 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000467 if (LID != RID)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000468 return (int)LID - (int)RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000469
470 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000471 if (const Argument *LA = dyn_cast<Argument>(LV)) {
472 const Argument *RA = cast<Argument>(RV);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000473 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
474 return (int)LArgNo - (int)RArgNo;
Dan Gohman3bf63762010-06-18 19:54:20 +0000475 }
476
Dan Gohman67ef74e2010-08-27 15:26:01 +0000477 // For instructions, compare their loop depth, and their operand
478 // count. This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000479 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
480 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000481
482 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000483 const BasicBlock *LParent = LInst->getParent(),
484 *RParent = RInst->getParent();
485 if (LParent != RParent) {
486 unsigned LDepth = LI->getLoopDepth(LParent),
487 RDepth = LI->getLoopDepth(RParent);
488 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000489 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000490 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000491
492 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000493 unsigned LNumOps = LInst->getNumOperands(),
494 RNumOps = RInst->getNumOperands();
Dan Gohman67ef74e2010-08-27 15:26:01 +0000495 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000496 }
497
Dan Gohman67ef74e2010-08-27 15:26:01 +0000498 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000499 }
500
Dan Gohman67ef74e2010-08-27 15:26:01 +0000501 case scConstant: {
502 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000503 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000504
505 // Compare constant values.
Dan Gohmane28d7922010-08-16 16:25:35 +0000506 const APInt &LA = LC->getValue()->getValue();
507 const APInt &RA = RC->getValue()->getValue();
508 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000509 if (LBitWidth != RBitWidth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000510 return (int)LBitWidth - (int)RBitWidth;
511 return LA.ult(RA) ? -1 : 1;
Dan Gohman3bf63762010-06-18 19:54:20 +0000512 }
513
Dan Gohman67ef74e2010-08-27 15:26:01 +0000514 case scAddRecExpr: {
515 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000516 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000517
518 // Compare addrec loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000519 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
520 if (LLoop != RLoop) {
521 unsigned LDepth = LLoop->getLoopDepth(),
522 RDepth = RLoop->getLoopDepth();
523 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000524 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000525 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000526
527 // Addrec complexity grows with operand count.
528 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
529 if (LNumOps != RNumOps)
530 return (int)LNumOps - (int)RNumOps;
531
532 // Lexicographically compare.
533 for (unsigned i = 0; i != LNumOps; ++i) {
534 long X = compare(LA->getOperand(i), RA->getOperand(i));
535 if (X != 0)
536 return X;
537 }
538
539 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000540 }
541
Dan Gohman67ef74e2010-08-27 15:26:01 +0000542 case scAddExpr:
543 case scMulExpr:
544 case scSMaxExpr:
545 case scUMaxExpr: {
546 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000547 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000548
549 // Lexicographically compare n-ary expressions.
Dan Gohman304a7a62010-07-23 21:20:52 +0000550 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
551 for (unsigned i = 0; i != LNumOps; ++i) {
552 if (i >= RNumOps)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000553 return 1;
554 long X = compare(LC->getOperand(i), RC->getOperand(i));
555 if (X != 0)
556 return X;
Dan Gohman3bf63762010-06-18 19:54:20 +0000557 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000558 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000559 }
560
Dan Gohman67ef74e2010-08-27 15:26:01 +0000561 case scUDivExpr: {
562 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000563 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000564
565 // Lexicographically compare udiv expressions.
566 long X = compare(LC->getLHS(), RC->getLHS());
567 if (X != 0)
568 return X;
569 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman3bf63762010-06-18 19:54:20 +0000570 }
571
Dan Gohman67ef74e2010-08-27 15:26:01 +0000572 case scTruncate:
573 case scZeroExtend:
574 case scSignExtend: {
575 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000576 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000577
578 // Compare cast expressions by operand.
579 return compare(LC->getOperand(), RC->getOperand());
580 }
581
582 default:
583 break;
Dan Gohman3bf63762010-06-18 19:54:20 +0000584 }
585
586 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman67ef74e2010-08-27 15:26:01 +0000587 return 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000588 }
589 };
590}
591
592/// GroupByComplexity - Given a list of SCEV objects, order them by their
593/// complexity, and group objects of the same complexity together by value.
594/// When this routine is finished, we know that any duplicates in the vector are
595/// consecutive and that complexity is monotonically increasing.
596///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000597/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000598/// results from this routine. In other words, we don't want the results of
599/// this to depend on where the addresses of various SCEV objects happened to
600/// land in memory.
601///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000602static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000603 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000604 if (Ops.size() < 2) return; // Noop
605 if (Ops.size() == 2) {
606 // This is the common case, which also happens to be trivially simple.
607 // Special case it.
Dan Gohmanc6a8e992010-08-29 15:07:13 +0000608 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
609 if (SCEVComplexityCompare(LI)(RHS, LHS))
610 std::swap(LHS, RHS);
Chris Lattner8d741b82004-06-20 06:23:15 +0000611 return;
612 }
613
Dan Gohman3bf63762010-06-18 19:54:20 +0000614 // Do the rough sort by complexity.
615 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
616
617 // Now that we are sorted by complexity, group elements of the same
618 // complexity. Note that this is, at worst, N^2, but the vector is likely to
619 // be extremely short in practice. Note that we take this approach because we
620 // do not want to depend on the addresses of the objects we are grouping.
621 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
622 const SCEV *S = Ops[i];
623 unsigned Complexity = S->getSCEVType();
624
625 // If there are any objects of the same complexity and same value as this
626 // one, group them.
627 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
628 if (Ops[j] == S) { // Found a duplicate.
629 // Move it to immediately after i'th element.
630 std::swap(Ops[i+1], Ops[j]);
631 ++i; // no need to rescan it.
632 if (i == e-2) return; // Done!
633 }
634 }
635 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000636}
637
Chris Lattner53e677a2004-04-02 20:23:17 +0000638
Chris Lattner53e677a2004-04-02 20:23:17 +0000639
640//===----------------------------------------------------------------------===//
641// Simple SCEV method implementations
642//===----------------------------------------------------------------------===//
643
Eli Friedmanb42a6262008-08-04 23:49:06 +0000644/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000645/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000646static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000647 ScalarEvolution &SE,
648 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000649 // Handle the simplest case efficiently.
650 if (K == 1)
651 return SE.getTruncateOrZeroExtend(It, ResultTy);
652
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000653 // We are using the following formula for BC(It, K):
654 //
655 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
656 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000657 // Suppose, W is the bitwidth of the return value. We must be prepared for
658 // overflow. Hence, we must assure that the result of our computation is
659 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
660 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000661 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000662 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000663 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000664 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
665 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000666 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000667 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000668 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669 // This formula is trivially equivalent to the previous formula. However,
670 // this formula can be implemented much more efficiently. The trick is that
671 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
672 // arithmetic. To do exact division in modular arithmetic, all we have
673 // to do is multiply by the inverse. Therefore, this step can be done at
674 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000675 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000676 // The next issue is how to safely do the division by 2^T. The way this
677 // is done is by doing the multiplication step at a width of at least W + T
678 // bits. This way, the bottom W+T bits of the product are accurate. Then,
679 // when we perform the division by 2^T (which is equivalent to a right shift
680 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
681 // truncated out after the division by 2^T.
682 //
683 // In comparison to just directly using the first formula, this technique
684 // is much more efficient; using the first formula requires W * K bits,
685 // but this formula less than W + K bits. Also, the first formula requires
686 // a division step, whereas this formula only requires multiplies and shifts.
687 //
688 // It doesn't matter whether the subtraction step is done in the calculation
689 // width or the input iteration count's width; if the subtraction overflows,
690 // the result must be zero anyway. We prefer here to do it in the width of
691 // the induction variable because it helps a lot for certain cases; CodeGen
692 // isn't smart enough to ignore the overflow, which leads to much less
693 // efficient code if the width of the subtraction is wider than the native
694 // register width.
695 //
696 // (It's possible to not widen at all by pulling out factors of 2 before
697 // the multiplication; for example, K=2 can be calculated as
698 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
699 // extra arithmetic, so it's not an obvious win, and it gets
700 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000701
Eli Friedmanb42a6262008-08-04 23:49:06 +0000702 // Protection from insane SCEVs; this bound is conservative,
703 // but it probably doesn't matter.
704 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000705 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000706
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000707 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000708
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709 // Calculate K! / 2^T and T; we divide out the factors of two before
710 // multiplying for calculating K! / 2^T to avoid overflow.
711 // Other overflow doesn't matter because we only care about the bottom
712 // W bits of the result.
713 APInt OddFactorial(W, 1);
714 unsigned T = 1;
715 for (unsigned i = 3; i <= K; ++i) {
716 APInt Mult(W, i);
717 unsigned TwoFactors = Mult.countTrailingZeros();
718 T += TwoFactors;
719 Mult = Mult.lshr(TwoFactors);
720 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000721 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000722
Eli Friedmanb42a6262008-08-04 23:49:06 +0000723 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000724 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000725
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000726 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000727 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
728
729 // Calculate the multiplicative inverse of K! / 2^T;
730 // this multiplication factor will perform the exact division by
731 // K! / 2^T.
732 APInt Mod = APInt::getSignedMinValue(W+1);
733 APInt MultiplyFactor = OddFactorial.zext(W+1);
734 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
735 MultiplyFactor = MultiplyFactor.trunc(W);
736
737 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000738 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
739 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000740 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000741 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000742 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000743 Dividend = SE.getMulExpr(Dividend,
744 SE.getTruncateOrZeroExtend(S, CalculationTy));
745 }
746
747 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000748 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000749
750 // Truncate the result, and divide by K! / 2^T.
751
752 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
753 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000754}
755
Chris Lattner53e677a2004-04-02 20:23:17 +0000756/// evaluateAtIteration - Return the value of this chain of recurrences at
757/// the specified iteration number. We can evaluate this recurrence by
758/// multiplying each element in the chain by the binomial coefficient
759/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
760///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000761/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000762///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000763/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000764///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000765const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000766 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000767 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000768 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000769 // The computation is correct in the face of overflow provided that the
770 // multiplication is performed _after_ the evaluation of the binomial
771 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000772 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000773 if (isa<SCEVCouldNotCompute>(Coeff))
774 return Coeff;
775
776 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000777 }
778 return Result;
779}
780
Chris Lattner53e677a2004-04-02 20:23:17 +0000781//===----------------------------------------------------------------------===//
782// SCEV Expression folder implementations
783//===----------------------------------------------------------------------===//
784
Dan Gohman0bba49c2009-07-07 17:06:11 +0000785const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000786 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000787 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000788 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000789 assert(isSCEVable(Ty) &&
790 "This is not a conversion to a SCEVable type!");
791 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000792
Dan Gohmanc050fd92009-07-13 20:50:19 +0000793 FoldingSetNodeID ID;
794 ID.AddInteger(scTruncate);
795 ID.AddPointer(Op);
796 ID.AddPointer(Ty);
797 void *IP = 0;
798 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
799
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000800 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000801 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000802 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000803 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
804 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000805
Dan Gohman20900ca2009-04-22 16:20:48 +0000806 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000807 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000808 return getTruncateExpr(ST->getOperand(), Ty);
809
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000810 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000811 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000812 return getTruncateOrSignExtend(SS->getOperand(), Ty);
813
814 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000815 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000816 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
817
Dan Gohman6864db62009-06-18 16:24:47 +0000818 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000819 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000820 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000821 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000822 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
823 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000824 }
825
Dan Gohmanf53462d2010-07-15 20:02:11 +0000826 // As a special case, fold trunc(undef) to undef. We don't want to
827 // know too much about SCEVUnknowns, but this special case is handy
828 // and harmless.
829 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
830 if (isa<UndefValue>(U->getValue()))
831 return getSCEV(UndefValue::get(Ty));
832
Dan Gohman420ab912010-06-25 18:47:08 +0000833 // The cast wasn't folded; create an explicit cast node. We can reuse
834 // the existing insert position since if we get here, we won't have
835 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000836 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
837 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000838 UniqueSCEVs.InsertNode(S, IP);
839 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000840}
841
Dan Gohman0bba49c2009-07-07 17:06:11 +0000842const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000843 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000844 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000845 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000846 assert(isSCEVable(Ty) &&
847 "This is not a conversion to a SCEVable type!");
848 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000849
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000850 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000851 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
852 return getConstant(
853 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
854 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000855
Dan Gohman20900ca2009-04-22 16:20:48 +0000856 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000857 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000858 return getZeroExtendExpr(SZ->getOperand(), Ty);
859
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000860 // Before doing any expensive analysis, check to see if we've already
861 // computed a SCEV for this Op and Ty.
862 FoldingSetNodeID ID;
863 ID.AddInteger(scZeroExtend);
864 ID.AddPointer(Op);
865 ID.AddPointer(Ty);
866 void *IP = 0;
867 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
868
Dan Gohman01ecca22009-04-27 20:16:15 +0000869 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000870 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000871 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000872 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000873 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000874 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000875 const SCEV *Start = AR->getStart();
876 const SCEV *Step = AR->getStepRecurrence(*this);
877 unsigned BitWidth = getTypeSizeInBits(AR->getType());
878 const Loop *L = AR->getLoop();
879
Dan Gohmaneb490a72009-07-25 01:22:26 +0000880 // If we have special knowledge that this addrec won't overflow,
881 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000882 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000883 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
884 getZeroExtendExpr(Step, Ty),
885 L);
886
Dan Gohman01ecca22009-04-27 20:16:15 +0000887 // Check whether the backedge-taken count is SCEVCouldNotCompute.
888 // Note that this serves two purposes: It filters out loops that are
889 // simply not analyzable, and it covers the case where this code is
890 // being called from within backedge-taken count analysis, such that
891 // attempting to ask for the backedge-taken count would likely result
892 // in infinite recursion. In the later case, the analysis code will
893 // cope with a conservative value, and it will take care to purge
894 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000895 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000896 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000897 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000898 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000899
900 // Check whether the backedge-taken count can be losslessly casted to
901 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000902 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000903 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000904 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000905 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
906 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000907 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000908 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000909 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000910 const SCEV *Add = getAddExpr(Start, ZMul);
911 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000912 getAddExpr(getZeroExtendExpr(Start, WideTy),
913 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
914 getZeroExtendExpr(Step, WideTy)));
915 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000916 // Return the expression with the addrec on the outside.
917 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
918 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000919 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000920
921 // Similar to above, only this time treat the step value as signed.
922 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000923 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000924 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000925 OperandExtendedAdd =
926 getAddExpr(getZeroExtendExpr(Start, WideTy),
927 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
928 getSignExtendExpr(Step, WideTy)));
929 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000930 // Return the expression with the addrec on the outside.
931 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
932 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000933 L);
934 }
935
936 // If the backedge is guarded by a comparison with the pre-inc value
937 // the addrec is safe. Also, if the entry is guarded by a comparison
938 // with the start value and the backedge is guarded by a comparison
939 // with the post-inc value, the addrec is safe.
940 if (isKnownPositive(Step)) {
941 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
942 getUnsignedRange(Step).getUnsignedMax());
943 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000944 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000945 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
946 AR->getPostIncExpr(*this), N)))
947 // Return the expression with the addrec on the outside.
948 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
949 getZeroExtendExpr(Step, Ty),
950 L);
951 } else if (isKnownNegative(Step)) {
952 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
953 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000954 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
955 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000956 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
957 AR->getPostIncExpr(*this), N)))
958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
961 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000962 }
963 }
964 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000965
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000966 // The cast wasn't folded; create an explicit cast node.
967 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000968 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000969 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
970 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000971 UniqueSCEVs.InsertNode(S, IP);
972 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000973}
974
Dan Gohman0bba49c2009-07-07 17:06:11 +0000975const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000976 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000977 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000978 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000979 assert(isSCEVable(Ty) &&
980 "This is not a conversion to a SCEVable type!");
981 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000982
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000983 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000984 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
985 return getConstant(
986 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
987 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +0000988
Dan Gohman20900ca2009-04-22 16:20:48 +0000989 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000990 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000991 return getSignExtendExpr(SS->getOperand(), Ty);
992
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000993 // Before doing any expensive analysis, check to see if we've already
994 // computed a SCEV for this Op and Ty.
995 FoldingSetNodeID ID;
996 ID.AddInteger(scSignExtend);
997 ID.AddPointer(Op);
998 ID.AddPointer(Ty);
999 void *IP = 0;
1000 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1001
Dan Gohman01ecca22009-04-27 20:16:15 +00001002 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001003 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001004 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001005 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001006 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001007 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001008 const SCEV *Start = AR->getStart();
1009 const SCEV *Step = AR->getStepRecurrence(*this);
1010 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1011 const Loop *L = AR->getLoop();
1012
Dan Gohmaneb490a72009-07-25 01:22:26 +00001013 // If we have special knowledge that this addrec won't overflow,
1014 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001015 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001016 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1017 getSignExtendExpr(Step, Ty),
1018 L);
1019
Dan Gohman01ecca22009-04-27 20:16:15 +00001020 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1021 // Note that this serves two purposes: It filters out loops that are
1022 // simply not analyzable, and it covers the case where this code is
1023 // being called from within backedge-taken count analysis, such that
1024 // attempting to ask for the backedge-taken count would likely result
1025 // in infinite recursion. In the later case, the analysis code will
1026 // cope with a conservative value, and it will take care to purge
1027 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001028 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001029 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001030 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001031 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001032
1033 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001034 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001035 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001036 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001037 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001038 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1039 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001040 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001041 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001042 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001043 const SCEV *Add = getAddExpr(Start, SMul);
1044 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001045 getAddExpr(getSignExtendExpr(Start, WideTy),
1046 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1047 getSignExtendExpr(Step, WideTy)));
1048 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001049 // Return the expression with the addrec on the outside.
1050 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1051 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001052 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001053
1054 // Similar to above, only this time treat the step value as unsigned.
1055 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001056 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001057 Add = getAddExpr(Start, UMul);
1058 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001059 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001060 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1061 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001062 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001063 // Return the expression with the addrec on the outside.
1064 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1065 getZeroExtendExpr(Step, Ty),
1066 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001067 }
1068
1069 // If the backedge is guarded by a comparison with the pre-inc value
1070 // the addrec is safe. Also, if the entry is guarded by a comparison
1071 // with the start value and the backedge is guarded by a comparison
1072 // with the post-inc value, the addrec is safe.
1073 if (isKnownPositive(Step)) {
1074 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1075 getSignedRange(Step).getSignedMax());
1076 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001077 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001078 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1079 AR->getPostIncExpr(*this), N)))
1080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getSignExtendExpr(Step, Ty),
1083 L);
1084 } else if (isKnownNegative(Step)) {
1085 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1086 getSignedRange(Step).getSignedMin());
1087 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001088 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001089 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1090 AR->getPostIncExpr(*this), N)))
1091 // Return the expression with the addrec on the outside.
1092 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1093 getSignExtendExpr(Step, Ty),
1094 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001095 }
1096 }
1097 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001098
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001099 // The cast wasn't folded; create an explicit cast node.
1100 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001102 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1103 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001104 UniqueSCEVs.InsertNode(S, IP);
1105 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001106}
1107
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001108/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1109/// unspecified bits out to the given type.
1110///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001111const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001112 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001113 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1114 "This is not an extending conversion!");
1115 assert(isSCEVable(Ty) &&
1116 "This is not a conversion to a SCEVable type!");
1117 Ty = getEffectiveSCEVType(Ty);
1118
1119 // Sign-extend negative constants.
1120 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1121 if (SC->getValue()->getValue().isNegative())
1122 return getSignExtendExpr(Op, Ty);
1123
1124 // Peel off a truncate cast.
1125 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001126 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001127 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1128 return getAnyExtendExpr(NewOp, Ty);
1129 return getTruncateOrNoop(NewOp, Ty);
1130 }
1131
1132 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001133 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001134 if (!isa<SCEVZeroExtendExpr>(ZExt))
1135 return ZExt;
1136
1137 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001138 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001139 if (!isa<SCEVSignExtendExpr>(SExt))
1140 return SExt;
1141
Dan Gohmana10756e2010-01-21 02:09:26 +00001142 // Force the cast to be folded into the operands of an addrec.
1143 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1144 SmallVector<const SCEV *, 4> Ops;
1145 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1146 I != E; ++I)
1147 Ops.push_back(getAnyExtendExpr(*I, Ty));
1148 return getAddRecExpr(Ops, AR->getLoop());
1149 }
1150
Dan Gohmanf53462d2010-07-15 20:02:11 +00001151 // As a special case, fold anyext(undef) to undef. We don't want to
1152 // know too much about SCEVUnknowns, but this special case is handy
1153 // and harmless.
1154 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1155 if (isa<UndefValue>(U->getValue()))
1156 return getSCEV(UndefValue::get(Ty));
1157
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001158 // If the expression is obviously signed, use the sext cast value.
1159 if (isa<SCEVSMaxExpr>(Op))
1160 return SExt;
1161
1162 // Absent any other information, use the zext cast value.
1163 return ZExt;
1164}
1165
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001166/// CollectAddOperandsWithScales - Process the given Ops list, which is
1167/// a list of operands to be added under the given scale, update the given
1168/// map. This is a helper function for getAddRecExpr. As an example of
1169/// what it does, given a sequence of operands that would form an add
1170/// expression like this:
1171///
1172/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1173///
1174/// where A and B are constants, update the map with these values:
1175///
1176/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1177///
1178/// and add 13 + A*B*29 to AccumulatedConstant.
1179/// This will allow getAddRecExpr to produce this:
1180///
1181/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1182///
1183/// This form often exposes folding opportunities that are hidden in
1184/// the original operand list.
1185///
1186/// Return true iff it appears that any interesting folding opportunities
1187/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1188/// the common case where no interesting opportunities are present, and
1189/// is also used as a check to avoid infinite recursion.
1190///
1191static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001192CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1193 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001194 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001195 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001196 const APInt &Scale,
1197 ScalarEvolution &SE) {
1198 bool Interesting = false;
1199
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001200 // Iterate over the add operands. They are sorted, with constants first.
1201 unsigned i = 0;
1202 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1203 ++i;
1204 // Pull a buried constant out to the outside.
1205 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1206 Interesting = true;
1207 AccumulatedConstant += Scale * C->getValue()->getValue();
1208 }
1209
1210 // Next comes everything else. We're especially interested in multiplies
1211 // here, but they're in the middle, so just visit the rest with one loop.
1212 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001213 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1214 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1215 APInt NewScale =
1216 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1217 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1218 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001219 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001220 Interesting |=
1221 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001222 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001223 NewScale, SE);
1224 } else {
1225 // A multiplication of a constant with some other value. Update
1226 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001227 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1228 const SCEV *Key = SE.getMulExpr(MulOps);
1229 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001230 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001231 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001232 NewOps.push_back(Pair.first->first);
1233 } else {
1234 Pair.first->second += NewScale;
1235 // The map already had an entry for this value, which may indicate
1236 // a folding opportunity.
1237 Interesting = true;
1238 }
1239 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001240 } else {
1241 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001242 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001243 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001244 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001245 NewOps.push_back(Pair.first->first);
1246 } else {
1247 Pair.first->second += Scale;
1248 // The map already had an entry for this value, which may indicate
1249 // a folding opportunity.
1250 Interesting = true;
1251 }
1252 }
1253 }
1254
1255 return Interesting;
1256}
1257
1258namespace {
1259 struct APIntCompare {
1260 bool operator()(const APInt &LHS, const APInt &RHS) const {
1261 return LHS.ult(RHS);
1262 }
1263 };
1264}
1265
Dan Gohman6c0866c2009-05-24 23:45:28 +00001266/// getAddExpr - Get a canonical add expression, or something simpler if
1267/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001268const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1269 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001270 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001271 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001272#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001273 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001274 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001275 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001276 "SCEVAddExpr operand types don't match!");
1277#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001278
Dan Gohmana10756e2010-01-21 02:09:26 +00001279 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1280 if (!HasNUW && HasNSW) {
1281 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001282 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1283 E = Ops.end(); I != E; ++I)
1284 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001285 All = false;
1286 break;
1287 }
1288 if (All) HasNUW = true;
1289 }
1290
Chris Lattner53e677a2004-04-02 20:23:17 +00001291 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001292 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001293
1294 // If there are any constants, fold them together.
1295 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001296 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001297 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001298 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001299 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001301 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1302 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001303 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001304 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001305 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 }
1307
1308 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001309 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001310 Ops.erase(Ops.begin());
1311 --Idx;
1312 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001313
Dan Gohmanbca091d2010-04-12 23:08:18 +00001314 if (Ops.size() == 1) return Ops[0];
1315 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001316
Dan Gohman68ff7762010-08-27 21:39:59 +00001317 // Okay, check to see if the same value occurs in the operand list more than
1318 // once. If so, merge them together into an multiply expression. Since we
1319 // sorted the list, these values are required to be adjacent.
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001321 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001322 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001324 // Scan ahead to count how many equal operands there are.
1325 unsigned Count = 2;
1326 while (i+Count != e && Ops[i+Count] == Ops[i])
1327 ++Count;
1328 // Merge the values into a multiply.
1329 const SCEV *Scale = getConstant(Ty, Count);
1330 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1331 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001332 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001333 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001334 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001335 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001336 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001337 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001338 if (FoundMatch)
1339 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001340
Dan Gohman728c7f32009-05-08 21:03:19 +00001341 // Check for truncates. If all the operands are truncated from the same
1342 // type, see if factoring out the truncate would permit the result to be
1343 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1344 // if the contents of the resulting outer trunc fold to something simple.
1345 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1346 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1347 const Type *DstType = Trunc->getType();
1348 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001349 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001350 bool Ok = true;
1351 // Check all the operands to see if they can be represented in the
1352 // source type of the truncate.
1353 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1354 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1355 if (T->getOperand()->getType() != SrcType) {
1356 Ok = false;
1357 break;
1358 }
1359 LargeOps.push_back(T->getOperand());
1360 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001361 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001362 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001363 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001364 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1365 if (const SCEVTruncateExpr *T =
1366 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1367 if (T->getOperand()->getType() != SrcType) {
1368 Ok = false;
1369 break;
1370 }
1371 LargeMulOps.push_back(T->getOperand());
1372 } else if (const SCEVConstant *C =
1373 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001374 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001375 } else {
1376 Ok = false;
1377 break;
1378 }
1379 }
1380 if (Ok)
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1382 } else {
1383 Ok = false;
1384 break;
1385 }
1386 }
1387 if (Ok) {
1388 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1393 }
1394 }
1395
1396 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1398 ++Idx;
1399
1400 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // If we have an add, expand the add operands onto the end of the operands
1405 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001406 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001407 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001408 DeletedAdd = true;
1409 }
1410
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001413 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001414 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001415 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
1417
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1420 ++Idx;
1421
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001430 Ops.data(), Ops.size(),
1431 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001432 // Some interesting folding opportunity is present, so its worthwhile to
1433 // re-generate the operands list. Group the operands by constant scale,
1434 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001435 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001436 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001437 E = NewOps.end(); I != E; ++I)
1438 MulOpLists[M.find(*I)->second].push_back(*I);
1439 // Re-generate the operands list.
1440 Ops.clear();
1441 if (AccumulatedConstant != 0)
1442 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001443 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1444 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001445 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001446 Ops.push_back(getMulExpr(getConstant(I->first),
1447 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001448 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001449 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001450 if (Ops.size() == 1)
1451 return Ops[0];
1452 return getAddExpr(Ops);
1453 }
1454 }
1455
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 // If we are adding something to a multiply expression, make sure the
1457 // something is not already an operand of the multiply. If so, merge it into
1458 // the multiply.
1459 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001460 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001461 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001462 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001463 if (isa<SCEVConstant>(MulOpSCEV))
1464 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001466 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001468 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 if (Mul->getNumOperands() != 2) {
1470 // If the multiply has more than two operands, we must get the
1471 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001472 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1473 Mul->op_begin()+MulOp);
1474 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001475 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001477 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001478 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001479 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 if (Ops.size() == 2) return OuterMul;
1481 if (AddOp < Idx) {
1482 Ops.erase(Ops.begin()+AddOp);
1483 Ops.erase(Ops.begin()+Idx-1);
1484 } else {
1485 Ops.erase(Ops.begin()+Idx);
1486 Ops.erase(Ops.begin()+AddOp-1);
1487 }
1488 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001489 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001490 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001491
Chris Lattner53e677a2004-04-02 20:23:17 +00001492 // Check this multiply against other multiplies being added together.
1493 for (unsigned OtherMulIdx = Idx+1;
1494 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1495 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001496 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001497 // If MulOp occurs in OtherMul, we can fold the two multiplies
1498 // together.
1499 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1500 OMulOp != e; ++OMulOp)
1501 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1502 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001503 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001505 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001506 Mul->op_begin()+MulOp);
1507 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001508 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001510 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001512 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001513 OtherMul->op_begin()+OMulOp);
1514 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001515 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001516 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001517 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1518 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001520 Ops.erase(Ops.begin()+Idx);
1521 Ops.erase(Ops.begin()+OtherMulIdx-1);
1522 Ops.push_back(OuterMul);
1523 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001524 }
1525 }
1526 }
1527 }
1528
1529 // If there are any add recurrences in the operands list, see if any other
1530 // added values are loop invariant. If so, we can fold them into the
1531 // recurrence.
1532 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1533 ++Idx;
1534
1535 // Scan over all recurrences, trying to fold loop invariants into them.
1536 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1537 // Scan all of the other operands to this add and add them to the vector if
1538 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001539 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001540 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001541 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001542 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001543 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 LIOps.push_back(Ops[i]);
1545 Ops.erase(Ops.begin()+i);
1546 --i; --e;
1547 }
1548
1549 // If we found some loop invariants, fold them into the recurrence.
1550 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001551 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 LIOps.push_back(AddRec->getStart());
1553
Dan Gohman0bba49c2009-07-07 17:06:11 +00001554 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001555 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001556 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001557
Dan Gohmanb9f96512010-06-30 07:16:37 +00001558 // Build the new addrec. Propagate the NUW and NSW flags if both the
1559 // outer add and the inner addrec are guaranteed to have no overflow.
1560 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1561 HasNUW && AddRec->hasNoUnsignedWrap(),
1562 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001563
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 // If all of the other operands were loop invariant, we are done.
1565 if (Ops.size() == 1) return NewRec;
1566
1567 // Otherwise, add the folded AddRec by the non-liv parts.
1568 for (unsigned i = 0;; ++i)
1569 if (Ops[i] == AddRec) {
1570 Ops[i] = NewRec;
1571 break;
1572 }
Dan Gohman246b2562007-10-22 18:31:58 +00001573 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001574 }
1575
1576 // Okay, if there weren't any loop invariants to be folded, check to see if
1577 // there are multiple AddRec's with the same loop induction variable being
1578 // added together. If so, we can fold them.
1579 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001580 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1581 ++OtherIdx)
1582 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1583 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1584 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1585 AddRec->op_end());
1586 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1587 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001588 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001589 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001590 if (OtherAddRec->getLoop() == AddRecLoop) {
1591 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1592 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001593 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001594 AddRecOps.append(OtherAddRec->op_begin()+i,
1595 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001596 break;
1597 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001598 AddRecOps[i] = getAddExpr(AddRecOps[i],
1599 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001600 }
1601 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 }
Dan Gohman32527152010-08-27 20:45:56 +00001603 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop);
1604 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 }
1606
1607 // Otherwise couldn't fold anything into this recurrence. Move onto the
1608 // next one.
1609 }
1610
1611 // Okay, it looks like we really DO need an add expr. Check to see if we
1612 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001613 FoldingSetNodeID ID;
1614 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001615 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1616 ID.AddPointer(Ops[i]);
1617 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001618 SCEVAddExpr *S =
1619 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1620 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001621 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1622 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001623 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1624 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001625 UniqueSCEVs.InsertNode(S, IP);
1626 }
Dan Gohman3645b012009-10-09 00:10:36 +00001627 if (HasNUW) S->setHasNoUnsignedWrap(true);
1628 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001629 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001630}
1631
Dan Gohman6c0866c2009-05-24 23:45:28 +00001632/// getMulExpr - Get a canonical multiply expression, or something simpler if
1633/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001634const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1635 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001636 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001637 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001638#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001639 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001640 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001641 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001642 "SCEVMulExpr operand types don't match!");
1643#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001644
Dan Gohmana10756e2010-01-21 02:09:26 +00001645 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1646 if (!HasNUW && HasNSW) {
1647 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001648 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1649 E = Ops.end(); I != E; ++I)
1650 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001651 All = false;
1652 break;
1653 }
1654 if (All) HasNUW = true;
1655 }
1656
Chris Lattner53e677a2004-04-02 20:23:17 +00001657 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001658 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001659
1660 // If there are any constants, fold them together.
1661 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001662 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001663
1664 // C1*(C2+V) -> C1*C2 + C1*V
1665 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001666 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 if (Add->getNumOperands() == 2 &&
1668 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001669 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1670 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001671
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001673 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001674 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001675 ConstantInt *Fold = ConstantInt::get(getContext(),
1676 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001677 RHSC->getValue()->getValue());
1678 Ops[0] = getConstant(Fold);
1679 Ops.erase(Ops.begin()+1); // Erase the folded element
1680 if (Ops.size() == 1) return Ops[0];
1681 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 }
1683
1684 // If we are left with a constant one being multiplied, strip it off.
1685 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1686 Ops.erase(Ops.begin());
1687 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001688 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001689 // If we have a multiply of zero, it will always be zero.
1690 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001691 } else if (Ops[0]->isAllOnesValue()) {
1692 // If we have a mul by -1 of an add, try distributing the -1 among the
1693 // add operands.
1694 if (Ops.size() == 2)
1695 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1696 SmallVector<const SCEV *, 4> NewOps;
1697 bool AnyFolded = false;
1698 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1699 I != E; ++I) {
1700 const SCEV *Mul = getMulExpr(Ops[0], *I);
1701 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1702 NewOps.push_back(Mul);
1703 }
1704 if (AnyFolded)
1705 return getAddExpr(NewOps);
1706 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001708
1709 if (Ops.size() == 1)
1710 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001711 }
1712
1713 // Skip over the add expression until we get to a multiply.
1714 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1715 ++Idx;
1716
Chris Lattner53e677a2004-04-02 20:23:17 +00001717 // If there are mul operands inline them all into this expression.
1718 if (Idx < Ops.size()) {
1719 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001720 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001721 // If we have an mul, expand the mul operands onto the end of the operands
1722 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001724 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001725 DeletedMul = true;
1726 }
1727
1728 // If we deleted at least one mul, we added operands to the end of the list,
1729 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001730 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001731 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001732 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001733 }
1734
1735 // If there are any add recurrences in the operands list, see if any other
1736 // added values are loop invariant. If so, we can fold them into the
1737 // recurrence.
1738 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1739 ++Idx;
1740
1741 // Scan over all recurrences, trying to fold loop invariants into them.
1742 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1743 // Scan all of the other operands to this mul and add them to the vector if
1744 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001745 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001746 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001747 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001749 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001750 LIOps.push_back(Ops[i]);
1751 Ops.erase(Ops.begin()+i);
1752 --i; --e;
1753 }
1754
1755 // If we found some loop invariants, fold them into the recurrence.
1756 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001757 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001758 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001759 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001760 const SCEV *Scale = getMulExpr(LIOps);
1761 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1762 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001763
Dan Gohmanb9f96512010-06-30 07:16:37 +00001764 // Build the new addrec. Propagate the NUW and NSW flags if both the
1765 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohman0f32ae32010-08-29 14:55:19 +00001766 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop,
Dan Gohmana10756e2010-01-21 02:09:26 +00001767 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001768 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001769
1770 // If all of the other operands were loop invariant, we are done.
1771 if (Ops.size() == 1) return NewRec;
1772
1773 // Otherwise, multiply the folded AddRec by the non-liv parts.
1774 for (unsigned i = 0;; ++i)
1775 if (Ops[i] == AddRec) {
1776 Ops[i] = NewRec;
1777 break;
1778 }
Dan Gohman246b2562007-10-22 18:31:58 +00001779 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001780 }
1781
1782 // Okay, if there weren't any loop invariants to be folded, check to see if
1783 // there are multiple AddRec's with the same loop induction variable being
1784 // multiplied together. If so, we can fold them.
1785 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001786 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1787 ++OtherIdx)
1788 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1789 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1790 // {A*C,+,F*D + G*B + B*D}<L>
1791 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1792 ++OtherIdx)
1793 if (const SCEVAddRecExpr *OtherAddRec =
1794 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1795 if (OtherAddRec->getLoop() == AddRecLoop) {
1796 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1797 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1798 const SCEV *B = F->getStepRecurrence(*this);
1799 const SCEV *D = G->getStepRecurrence(*this);
1800 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1801 getMulExpr(G, B),
1802 getMulExpr(B, D));
1803 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1804 F->getLoop());
1805 if (Ops.size() == 2) return NewAddRec;
1806 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1807 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1808 }
1809 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001810 }
1811
1812 // Otherwise couldn't fold anything into this recurrence. Move onto the
1813 // next one.
1814 }
1815
1816 // Okay, it looks like we really DO need an mul expr. Check to see if we
1817 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001818 FoldingSetNodeID ID;
1819 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001820 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1821 ID.AddPointer(Ops[i]);
1822 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001823 SCEVMulExpr *S =
1824 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1825 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001826 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1827 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001828 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1829 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001830 UniqueSCEVs.InsertNode(S, IP);
1831 }
Dan Gohman3645b012009-10-09 00:10:36 +00001832 if (HasNUW) S->setHasNoUnsignedWrap(true);
1833 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001834 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001835}
1836
Andreas Bolka8a11c982009-08-07 22:55:26 +00001837/// getUDivExpr - Get a canonical unsigned division expression, or something
1838/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001839const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1840 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001841 assert(getEffectiveSCEVType(LHS->getType()) ==
1842 getEffectiveSCEVType(RHS->getType()) &&
1843 "SCEVUDivExpr operand types don't match!");
1844
Dan Gohman622ed672009-05-04 22:02:23 +00001845 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001846 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001847 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001848 // If the denominator is zero, the result of the udiv is undefined. Don't
1849 // try to analyze it, because the resolution chosen here may differ from
1850 // the resolution chosen in other parts of the compiler.
1851 if (!RHSC->getValue()->isZero()) {
1852 // Determine if the division can be folded into the operands of
1853 // its operands.
1854 // TODO: Generalize this to non-constants by using known-bits information.
1855 const Type *Ty = LHS->getType();
1856 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001857 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001858 // For non-power-of-two values, effectively round the value up to the
1859 // nearest power of two.
1860 if (!RHSC->getValue()->getValue().isPowerOf2())
1861 ++MaxShiftAmt;
1862 const IntegerType *ExtTy =
1863 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1864 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1865 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1866 if (const SCEVConstant *Step =
1867 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1868 if (!Step->getValue()->getValue()
1869 .urem(RHSC->getValue()->getValue()) &&
1870 getZeroExtendExpr(AR, ExtTy) ==
1871 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1872 getZeroExtendExpr(Step, ExtTy),
1873 AR->getLoop())) {
1874 SmallVector<const SCEV *, 4> Operands;
1875 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1876 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1877 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001878 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001879 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1880 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1881 SmallVector<const SCEV *, 4> Operands;
1882 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1883 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1884 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1885 // Find an operand that's safely divisible.
1886 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1887 const SCEV *Op = M->getOperand(i);
1888 const SCEV *Div = getUDivExpr(Op, RHSC);
1889 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1890 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1891 M->op_end());
1892 Operands[i] = Div;
1893 return getMulExpr(Operands);
1894 }
1895 }
Dan Gohman185cf032009-05-08 20:18:49 +00001896 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001897 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1898 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1899 SmallVector<const SCEV *, 4> Operands;
1900 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1901 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1902 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1903 Operands.clear();
1904 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1905 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1906 if (isa<SCEVUDivExpr>(Op) ||
1907 getMulExpr(Op, RHS) != A->getOperand(i))
1908 break;
1909 Operands.push_back(Op);
1910 }
1911 if (Operands.size() == A->getNumOperands())
1912 return getAddExpr(Operands);
1913 }
1914 }
Dan Gohman185cf032009-05-08 20:18:49 +00001915
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001916 // Fold if both operands are constant.
1917 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1918 Constant *LHSCV = LHSC->getValue();
1919 Constant *RHSCV = RHSC->getValue();
1920 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1921 RHSCV)));
1922 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001923 }
1924 }
1925
Dan Gohman1c343752009-06-27 21:21:31 +00001926 FoldingSetNodeID ID;
1927 ID.AddInteger(scUDivExpr);
1928 ID.AddPointer(LHS);
1929 ID.AddPointer(RHS);
1930 void *IP = 0;
1931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001932 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1933 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001934 UniqueSCEVs.InsertNode(S, IP);
1935 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001936}
1937
1938
Dan Gohman6c0866c2009-05-24 23:45:28 +00001939/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1940/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001941const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001942 const SCEV *Step, const Loop *L,
1943 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001944 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001945 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001946 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001948 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001949 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001950 }
1951
1952 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001953 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001954}
1955
Dan Gohman6c0866c2009-05-24 23:45:28 +00001956/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1957/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001958const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001959ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001960 const Loop *L,
1961 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001962 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001963#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001964 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001965 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001966 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001967 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00001968 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001969 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00001970 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001971#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001972
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001973 if (Operands.back()->isZero()) {
1974 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001975 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001976 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001977
Dan Gohmanbc028532010-02-19 18:49:22 +00001978 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1979 // use that information to infer NUW and NSW flags. However, computing a
1980 // BE count requires calling getAddRecExpr, so we may not yet have a
1981 // meaningful BE count at this point (and if we don't, we'd be stuck
1982 // with a SCEVCouldNotCompute as the cached BE count).
1983
Dan Gohmana10756e2010-01-21 02:09:26 +00001984 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1985 if (!HasNUW && HasNSW) {
1986 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001987 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
1988 E = Operands.end(); I != E; ++I)
1989 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001990 All = false;
1991 break;
1992 }
1993 if (All) HasNUW = true;
1994 }
1995
Dan Gohmand9cc7492008-08-08 18:33:12 +00001996 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001997 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001998 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00001999 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002000 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002001 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002002 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002003 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002004 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002005 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002006 // AddRecs require their operands be loop-invariant with respect to their
2007 // loops. Don't perform this transformation if it would break this
2008 // requirement.
2009 bool AllInvariant = true;
2010 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002011 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002012 AllInvariant = false;
2013 break;
2014 }
2015 if (AllInvariant) {
2016 NestedOperands[0] = getAddRecExpr(Operands, L);
2017 AllInvariant = true;
2018 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002019 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002020 AllInvariant = false;
2021 break;
2022 }
2023 if (AllInvariant)
2024 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002025 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002026 }
2027 // Reset Operands to its original state.
2028 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002029 }
2030 }
2031
Dan Gohman67847532010-01-19 22:27:22 +00002032 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2033 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002034 FoldingSetNodeID ID;
2035 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002036 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2037 ID.AddPointer(Operands[i]);
2038 ID.AddPointer(L);
2039 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002040 SCEVAddRecExpr *S =
2041 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2042 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002043 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2044 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002045 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2046 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002047 UniqueSCEVs.InsertNode(S, IP);
2048 }
Dan Gohman3645b012009-10-09 00:10:36 +00002049 if (HasNUW) S->setHasNoUnsignedWrap(true);
2050 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002051 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002052}
2053
Dan Gohman9311ef62009-06-24 14:49:00 +00002054const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2055 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002056 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002057 Ops.push_back(LHS);
2058 Ops.push_back(RHS);
2059 return getSMaxExpr(Ops);
2060}
2061
Dan Gohman0bba49c2009-07-07 17:06:11 +00002062const SCEV *
2063ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002064 assert(!Ops.empty() && "Cannot get empty smax!");
2065 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002066#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002067 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002068 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002069 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002070 "SCEVSMaxExpr operand types don't match!");
2071#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002072
2073 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002074 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002075
2076 // If there are any constants, fold them together.
2077 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002078 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002079 ++Idx;
2080 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002081 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002082 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002083 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002084 APIntOps::smax(LHSC->getValue()->getValue(),
2085 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002086 Ops[0] = getConstant(Fold);
2087 Ops.erase(Ops.begin()+1); // Erase the folded element
2088 if (Ops.size() == 1) return Ops[0];
2089 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002090 }
2091
Dan Gohmane5aceed2009-06-24 14:46:22 +00002092 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002093 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2094 Ops.erase(Ops.begin());
2095 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002096 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2097 // If we have an smax with a constant maximum-int, it will always be
2098 // maximum-int.
2099 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002100 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002101
Dan Gohman3ab13122010-04-13 16:49:23 +00002102 if (Ops.size() == 1) return Ops[0];
2103 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002104
2105 // Find the first SMax
2106 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2107 ++Idx;
2108
2109 // Check to see if one of the operands is an SMax. If so, expand its operands
2110 // onto our operand list, and recurse to simplify.
2111 if (Idx < Ops.size()) {
2112 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002113 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002114 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002115 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002116 DeletedSMax = true;
2117 }
2118
2119 if (DeletedSMax)
2120 return getSMaxExpr(Ops);
2121 }
2122
2123 // Okay, check to see if the same value occurs in the operand list twice. If
2124 // so, delete one. Since we sorted the list, these values are required to
2125 // be adjacent.
2126 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002127 // X smax Y smax Y --> X smax Y
2128 // X smax Y --> X, if X is always greater than Y
2129 if (Ops[i] == Ops[i+1] ||
2130 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2131 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2132 --i; --e;
2133 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002134 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2135 --i; --e;
2136 }
2137
2138 if (Ops.size() == 1) return Ops[0];
2139
2140 assert(!Ops.empty() && "Reduced smax down to nothing!");
2141
Nick Lewycky3e630762008-02-20 06:48:22 +00002142 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002143 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002144 FoldingSetNodeID ID;
2145 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002146 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2147 ID.AddPointer(Ops[i]);
2148 void *IP = 0;
2149 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002150 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2151 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002152 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2153 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002154 UniqueSCEVs.InsertNode(S, IP);
2155 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002156}
2157
Dan Gohman9311ef62009-06-24 14:49:00 +00002158const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2159 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002160 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002161 Ops.push_back(LHS);
2162 Ops.push_back(RHS);
2163 return getUMaxExpr(Ops);
2164}
2165
Dan Gohman0bba49c2009-07-07 17:06:11 +00002166const SCEV *
2167ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002168 assert(!Ops.empty() && "Cannot get empty umax!");
2169 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002170#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002171 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002172 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002173 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002174 "SCEVUMaxExpr operand types don't match!");
2175#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002176
2177 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002178 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002179
2180 // If there are any constants, fold them together.
2181 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002182 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002183 ++Idx;
2184 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002185 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002186 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002187 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002188 APIntOps::umax(LHSC->getValue()->getValue(),
2189 RHSC->getValue()->getValue()));
2190 Ops[0] = getConstant(Fold);
2191 Ops.erase(Ops.begin()+1); // Erase the folded element
2192 if (Ops.size() == 1) return Ops[0];
2193 LHSC = cast<SCEVConstant>(Ops[0]);
2194 }
2195
Dan Gohmane5aceed2009-06-24 14:46:22 +00002196 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002197 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2198 Ops.erase(Ops.begin());
2199 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002200 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2201 // If we have an umax with a constant maximum-int, it will always be
2202 // maximum-int.
2203 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002204 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002205
Dan Gohman3ab13122010-04-13 16:49:23 +00002206 if (Ops.size() == 1) return Ops[0];
2207 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002208
2209 // Find the first UMax
2210 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2211 ++Idx;
2212
2213 // Check to see if one of the operands is a UMax. If so, expand its operands
2214 // onto our operand list, and recurse to simplify.
2215 if (Idx < Ops.size()) {
2216 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002217 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002218 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002219 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002220 DeletedUMax = true;
2221 }
2222
2223 if (DeletedUMax)
2224 return getUMaxExpr(Ops);
2225 }
2226
2227 // Okay, check to see if the same value occurs in the operand list twice. If
2228 // so, delete one. Since we sorted the list, these values are required to
2229 // be adjacent.
2230 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002231 // X umax Y umax Y --> X umax Y
2232 // X umax Y --> X, if X is always greater than Y
2233 if (Ops[i] == Ops[i+1] ||
2234 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2235 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2236 --i; --e;
2237 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002238 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2239 --i; --e;
2240 }
2241
2242 if (Ops.size() == 1) return Ops[0];
2243
2244 assert(!Ops.empty() && "Reduced umax down to nothing!");
2245
2246 // Okay, it looks like we really DO need a umax expr. Check to see if we
2247 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002248 FoldingSetNodeID ID;
2249 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002250 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2251 ID.AddPointer(Ops[i]);
2252 void *IP = 0;
2253 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002254 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2255 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002256 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2257 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002258 UniqueSCEVs.InsertNode(S, IP);
2259 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002260}
2261
Dan Gohman9311ef62009-06-24 14:49:00 +00002262const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2263 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002264 // ~smax(~x, ~y) == smin(x, y).
2265 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2266}
2267
Dan Gohman9311ef62009-06-24 14:49:00 +00002268const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2269 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002270 // ~umax(~x, ~y) == umin(x, y)
2271 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2272}
2273
Dan Gohman4f8eea82010-02-01 18:27:38 +00002274const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002275 // If we have TargetData, we can bypass creating a target-independent
2276 // constant expression and then folding it back into a ConstantInt.
2277 // This is just a compile-time optimization.
2278 if (TD)
2279 return getConstant(TD->getIntPtrType(getContext()),
2280 TD->getTypeAllocSize(AllocTy));
2281
Dan Gohman4f8eea82010-02-01 18:27:38 +00002282 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2283 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002284 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2285 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002286 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2287 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2288}
2289
2290const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2291 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2292 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002293 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2294 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002295 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2296 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2297}
2298
2299const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2300 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002301 // If we have TargetData, we can bypass creating a target-independent
2302 // constant expression and then folding it back into a ConstantInt.
2303 // This is just a compile-time optimization.
2304 if (TD)
2305 return getConstant(TD->getIntPtrType(getContext()),
2306 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2307
Dan Gohman0f5efe52010-01-28 02:15:55 +00002308 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2309 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002310 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2311 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002312 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002313 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002314}
2315
Dan Gohman4f8eea82010-02-01 18:27:38 +00002316const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2317 Constant *FieldNo) {
2318 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002320 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2321 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002322 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002323 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002324}
2325
Dan Gohman0bba49c2009-07-07 17:06:11 +00002326const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002327 // Don't attempt to do anything other than create a SCEVUnknown object
2328 // here. createSCEV only calls getUnknown after checking for all other
2329 // interesting possibilities, and any other code that calls getUnknown
2330 // is doing so in order to hide a value from SCEV canonicalization.
2331
Dan Gohman1c343752009-06-27 21:21:31 +00002332 FoldingSetNodeID ID;
2333 ID.AddInteger(scUnknown);
2334 ID.AddPointer(V);
2335 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002336 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2337 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2338 "Stale SCEVUnknown in uniquing map!");
2339 return S;
2340 }
2341 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2342 FirstUnknown);
2343 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002344 UniqueSCEVs.InsertNode(S, IP);
2345 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002346}
2347
Chris Lattner53e677a2004-04-02 20:23:17 +00002348//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002349// Basic SCEV Analysis and PHI Idiom Recognition Code
2350//
2351
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002352/// isSCEVable - Test if values of the given type are analyzable within
2353/// the SCEV framework. This primarily includes integer types, and it
2354/// can optionally include pointer types if the ScalarEvolution class
2355/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002356bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002357 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002358 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002359}
2360
2361/// getTypeSizeInBits - Return the size in bits of the specified type,
2362/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002363uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002364 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2365
2366 // If we have a TargetData, use it!
2367 if (TD)
2368 return TD->getTypeSizeInBits(Ty);
2369
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002370 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002371 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002372 return Ty->getPrimitiveSizeInBits();
2373
2374 // The only other support type is pointer. Without TargetData, conservatively
2375 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002376 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002377 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002378}
2379
2380/// getEffectiveSCEVType - Return a type with the same bitwidth as
2381/// the given type and which represents how SCEV will treat the given
2382/// type, for which isSCEVable must return true. For pointer types,
2383/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002384const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002385 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2386
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002387 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002388 return Ty;
2389
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002390 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002391 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002392 if (TD) return TD->getIntPtrType(getContext());
2393
2394 // Without TargetData, conservatively assume pointers are 64-bit.
2395 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002396}
Chris Lattner53e677a2004-04-02 20:23:17 +00002397
Dan Gohman0bba49c2009-07-07 17:06:11 +00002398const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002399 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002400}
2401
Chris Lattner53e677a2004-04-02 20:23:17 +00002402/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2403/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002404const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002405 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002406
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002407 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2408 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002409 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002410
2411 // The process of creating a SCEV for V may have caused other SCEVs
2412 // to have been created, so it's necessary to insert the new entry
2413 // from scratch, rather than trying to remember the insert position
2414 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002415 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002416 return S;
2417}
2418
Dan Gohman2d1be872009-04-16 03:18:22 +00002419/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2420///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002421const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002422 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002423 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002424 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002425
2426 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002427 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002428 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002429 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002430}
2431
2432/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002433const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002434 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002435 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002436 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002437
2438 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002439 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002440 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002441 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002442 return getMinusSCEV(AllOnes, V);
2443}
2444
2445/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2446///
Dan Gohman9311ef62009-06-24 14:49:00 +00002447const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2448 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002449 // Fast path: X - X --> 0.
2450 if (LHS == RHS)
2451 return getConstant(LHS->getType(), 0);
2452
Dan Gohman2d1be872009-04-16 03:18:22 +00002453 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002454 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002455}
2456
2457/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2458/// input value to the specified type. If the type must be extended, it is zero
2459/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002460const SCEV *
2461ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002462 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002463 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002464 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2465 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002466 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002467 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002468 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002469 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002470 return getTruncateExpr(V, Ty);
2471 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002472}
2473
2474/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2475/// input value to the specified type. If the type must be extended, it is sign
2476/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002477const SCEV *
2478ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002479 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +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 Gohman2d1be872009-04-16 03:18:22 +00002483 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002484 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002485 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002486 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002487 return getTruncateExpr(V, Ty);
2488 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002489}
2490
Dan Gohman467c4302009-05-13 03:46:30 +00002491/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2492/// input value to the specified type. If the type must be extended, it is zero
2493/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002494const SCEV *
2495ScalarEvolution::getNoopOrZeroExtend(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 zero extend with non-integer arguments!");
2500 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2501 "getNoopOrZeroExtend cannot truncate!");
2502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2503 return V; // No conversion
2504 return getZeroExtendExpr(V, Ty);
2505}
2506
2507/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2508/// input value to the specified type. If the type must be extended, it is sign
2509/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002510const SCEV *
2511ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002512 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002513 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2514 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002515 "Cannot noop or sign extend with non-integer arguments!");
2516 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2517 "getNoopOrSignExtend cannot truncate!");
2518 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2519 return V; // No conversion
2520 return getSignExtendExpr(V, Ty);
2521}
2522
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002523/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2524/// the input value to the specified type. If the type must be extended,
2525/// it is extended with unspecified bits. The conversion must not be
2526/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002527const SCEV *
2528ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002529 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002530 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2531 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002532 "Cannot noop or any extend with non-integer arguments!");
2533 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2534 "getNoopOrAnyExtend cannot truncate!");
2535 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2536 return V; // No conversion
2537 return getAnyExtendExpr(V, Ty);
2538}
2539
Dan Gohman467c4302009-05-13 03:46:30 +00002540/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2541/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002542const SCEV *
2543ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002544 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002545 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2546 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002547 "Cannot truncate or noop with non-integer arguments!");
2548 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2549 "getTruncateOrNoop cannot extend!");
2550 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2551 return V; // No conversion
2552 return getTruncateExpr(V, Ty);
2553}
2554
Dan Gohmana334aa72009-06-22 00:31:57 +00002555/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2556/// the types using zero-extension, and then perform a umax operation
2557/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002558const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(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 Gohmana334aa72009-06-22 00:31:57 +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 getUMaxExpr(PromotedLHS, PromotedRHS);
2569}
2570
Dan Gohmanc9759e82009-06-22 15:03:27 +00002571/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2572/// the types using zero-extension, and then perform a umin operation
2573/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002574const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2575 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002576 const SCEV *PromotedLHS = LHS;
2577 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002578
2579 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2580 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2581 else
2582 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2583
2584 return getUMinExpr(PromotedLHS, PromotedRHS);
2585}
2586
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002587/// PushDefUseChildren - Push users of the given Instruction
2588/// onto the given Worklist.
2589static void
2590PushDefUseChildren(Instruction *I,
2591 SmallVectorImpl<Instruction *> &Worklist) {
2592 // Push the def-use children onto the Worklist stack.
2593 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2594 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002595 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002596}
2597
2598/// ForgetSymbolicValue - This looks up computed SCEV values for all
2599/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002600/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002601/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002602void
Dan Gohman85669632010-02-25 06:57:05 +00002603ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002604 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002605 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002606
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002607 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002608 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002609 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002610 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002611 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002612
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002613 ValueExprMapType::iterator It =
2614 ValueExprMap.find(static_cast<Value *>(I));
2615 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002616 const SCEV *Old = It->second;
2617
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002618 // Short-circuit the def-use traversal if the symbolic name
2619 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002620 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002621 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002622
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002623 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002624 // structure, it's a PHI that's in the progress of being computed
2625 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2626 // additional loop trip count information isn't going to change anything.
2627 // In the second case, createNodeForPHI will perform the necessary
2628 // updates on its own when it gets to that point. In the third, we do
2629 // want to forget the SCEVUnknown.
2630 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002631 !isa<SCEVUnknown>(Old) ||
2632 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002633 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002634 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002635 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002636 }
2637
2638 PushDefUseChildren(I, Worklist);
2639 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002640}
Chris Lattner53e677a2004-04-02 20:23:17 +00002641
2642/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2643/// a loop header, making it a potential recurrence, or it doesn't.
2644///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002645const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002646 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2647 if (L->getHeader() == PN->getParent()) {
2648 // The loop may have multiple entrances or multiple exits; we can analyze
2649 // this phi as an addrec if it has a unique entry value and a unique
2650 // backedge value.
2651 Value *BEValueV = 0, *StartValueV = 0;
2652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2653 Value *V = PN->getIncomingValue(i);
2654 if (L->contains(PN->getIncomingBlock(i))) {
2655 if (!BEValueV) {
2656 BEValueV = V;
2657 } else if (BEValueV != V) {
2658 BEValueV = 0;
2659 break;
2660 }
2661 } else if (!StartValueV) {
2662 StartValueV = V;
2663 } else if (StartValueV != V) {
2664 StartValueV = 0;
2665 break;
2666 }
2667 }
2668 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002669 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002670 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002671 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002672 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002673 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002674
2675 // Using this symbolic name for the PHI, analyze the value coming around
2676 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002677 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002678
2679 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2680 // has a special value for the first iteration of the loop.
2681
2682 // If the value coming around the backedge is an add with the symbolic
2683 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002684 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002685 // If there is a single occurrence of the symbolic value, replace it
2686 // with a recurrence.
2687 unsigned FoundIndex = Add->getNumOperands();
2688 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2689 if (Add->getOperand(i) == SymbolicName)
2690 if (FoundIndex == e) {
2691 FoundIndex = i;
2692 break;
2693 }
2694
2695 if (FoundIndex != Add->getNumOperands()) {
2696 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002697 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002698 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2699 if (i != FoundIndex)
2700 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002701 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002702
2703 // This is not a valid addrec if the step amount is varying each
2704 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002705 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002706 (isa<SCEVAddRecExpr>(Accum) &&
2707 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002708 bool HasNUW = false;
2709 bool HasNSW = false;
2710
2711 // If the increment doesn't overflow, then neither the addrec nor
2712 // the post-increment will overflow.
2713 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2714 if (OBO->hasNoUnsignedWrap())
2715 HasNUW = true;
2716 if (OBO->hasNoSignedWrap())
2717 HasNSW = true;
2718 }
2719
Dan Gohman27dead42010-04-12 07:49:36 +00002720 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002721 const SCEV *PHISCEV =
2722 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002723
Dan Gohmana10756e2010-01-21 02:09:26 +00002724 // Since the no-wrap flags are on the increment, they apply to the
2725 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002726 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002727 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2728 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002729
2730 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002731 // to be symbolic. We now need to go back and purge all of the
2732 // entries for the scalars that use the symbolic expression.
2733 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002734 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002735 return PHISCEV;
2736 }
2737 }
Dan Gohman622ed672009-05-04 22:02:23 +00002738 } else if (const SCEVAddRecExpr *AddRec =
2739 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002740 // Otherwise, this could be a loop like this:
2741 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2742 // In this case, j = {1,+,1} and BEValue is j.
2743 // Because the other in-value of i (0) fits the evolution of BEValue
2744 // i really is an addrec evolution.
2745 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002746 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002747
2748 // If StartVal = j.start - j.stride, we can use StartVal as the
2749 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002750 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002751 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002752 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002753 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002754
2755 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002756 // to be symbolic. We now need to go back and purge all of the
2757 // entries for the scalars that use the symbolic expression.
2758 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002759 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002760 return PHISCEV;
2761 }
2762 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002763 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002764 }
Dan Gohman27dead42010-04-12 07:49:36 +00002765 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002766
Dan Gohman85669632010-02-25 06:57:05 +00002767 // If the PHI has a single incoming value, follow that value, unless the
2768 // PHI's incoming blocks are in a different loop, in which case doing so
2769 // risks breaking LCSSA form. Instcombine would normally zap these, but
2770 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsa0c52442010-11-17 04:18:45 +00002771 if (Value *V = SimplifyInstruction(PN, TD, DT)) {
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002772 Instruction *I = dyn_cast<Instruction>(V);
2773 // Only instructions are problematic for preserving LCSSA form.
2774 if (!I)
Dan Gohman85669632010-02-25 06:57:05 +00002775 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002776
2777 // If the instruction is not defined in a loop, then it can be used freely.
2778 Loop *ILoop = LI->getLoopFor(I->getParent());
2779 if (!ILoop)
2780 return getSCEV(I);
2781
2782 // If the instruction is defined in the same loop as the phi node, or in a
2783 // loop that contains the phi node loop as an inner loop, then using it as
2784 // a replacement for the phi node will not break LCSSA form.
2785 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2786 if (ILoop->contains(PNLoop))
2787 return getSCEV(I);
Dan Gohman85669632010-02-25 06:57:05 +00002788 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002789
Chris Lattner53e677a2004-04-02 20:23:17 +00002790 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002791 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002792}
2793
Dan Gohman26466c02009-05-08 20:26:55 +00002794/// createNodeForGEP - Expand GEP instructions into add and multiply
2795/// operations. This allows them to be analyzed by regular SCEV code.
2796///
Dan Gohmand281ed22009-12-18 02:09:29 +00002797const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002798
Dan Gohmanb9f96512010-06-30 07:16:37 +00002799 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2800 // Add expression, because the Instruction may be guarded by control flow
2801 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002802 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002803
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002804 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002805 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002806 // Don't attempt to analyze GEPs over unsized objects.
2807 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2808 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002809 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002810 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002811 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002812 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002813 I != E; ++I) {
2814 Value *Index = *I;
2815 // Compute the (potentially symbolic) offset in bytes for this index.
2816 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2817 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002818 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002819 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2820
Dan Gohmanb9f96512010-06-30 07:16:37 +00002821 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002822 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002823 } else {
2824 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002825 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2826 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002827 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002828 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2829
Dan Gohmanb9f96512010-06-30 07:16:37 +00002830 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002831 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002832
2833 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002834 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002835 }
2836 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002837
2838 // Get the SCEV for the GEP base.
2839 const SCEV *BaseS = getSCEV(Base);
2840
Dan Gohmanb9f96512010-06-30 07:16:37 +00002841 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002842 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002843}
2844
Nick Lewycky83bb0052007-11-22 07:59:40 +00002845/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2846/// guaranteed to end in (at every loop iteration). It is, at the same time,
2847/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2848/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002849uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002850ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002851 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002852 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002853
Dan Gohman622ed672009-05-04 22:02:23 +00002854 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002855 return std::min(GetMinTrailingZeros(T->getOperand()),
2856 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002857
Dan Gohman622ed672009-05-04 22:02:23 +00002858 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002859 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2860 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2861 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002862 }
2863
Dan Gohman622ed672009-05-04 22:02:23 +00002864 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002865 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2866 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2867 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002868 }
2869
Dan Gohman622ed672009-05-04 22:02:23 +00002870 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002871 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002872 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002873 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002874 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002875 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002876 }
2877
Dan Gohman622ed672009-05-04 22:02:23 +00002878 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002879 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002880 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2881 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002882 for (unsigned i = 1, e = M->getNumOperands();
2883 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002884 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002885 BitWidth);
2886 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002887 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002888
Dan Gohman622ed672009-05-04 22:02:23 +00002889 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002890 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002891 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002892 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002893 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002894 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002895 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002896
Dan Gohman622ed672009-05-04 22:02:23 +00002897 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002898 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002899 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002900 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002901 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002902 return MinOpRes;
2903 }
2904
Dan Gohman622ed672009-05-04 22:02:23 +00002905 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002906 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002907 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002908 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002909 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002910 return MinOpRes;
2911 }
2912
Dan Gohman2c364ad2009-06-19 23:29:04 +00002913 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2914 // For a SCEVUnknown, ask ValueTracking.
2915 unsigned BitWidth = getTypeSizeInBits(U->getType());
2916 APInt Mask = APInt::getAllOnesValue(BitWidth);
2917 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2918 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2919 return Zeros.countTrailingOnes();
2920 }
2921
2922 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002923 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002924}
Chris Lattner53e677a2004-04-02 20:23:17 +00002925
Dan Gohman85b05a22009-07-13 21:35:55 +00002926/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2927///
2928ConstantRange
2929ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002930 // See if we've computed this range already.
2931 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
2932 if (I != UnsignedRanges.end())
2933 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002934
2935 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002936 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002937
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002938 unsigned BitWidth = getTypeSizeInBits(S->getType());
2939 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2940
2941 // If the value has known zeros, the maximum unsigned value will have those
2942 // known zeros as well.
2943 uint32_t TZ = GetMinTrailingZeros(S);
2944 if (TZ != 0)
2945 ConservativeResult =
2946 ConstantRange(APInt::getMinValue(BitWidth),
2947 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2948
Dan Gohman85b05a22009-07-13 21:35:55 +00002949 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2950 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2951 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2952 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002953 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002954 }
2955
2956 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2957 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2958 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2959 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002960 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002961 }
2962
2963 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2964 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2965 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2966 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002967 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002968 }
2969
2970 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2971 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2972 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2973 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002974 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002975 }
2976
2977 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2978 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2979 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002980 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002981 }
2982
2983 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2984 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002985 return setUnsignedRange(ZExt,
2986 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002987 }
2988
2989 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2990 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002991 return setUnsignedRange(SExt,
2992 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002993 }
2994
2995 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2996 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002997 return setUnsignedRange(Trunc,
2998 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002999 }
3000
Dan Gohman85b05a22009-07-13 21:35:55 +00003001 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003002 // If there's no unsigned wrap, the value will never be less than its
3003 // initial value.
3004 if (AddRec->hasNoUnsignedWrap())
3005 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003006 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003007 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003008 ConservativeResult.intersectWith(
3009 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003010
3011 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003012 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003013 const Type *Ty = AddRec->getType();
3014 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003015 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3016 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003017 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3018
3019 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003020 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003021
3022 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003023 ConstantRange StepRange = getSignedRange(Step);
3024 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3025 ConstantRange EndRange =
3026 StartRange.add(MaxBECountRange.multiply(StepRange));
3027
3028 // Check for overflow. This must be done with ConstantRange arithmetic
3029 // because we could be called from within the ScalarEvolution overflow
3030 // checking code.
3031 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3032 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3033 ConstantRange ExtMaxBECountRange =
3034 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3035 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3036 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3037 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003038 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003039
Dan Gohman85b05a22009-07-13 21:35:55 +00003040 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3041 EndRange.getUnsignedMin());
3042 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3043 EndRange.getUnsignedMax());
3044 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003045 return setUnsignedRange(AddRec, ConservativeResult);
3046 return setUnsignedRange(AddRec,
3047 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003048 }
3049 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003050
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003051 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003052 }
3053
3054 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3055 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003056 APInt Mask = APInt::getAllOnesValue(BitWidth);
3057 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3058 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003059 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003060 return setUnsignedRange(U, ConservativeResult);
3061 return setUnsignedRange(U,
3062 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003063 }
3064
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003065 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003066}
3067
Dan Gohman85b05a22009-07-13 21:35:55 +00003068/// getSignedRange - Determine the signed range for a particular SCEV.
3069///
3070ConstantRange
3071ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003072 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3073 if (I != SignedRanges.end())
3074 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003075
Dan Gohman85b05a22009-07-13 21:35:55 +00003076 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003077 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003078
Dan Gohman52fddd32010-01-26 04:40:18 +00003079 unsigned BitWidth = getTypeSizeInBits(S->getType());
3080 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3081
3082 // If the value has known zeros, the maximum signed value will have those
3083 // known zeros as well.
3084 uint32_t TZ = GetMinTrailingZeros(S);
3085 if (TZ != 0)
3086 ConservativeResult =
3087 ConstantRange(APInt::getSignedMinValue(BitWidth),
3088 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3089
Dan Gohman85b05a22009-07-13 21:35:55 +00003090 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3091 ConstantRange X = getSignedRange(Add->getOperand(0));
3092 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3093 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003094 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003095 }
3096
Dan Gohman85b05a22009-07-13 21:35:55 +00003097 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3098 ConstantRange X = getSignedRange(Mul->getOperand(0));
3099 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3100 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003101 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003102 }
3103
Dan Gohman85b05a22009-07-13 21:35:55 +00003104 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3105 ConstantRange X = getSignedRange(SMax->getOperand(0));
3106 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3107 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003108 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003109 }
Dan Gohman62849c02009-06-24 01:05:09 +00003110
Dan Gohman85b05a22009-07-13 21:35:55 +00003111 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3112 ConstantRange X = getSignedRange(UMax->getOperand(0));
3113 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3114 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003115 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003116 }
Dan Gohman62849c02009-06-24 01:05:09 +00003117
Dan Gohman85b05a22009-07-13 21:35:55 +00003118 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3119 ConstantRange X = getSignedRange(UDiv->getLHS());
3120 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003121 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003122 }
Dan Gohman62849c02009-06-24 01:05:09 +00003123
Dan Gohman85b05a22009-07-13 21:35:55 +00003124 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3125 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003126 return setSignedRange(ZExt,
3127 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003128 }
3129
3130 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3131 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003132 return setSignedRange(SExt,
3133 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003134 }
3135
3136 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3137 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003138 return setSignedRange(Trunc,
3139 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003140 }
3141
Dan Gohman85b05a22009-07-13 21:35:55 +00003142 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003143 // If there's no signed wrap, and all the operands have the same sign or
3144 // zero, the value won't ever change sign.
3145 if (AddRec->hasNoSignedWrap()) {
3146 bool AllNonNeg = true;
3147 bool AllNonPos = true;
3148 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3149 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3150 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3151 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003152 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003153 ConservativeResult = ConservativeResult.intersectWith(
3154 ConstantRange(APInt(BitWidth, 0),
3155 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003156 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003157 ConservativeResult = ConservativeResult.intersectWith(
3158 ConstantRange(APInt::getSignedMinValue(BitWidth),
3159 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003160 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003161
3162 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003163 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003164 const Type *Ty = AddRec->getType();
3165 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003166 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3167 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003168 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3169
3170 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003171 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003172
3173 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003174 ConstantRange StepRange = getSignedRange(Step);
3175 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3176 ConstantRange EndRange =
3177 StartRange.add(MaxBECountRange.multiply(StepRange));
3178
3179 // Check for overflow. This must be done with ConstantRange arithmetic
3180 // because we could be called from within the ScalarEvolution overflow
3181 // checking code.
3182 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3183 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3184 ConstantRange ExtMaxBECountRange =
3185 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3186 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3187 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3188 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003189 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003190
Dan Gohman85b05a22009-07-13 21:35:55 +00003191 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3192 EndRange.getSignedMin());
3193 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3194 EndRange.getSignedMax());
3195 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003196 return setSignedRange(AddRec, ConservativeResult);
3197 return setSignedRange(AddRec,
3198 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003199 }
Dan Gohman62849c02009-06-24 01:05:09 +00003200 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003201
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003202 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003203 }
3204
Dan Gohman2c364ad2009-06-19 23:29:04 +00003205 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3206 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003207 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003208 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003209 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3210 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003211 return setSignedRange(U, ConservativeResult);
3212 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003213 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003214 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003215 }
3216
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003217 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003218}
3219
Chris Lattner53e677a2004-04-02 20:23:17 +00003220/// createSCEV - We know that there is no SCEV for the specified value.
3221/// Analyze the expression.
3222///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003223const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003224 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003225 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003226
Dan Gohman6c459a22008-06-22 19:56:46 +00003227 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003228 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003229 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003230
3231 // Don't attempt to analyze instructions in blocks that aren't
3232 // reachable. Such instructions don't matter, and they aren't required
3233 // to obey basic rules for definitions dominating uses which this
3234 // analysis depends on.
3235 if (!DT->isReachableFromEntry(I->getParent()))
3236 return getUnknown(V);
3237 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003238 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003239 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3240 return getConstant(CI);
3241 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003242 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003243 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3244 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003245 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003246 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003247
Dan Gohmanca178902009-07-17 20:47:02 +00003248 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003249 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003250 case Instruction::Add: {
3251 // The simple thing to do would be to just call getSCEV on both operands
3252 // and call getAddExpr with the result. However if we're looking at a
3253 // bunch of things all added together, this can be quite inefficient,
3254 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3255 // Instead, gather up all the operands and make a single getAddExpr call.
3256 // LLVM IR canonical form means we need only traverse the left operands.
3257 SmallVector<const SCEV *, 4> AddOps;
3258 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003259 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3260 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3261 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3262 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003263 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003264 const SCEV *Op1 = getSCEV(U->getOperand(1));
3265 if (Opcode == Instruction::Sub)
3266 AddOps.push_back(getNegativeSCEV(Op1));
3267 else
3268 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003269 }
3270 AddOps.push_back(getSCEV(U->getOperand(0)));
3271 return getAddExpr(AddOps);
3272 }
3273 case Instruction::Mul: {
3274 // See the Add code above.
3275 SmallVector<const SCEV *, 4> MulOps;
3276 MulOps.push_back(getSCEV(U->getOperand(1)));
3277 for (Value *Op = U->getOperand(0);
3278 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3279 Op = U->getOperand(0)) {
3280 U = cast<Operator>(Op);
3281 MulOps.push_back(getSCEV(U->getOperand(1)));
3282 }
3283 MulOps.push_back(getSCEV(U->getOperand(0)));
3284 return getMulExpr(MulOps);
3285 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003286 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003287 return getUDivExpr(getSCEV(U->getOperand(0)),
3288 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003289 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003290 return getMinusSCEV(getSCEV(U->getOperand(0)),
3291 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003292 case Instruction::And:
3293 // For an expression like x&255 that merely masks off the high bits,
3294 // use zext(trunc(x)) as the SCEV expression.
3295 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003296 if (CI->isNullValue())
3297 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003298 if (CI->isAllOnesValue())
3299 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003300 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003301
3302 // Instcombine's ShrinkDemandedConstant may strip bits out of
3303 // constants, obscuring what would otherwise be a low-bits mask.
3304 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3305 // knew about to reconstruct a low-bits mask value.
3306 unsigned LZ = A.countLeadingZeros();
3307 unsigned BitWidth = A.getBitWidth();
3308 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3309 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3310 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3311
3312 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3313
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003314 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003315 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003316 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003317 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003318 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003319 }
3320 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003321
Dan Gohman6c459a22008-06-22 19:56:46 +00003322 case Instruction::Or:
3323 // If the RHS of the Or is a constant, we may have something like:
3324 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3325 // optimizations will transparently handle this case.
3326 //
3327 // In order for this transformation to be safe, the LHS must be of the
3328 // form X*(2^n) and the Or constant must be less than 2^n.
3329 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003330 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003331 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003332 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003333 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3334 // Build a plain add SCEV.
3335 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3336 // If the LHS of the add was an addrec and it has no-wrap flags,
3337 // transfer the no-wrap flags, since an or won't introduce a wrap.
3338 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3339 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3340 if (OldAR->hasNoUnsignedWrap())
3341 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3342 if (OldAR->hasNoSignedWrap())
3343 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3344 }
3345 return S;
3346 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003347 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003348 break;
3349 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003350 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003351 // If the RHS of the xor is a signbit, then this is just an add.
3352 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003353 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003354 return getAddExpr(getSCEV(U->getOperand(0)),
3355 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003356
3357 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003358 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003359 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003360
3361 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3362 // This is a variant of the check for xor with -1, and it handles
3363 // the case where instcombine has trimmed non-demanded bits out
3364 // of an xor with -1.
3365 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3366 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3367 if (BO->getOpcode() == Instruction::And &&
3368 LCI->getValue() == CI->getValue())
3369 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003370 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003371 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003372 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003373 const Type *Z0Ty = Z0->getType();
3374 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3375
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003376 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003377 // mask off the high bits. Complement the operand and
3378 // re-apply the zext.
3379 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3380 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3381
3382 // If C is a single bit, it may be in the sign-bit position
3383 // before the zero-extend. In this case, represent the xor
3384 // using an add, which is equivalent, and re-apply the zext.
3385 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3386 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3387 Trunc.isSignBit())
3388 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3389 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003390 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003391 }
3392 break;
3393
3394 case Instruction::Shl:
3395 // Turn shift left of a constant amount into a multiply.
3396 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003397 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003398
3399 // If the shift count is not less than the bitwidth, the result of
3400 // the shift is undefined. Don't try to analyze it, because the
3401 // resolution chosen here may differ from the resolution chosen in
3402 // other parts of the compiler.
3403 if (SA->getValue().uge(BitWidth))
3404 break;
3405
Owen Andersoneed707b2009-07-24 23:12:02 +00003406 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003407 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003408 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003409 }
3410 break;
3411
Nick Lewycky01eaf802008-07-07 06:15:49 +00003412 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003413 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003414 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003415 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003416
3417 // If the shift count is not less than the bitwidth, the result of
3418 // the shift is undefined. Don't try to analyze it, because the
3419 // resolution chosen here may differ from the resolution chosen in
3420 // other parts of the compiler.
3421 if (SA->getValue().uge(BitWidth))
3422 break;
3423
Owen Andersoneed707b2009-07-24 23:12:02 +00003424 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003425 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003426 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003427 }
3428 break;
3429
Dan Gohman4ee29af2009-04-21 02:26:00 +00003430 case Instruction::AShr:
3431 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3432 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003433 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003434 if (L->getOpcode() == Instruction::Shl &&
3435 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003436 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3437
3438 // If the shift count is not less than the bitwidth, the result of
3439 // the shift is undefined. Don't try to analyze it, because the
3440 // resolution chosen here may differ from the resolution chosen in
3441 // other parts of the compiler.
3442 if (CI->getValue().uge(BitWidth))
3443 break;
3444
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003445 uint64_t Amt = BitWidth - CI->getZExtValue();
3446 if (Amt == BitWidth)
3447 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003448 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003449 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003450 IntegerType::get(getContext(),
3451 Amt)),
3452 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003453 }
3454 break;
3455
Dan Gohman6c459a22008-06-22 19:56:46 +00003456 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003457 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003458
3459 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003460 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003461
3462 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003463 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003464
3465 case Instruction::BitCast:
3466 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003467 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003468 return getSCEV(U->getOperand(0));
3469 break;
3470
Dan Gohman4f8eea82010-02-01 18:27:38 +00003471 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3472 // lead to pointer expressions which cannot safely be expanded to GEPs,
3473 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3474 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003475
Dan Gohman26466c02009-05-08 20:26:55 +00003476 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003477 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003478
Dan Gohman6c459a22008-06-22 19:56:46 +00003479 case Instruction::PHI:
3480 return createNodeForPHI(cast<PHINode>(U));
3481
3482 case Instruction::Select:
3483 // This could be a smax or umax that was lowered earlier.
3484 // Try to recover it.
3485 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3486 Value *LHS = ICI->getOperand(0);
3487 Value *RHS = ICI->getOperand(1);
3488 switch (ICI->getPredicate()) {
3489 case ICmpInst::ICMP_SLT:
3490 case ICmpInst::ICMP_SLE:
3491 std::swap(LHS, RHS);
3492 // fall through
3493 case ICmpInst::ICMP_SGT:
3494 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003495 // a >s b ? a+x : b+x -> smax(a, b)+x
3496 // a >s b ? b+x : a+x -> smin(a, b)+x
3497 if (LHS->getType() == U->getType()) {
3498 const SCEV *LS = getSCEV(LHS);
3499 const SCEV *RS = getSCEV(RHS);
3500 const SCEV *LA = getSCEV(U->getOperand(1));
3501 const SCEV *RA = getSCEV(U->getOperand(2));
3502 const SCEV *LDiff = getMinusSCEV(LA, LS);
3503 const SCEV *RDiff = getMinusSCEV(RA, RS);
3504 if (LDiff == RDiff)
3505 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3506 LDiff = getMinusSCEV(LA, RS);
3507 RDiff = getMinusSCEV(RA, LS);
3508 if (LDiff == RDiff)
3509 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3510 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003511 break;
3512 case ICmpInst::ICMP_ULT:
3513 case ICmpInst::ICMP_ULE:
3514 std::swap(LHS, RHS);
3515 // fall through
3516 case ICmpInst::ICMP_UGT:
3517 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003518 // a >u b ? a+x : b+x -> umax(a, b)+x
3519 // a >u b ? b+x : a+x -> umin(a, b)+x
3520 if (LHS->getType() == U->getType()) {
3521 const SCEV *LS = getSCEV(LHS);
3522 const SCEV *RS = getSCEV(RHS);
3523 const SCEV *LA = getSCEV(U->getOperand(1));
3524 const SCEV *RA = getSCEV(U->getOperand(2));
3525 const SCEV *LDiff = getMinusSCEV(LA, LS);
3526 const SCEV *RDiff = getMinusSCEV(RA, RS);
3527 if (LDiff == RDiff)
3528 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3529 LDiff = getMinusSCEV(LA, RS);
3530 RDiff = getMinusSCEV(RA, LS);
3531 if (LDiff == RDiff)
3532 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3533 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003534 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003535 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003536 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3537 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003538 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003539 cast<ConstantInt>(RHS)->isZero()) {
3540 const SCEV *One = getConstant(LHS->getType(), 1);
3541 const SCEV *LS = getSCEV(LHS);
3542 const SCEV *LA = getSCEV(U->getOperand(1));
3543 const SCEV *RA = getSCEV(U->getOperand(2));
3544 const SCEV *LDiff = getMinusSCEV(LA, LS);
3545 const SCEV *RDiff = getMinusSCEV(RA, One);
3546 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003547 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003548 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003549 break;
3550 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003551 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3552 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003553 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003554 cast<ConstantInt>(RHS)->isZero()) {
3555 const SCEV *One = getConstant(LHS->getType(), 1);
3556 const SCEV *LS = getSCEV(LHS);
3557 const SCEV *LA = getSCEV(U->getOperand(1));
3558 const SCEV *RA = getSCEV(U->getOperand(2));
3559 const SCEV *LDiff = getMinusSCEV(LA, One);
3560 const SCEV *RDiff = getMinusSCEV(RA, LS);
3561 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003562 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003563 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003564 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003565 default:
3566 break;
3567 }
3568 }
3569
3570 default: // We cannot analyze this expression.
3571 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003572 }
3573
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003574 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003575}
3576
3577
3578
3579//===----------------------------------------------------------------------===//
3580// Iteration Count Computation Code
3581//
3582
Dan Gohman46bdfb02009-02-24 18:55:53 +00003583/// getBackedgeTakenCount - If the specified loop has a predictable
3584/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3585/// object. The backedge-taken count is the number of times the loop header
3586/// will be branched to from within the loop. This is one less than the
3587/// trip count of the loop, since it doesn't count the first iteration,
3588/// when the header is branched to from outside the loop.
3589///
3590/// Note that it is not valid to call this method on a loop without a
3591/// loop-invariant backedge-taken count (see
3592/// hasLoopInvariantBackedgeTakenCount).
3593///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003594const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003595 return getBackedgeTakenInfo(L).Exact;
3596}
3597
3598/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3599/// return the least SCEV value that is known never to be less than the
3600/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003601const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003602 return getBackedgeTakenInfo(L).Max;
3603}
3604
Dan Gohman59ae6b92009-07-08 19:23:34 +00003605/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3606/// onto the given Worklist.
3607static void
3608PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3609 BasicBlock *Header = L->getHeader();
3610
3611 // Push all Loop-header PHIs onto the Worklist stack.
3612 for (BasicBlock::iterator I = Header->begin();
3613 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3614 Worklist.push_back(PN);
3615}
3616
Dan Gohmana1af7572009-04-30 20:47:05 +00003617const ScalarEvolution::BackedgeTakenInfo &
3618ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003619 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003620 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003621 // update the value. The temporary CouldNotCompute value tells SCEV
3622 // code elsewhere that it shouldn't attempt to request a new
3623 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003624 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003625 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3626 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003627 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3628 if (BECount.Exact != getCouldNotCompute()) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00003629 assert(isLoopInvariant(BECount.Exact, L) &&
3630 isLoopInvariant(BECount.Max, L) &&
Dan Gohman93dacad2010-01-26 16:46:18 +00003631 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003632 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003633
Dan Gohman01ecca22009-04-27 20:16:15 +00003634 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003635 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003636 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003637 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003638 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003639 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003640 if (isa<PHINode>(L->getHeader()->begin()))
3641 // Only count loops that have phi nodes as not being computable.
3642 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003643 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003644
3645 // Now that we know more about the trip count for this loop, forget any
3646 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003647 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003648 // information. This is similar to the code in forgetLoop, except that
3649 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003650 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003651 SmallVector<Instruction *, 16> Worklist;
3652 PushLoopPHIs(L, Worklist);
3653
3654 SmallPtrSet<Instruction *, 8> Visited;
3655 while (!Worklist.empty()) {
3656 Instruction *I = Worklist.pop_back_val();
3657 if (!Visited.insert(I)) continue;
3658
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003659 ValueExprMapType::iterator It =
3660 ValueExprMap.find(static_cast<Value *>(I));
3661 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003662 const SCEV *Old = It->second;
3663
Dan Gohman59ae6b92009-07-08 19:23:34 +00003664 // SCEVUnknown for a PHI either means that it has an unrecognized
3665 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003666 // by createNodeForPHI. In the former case, additional loop trip
3667 // count information isn't going to change anything. In the later
3668 // case, createNodeForPHI will perform the necessary updates on its
3669 // own when it gets to that point.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003670 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Dan Gohman56a75682010-11-17 23:28:48 +00003671 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003672 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003673 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003674 if (PHINode *PN = dyn_cast<PHINode>(I))
3675 ConstantEvolutionLoopExitValue.erase(PN);
3676 }
3677
3678 PushDefUseChildren(I, Worklist);
3679 }
3680 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003681 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003682 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003683}
3684
Dan Gohman4c7279a2009-10-31 15:04:55 +00003685/// forgetLoop - This method should be called by the client when it has
3686/// changed a loop in a way that may effect ScalarEvolution's ability to
3687/// compute a trip count, or if the loop is deleted.
3688void ScalarEvolution::forgetLoop(const Loop *L) {
3689 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003690 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003691
Dan Gohman4c7279a2009-10-31 15:04:55 +00003692 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003693 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003694 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003695
Dan Gohman59ae6b92009-07-08 19:23:34 +00003696 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003697 while (!Worklist.empty()) {
3698 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003699 if (!Visited.insert(I)) continue;
3700
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003701 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3702 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003703 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003704 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003705 if (PHINode *PN = dyn_cast<PHINode>(I))
3706 ConstantEvolutionLoopExitValue.erase(PN);
3707 }
3708
3709 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003710 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003711
3712 // Forget all contained loops too, to avoid dangling entries in the
3713 // ValuesAtScopes map.
3714 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3715 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003716}
3717
Eric Christophere6cbfa62010-07-29 01:25:38 +00003718/// forgetValue - This method should be called by the client when it has
3719/// changed a value in a way that may effect its value, or which may
3720/// disconnect it from a def-use chain linking it to a loop.
3721void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003722 Instruction *I = dyn_cast<Instruction>(V);
3723 if (!I) return;
3724
3725 // Drop information about expressions based on loop-header PHIs.
3726 SmallVector<Instruction *, 16> Worklist;
3727 Worklist.push_back(I);
3728
3729 SmallPtrSet<Instruction *, 8> Visited;
3730 while (!Worklist.empty()) {
3731 I = Worklist.pop_back_val();
3732 if (!Visited.insert(I)) continue;
3733
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003734 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3735 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003736 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003737 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003738 if (PHINode *PN = dyn_cast<PHINode>(I))
3739 ConstantEvolutionLoopExitValue.erase(PN);
3740 }
3741
3742 PushDefUseChildren(I, Worklist);
3743 }
3744}
3745
Dan Gohman46bdfb02009-02-24 18:55:53 +00003746/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3747/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003748ScalarEvolution::BackedgeTakenInfo
3749ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003750 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003751 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003752
Dan Gohmana334aa72009-06-22 00:31:57 +00003753 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003754 const SCEV *BECount = getCouldNotCompute();
3755 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003756 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003757 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3758 BackedgeTakenInfo NewBTI =
3759 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003760
Dan Gohman1c343752009-06-27 21:21:31 +00003761 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003762 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003763 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003764 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003765 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003766 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003767 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003768 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003769 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003770 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003771 }
Dan Gohman1c343752009-06-27 21:21:31 +00003772 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003773 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003774 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003775 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003776 }
3777
3778 return BackedgeTakenInfo(BECount, MaxBECount);
3779}
3780
3781/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3782/// of the specified loop will execute if it exits via the specified block.
3783ScalarEvolution::BackedgeTakenInfo
3784ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3785 BasicBlock *ExitingBlock) {
3786
3787 // Okay, we've chosen an exiting block. See what condition causes us to
3788 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003789 //
3790 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003791 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003792 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003793 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003794
Chris Lattner8b0e3602007-01-07 02:24:26 +00003795 // At this point, we know we have a conditional branch that determines whether
3796 // the loop is exited. However, we don't know if the branch is executed each
3797 // time through the loop. If not, then the execution count of the branch will
3798 // not be equal to the trip count of the loop.
3799 //
3800 // Currently we check for this by checking to see if the Exit branch goes to
3801 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003802 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003803 // loop header. This is common for un-rotated loops.
3804 //
3805 // If both of those tests fail, walk up the unique predecessor chain to the
3806 // header, stopping if there is an edge that doesn't exit the loop. If the
3807 // header is reached, the execution count of the branch will be equal to the
3808 // trip count of the loop.
3809 //
3810 // More extensive analysis could be done to handle more cases here.
3811 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003812 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003813 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003814 ExitBr->getParent() != L->getHeader()) {
3815 // The simple checks failed, try climbing the unique predecessor chain
3816 // up to the header.
3817 bool Ok = false;
3818 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3819 BasicBlock *Pred = BB->getUniquePredecessor();
3820 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003821 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003822 TerminatorInst *PredTerm = Pred->getTerminator();
3823 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3824 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3825 if (PredSucc == BB)
3826 continue;
3827 // If the predecessor has a successor that isn't BB and isn't
3828 // outside the loop, assume the worst.
3829 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003830 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003831 }
3832 if (Pred == L->getHeader()) {
3833 Ok = true;
3834 break;
3835 }
3836 BB = Pred;
3837 }
3838 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003839 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003840 }
3841
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003842 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003843 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3844 ExitBr->getSuccessor(0),
3845 ExitBr->getSuccessor(1));
3846}
3847
3848/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3849/// backedge of the specified loop will execute if its exit condition
3850/// were a conditional branch of ExitCond, TBB, and FBB.
3851ScalarEvolution::BackedgeTakenInfo
3852ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3853 Value *ExitCond,
3854 BasicBlock *TBB,
3855 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003856 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3858 if (BO->getOpcode() == Instruction::And) {
3859 // Recurse on the operands of the and.
3860 BackedgeTakenInfo BTI0 =
3861 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3862 BackedgeTakenInfo BTI1 =
3863 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003864 const SCEV *BECount = getCouldNotCompute();
3865 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003866 if (L->contains(TBB)) {
3867 // Both conditions must be true for the loop to continue executing.
3868 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003869 if (BTI0.Exact == getCouldNotCompute() ||
3870 BTI1.Exact == getCouldNotCompute())
3871 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003872 else
3873 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003874 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003875 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003876 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003877 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003878 else
3879 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003880 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003881 // Both conditions must be true at the same time for the loop to exit.
3882 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003883 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003884 if (BTI0.Max == BTI1.Max)
3885 MaxBECount = BTI0.Max;
3886 if (BTI0.Exact == BTI1.Exact)
3887 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003888 }
3889
3890 return BackedgeTakenInfo(BECount, MaxBECount);
3891 }
3892 if (BO->getOpcode() == Instruction::Or) {
3893 // Recurse on the operands of the or.
3894 BackedgeTakenInfo BTI0 =
3895 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3896 BackedgeTakenInfo BTI1 =
3897 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003898 const SCEV *BECount = getCouldNotCompute();
3899 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003900 if (L->contains(FBB)) {
3901 // Both conditions must be false for the loop to continue executing.
3902 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003903 if (BTI0.Exact == getCouldNotCompute() ||
3904 BTI1.Exact == getCouldNotCompute())
3905 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003906 else
3907 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003908 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003909 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003910 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003911 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003912 else
3913 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003914 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003915 // Both conditions must be false at the same time for the loop to exit.
3916 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003917 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003918 if (BTI0.Max == BTI1.Max)
3919 MaxBECount = BTI0.Max;
3920 if (BTI0.Exact == BTI1.Exact)
3921 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003922 }
3923
3924 return BackedgeTakenInfo(BECount, MaxBECount);
3925 }
3926 }
3927
3928 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003929 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003930 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3931 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932
Dan Gohman00cb5b72010-02-19 18:12:07 +00003933 // Check for a constant condition. These are normally stripped out by
3934 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3935 // preserve the CFG and is temporarily leaving constant conditions
3936 // in place.
3937 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3938 if (L->contains(FBB) == !CI->getZExtValue())
3939 // The backedge is always taken.
3940 return getCouldNotCompute();
3941 else
3942 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003943 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003944 }
3945
Eli Friedman361e54d2009-05-09 12:32:42 +00003946 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003947 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3948}
3949
3950/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3951/// backedge of the specified loop will execute if its exit condition
3952/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3953ScalarEvolution::BackedgeTakenInfo
3954ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3955 ICmpInst *ExitCond,
3956 BasicBlock *TBB,
3957 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003958
Reid Spencere4d87aa2006-12-23 06:05:41 +00003959 // If the condition was exit on true, convert the condition to exit on false
3960 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003961 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003962 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003963 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003964 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003965
3966 // Handle common loops like: for (X = "string"; *X; ++X)
3967 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3968 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003969 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003970 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003971 if (ItCnt.hasAnyInfo())
3972 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003973 }
3974
Dan Gohman0bba49c2009-07-07 17:06:11 +00003975 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3976 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003977
3978 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003979 LHS = getSCEVAtScope(LHS, L);
3980 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003981
Dan Gohman64a845e2009-06-24 04:48:43 +00003982 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00003984 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003985 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003986 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003987 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003988 }
3989
Dan Gohman03557dc2010-05-03 16:35:17 +00003990 // Simplify the operands before analyzing them.
3991 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3992
Chris Lattner53e677a2004-04-02 20:23:17 +00003993 // If we have a comparison of a chrec against a constant, try to use value
3994 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003995 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3996 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003997 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003998 // Form the constant range.
3999 ConstantRange CompRange(
4000 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004001
Dan Gohman0bba49c2009-07-07 17:06:11 +00004002 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004003 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004004 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004005
Chris Lattner53e677a2004-04-02 20:23:17 +00004006 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004007 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004008 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004009 BackedgeTakenInfo BTI = HowFarToZero(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 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004013 case ICmpInst::ICMP_EQ: { // while (X == Y)
4014 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004015 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4016 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004017 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004018 }
4019 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004020 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4021 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004022 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004023 }
4024 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004025 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4026 getNotSCEV(RHS), L, true);
4027 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004028 break;
4029 }
4030 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004031 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4032 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004033 break;
4034 }
4035 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004036 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4037 getNotSCEV(RHS), L, false);
4038 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004039 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004041 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004042#if 0
David Greene25e0e872009-12-23 22:18:14 +00004043 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004044 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004045 dbgs() << "[unsigned] ";
4046 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004047 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004048 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004049#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004050 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004051 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004052 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004053 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004054}
4055
Chris Lattner673e02b2004-10-12 01:49:27 +00004056static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004057EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4058 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004059 const SCEV *InVal = SE.getConstant(C);
4060 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004061 assert(isa<SCEVConstant>(Val) &&
4062 "Evaluation of SCEV at constant didn't fold correctly?");
4063 return cast<SCEVConstant>(Val)->getValue();
4064}
4065
4066/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4067/// and a GEP expression (missing the pointer index) indexing into it, return
4068/// the addressed element of the initializer or null if the index expression is
4069/// invalid.
4070static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004071GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004072 const std::vector<ConstantInt*> &Indices) {
4073 Constant *Init = GV->getInitializer();
4074 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004075 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004076 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4077 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4078 Init = cast<Constant>(CS->getOperand(Idx));
4079 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4080 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4081 Init = cast<Constant>(CA->getOperand(Idx));
4082 } else if (isa<ConstantAggregateZero>(Init)) {
4083 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4084 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004085 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004086 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4087 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004088 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004089 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004090 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004091 }
4092 return 0;
4093 } else {
4094 return 0; // Unknown initializer type
4095 }
4096 }
4097 return Init;
4098}
4099
Dan Gohman46bdfb02009-02-24 18:55:53 +00004100/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4101/// 'icmp op load X, cst', try to see if we can compute the backedge
4102/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004103ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004104ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4105 LoadInst *LI,
4106 Constant *RHS,
4107 const Loop *L,
4108 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004109 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004110
4111 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004112 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004113 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004114 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004115
4116 // Make sure that it is really a constant global we are gepping, with an
4117 // initializer, and make sure the first IDX is really 0.
4118 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004119 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004120 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4121 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004122 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004123
4124 // Okay, we allow one non-constant index into the GEP instruction.
4125 Value *VarIdx = 0;
4126 std::vector<ConstantInt*> Indexes;
4127 unsigned VarIdxNum = 0;
4128 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4129 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4130 Indexes.push_back(CI);
4131 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004132 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004133 VarIdx = GEP->getOperand(i);
4134 VarIdxNum = i-2;
4135 Indexes.push_back(0);
4136 }
4137
4138 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4139 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004140 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004141 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004142
4143 // We can only recognize very limited forms of loop index expressions, in
4144 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004145 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004146 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004147 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4148 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004149 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004150
4151 unsigned MaxSteps = MaxBruteForceIterations;
4152 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004153 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004154 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004155 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004156
4157 // Form the GEP offset.
4158 Indexes[VarIdxNum] = Val;
4159
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004160 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004161 if (Result == 0) break; // Cannot compute!
4162
4163 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004165 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004166 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004167#if 0
David Greene25e0e872009-12-23 22:18:14 +00004168 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004169 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4170 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004171#endif
4172 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004173 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004174 }
4175 }
Dan Gohman1c343752009-06-27 21:21:31 +00004176 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004177}
4178
4179
Chris Lattner3221ad02004-04-17 22:58:41 +00004180/// CanConstantFold - Return true if we can constant fold an instruction of the
4181/// specified type, assuming that all operands were constants.
4182static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004183 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004184 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4185 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004186
Chris Lattner3221ad02004-04-17 22:58:41 +00004187 if (const CallInst *CI = dyn_cast<CallInst>(I))
4188 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004189 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004190 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004191}
4192
Chris Lattner3221ad02004-04-17 22:58:41 +00004193/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4194/// in the loop that V is derived from. We allow arbitrary operations along the
4195/// way, but the operands of an operation must either be constants or a value
4196/// derived from a constant PHI. If this expression does not fit with these
4197/// constraints, return null.
4198static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4199 // If this is not an instruction, or if this is an instruction outside of the
4200 // loop, it can't be derived from a loop PHI.
4201 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004202 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004203
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004204 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004205 if (L->getHeader() == I->getParent())
4206 return PN;
4207 else
4208 // We don't currently keep track of the control flow needed to evaluate
4209 // PHIs, so we cannot handle PHIs inside of loops.
4210 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004211 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004212
4213 // If we won't be able to constant fold this expression even if the operands
4214 // are constants, return early.
4215 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004216
Chris Lattner3221ad02004-04-17 22:58:41 +00004217 // Otherwise, we can evaluate this instruction if all of its operands are
4218 // constant or derived from a PHI node themselves.
4219 PHINode *PHI = 0;
4220 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004221 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004222 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4223 if (P == 0) return 0; // Not evolving from PHI
4224 if (PHI == 0)
4225 PHI = P;
4226 else if (PHI != P)
4227 return 0; // Evolving from multiple different PHIs.
4228 }
4229
4230 // This is a expression evolving from a constant PHI!
4231 return PHI;
4232}
4233
4234/// EvaluateExpression - Given an expression that passes the
4235/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4236/// in the loop has the value PHIVal. If we can't fold this expression for some
4237/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004238static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4239 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004240 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004241 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004242 Instruction *I = cast<Instruction>(V);
4243
Dan Gohman9d4588f2010-06-22 13:15:46 +00004244 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004245
4246 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004247 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004248 if (Operands[i] == 0) return 0;
4249 }
4250
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004251 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004252 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004253 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004254 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004255 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004256}
4257
4258/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4259/// in the header of its containing loop, we know the loop executes a
4260/// constant number of times, and the PHI node is just a recurrence
4261/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004262Constant *
4263ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004264 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004265 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004266 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004267 ConstantEvolutionLoopExitValue.find(PN);
4268 if (I != ConstantEvolutionLoopExitValue.end())
4269 return I->second;
4270
Dan Gohmane0567812010-04-08 23:03:40 +00004271 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004272 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4273
4274 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4275
4276 // Since the loop is canonicalized, the PHI node must have two entries. One
4277 // entry must be a constant (coming in from outside of the loop), and the
4278 // second must be derived from the same PHI.
4279 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4280 Constant *StartCST =
4281 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4282 if (StartCST == 0)
4283 return RetVal = 0; // Must be a constant.
4284
4285 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004286 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4287 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004288 return RetVal = 0; // Not derived from same PHI.
4289
4290 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004291 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004292 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004293
Dan Gohman46bdfb02009-02-24 18:55:53 +00004294 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004295 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004296 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4297 if (IterationNum == NumIterations)
4298 return RetVal = PHIVal; // Got exit value!
4299
4300 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004301 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004302 if (NextPHI == PHIVal)
4303 return RetVal = NextPHI; // Stopped evolving!
4304 if (NextPHI == 0)
4305 return 0; // Couldn't evaluate!
4306 PHIVal = NextPHI;
4307 }
4308}
4309
Dan Gohman07ad19b2009-07-27 16:09:48 +00004310/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004311/// constant number of times (the condition evolves only from constants),
4312/// try to evaluate a few iterations of the loop until we get the exit
4313/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004314/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004315const SCEV *
4316ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4317 Value *Cond,
4318 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004319 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004320 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004321
Dan Gohmanb92654d2010-06-19 14:17:24 +00004322 // If the loop is canonicalized, the PHI will have exactly two entries.
4323 // That's the only form we support here.
4324 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4325
4326 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004327 // second must be derived from the same PHI.
4328 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4329 Constant *StartCST =
4330 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004331 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004332
4333 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004334 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4335 !isa<Constant>(BEValue))
4336 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004337
4338 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4339 // the loop symbolically to determine when the condition gets a value of
4340 // "ExitWhen".
4341 unsigned IterationNum = 0;
4342 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4343 for (Constant *PHIVal = StartCST;
4344 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004345 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004346 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004347
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004348 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004349 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004350
Reid Spencere8019bb2007-03-01 07:25:48 +00004351 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004352 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004353 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004354 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004355
Chris Lattner3221ad02004-04-17 22:58:41 +00004356 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004357 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004358 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004359 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004360 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004361 }
4362
4363 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004364 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004365}
4366
Dan Gohmane7125f42009-09-03 15:00:26 +00004367/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004368/// at the specified scope in the program. The L value specifies a loop
4369/// nest to evaluate the expression at, where null is the top-level or a
4370/// specified loop is immediately inside of the loop.
4371///
4372/// This method can be used to compute the exit value for a variable defined
4373/// in a loop by querying what the value will hold in the parent loop.
4374///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004375/// In the case that a relevant loop exit value cannot be computed, the
4376/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004377const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004378 // Check to see if we've folded this expression at this loop before.
4379 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4380 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4381 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4382 if (!Pair.second)
4383 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004384
Dan Gohman42214892009-08-31 21:15:23 +00004385 // Otherwise compute it.
4386 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004387 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004388 return C;
4389}
4390
4391const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004392 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004393
Nick Lewycky3e630762008-02-20 06:48:22 +00004394 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004395 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004396 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004397 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004398 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004399 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4400 if (PHINode *PN = dyn_cast<PHINode>(I))
4401 if (PN->getParent() == LI->getHeader()) {
4402 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004403 // to see if the loop that contains it has a known backedge-taken
4404 // count. If so, we may be able to force computation of the exit
4405 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004406 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004407 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004408 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004409 // Okay, we know how many times the containing loop executes. If
4410 // this is a constant evolving PHI node, get the final value at
4411 // the specified iteration number.
4412 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004413 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004414 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004415 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004416 }
4417 }
4418
Reid Spencer09906f32006-12-04 21:33:23 +00004419 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004420 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004421 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004422 // result. This is particularly useful for computing loop exit values.
4423 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004424 SmallVector<Constant *, 4> Operands;
4425 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004426 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4427 Value *Op = I->getOperand(i);
4428 if (Constant *C = dyn_cast<Constant>(Op)) {
4429 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004430 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004431 }
Dan Gohman11046452010-06-29 23:43:06 +00004432
4433 // If any of the operands is non-constant and if they are
4434 // non-integer and non-pointer, don't even try to analyze them
4435 // with scev techniques.
4436 if (!isSCEVable(Op->getType()))
4437 return V;
4438
4439 const SCEV *OrigV = getSCEV(Op);
4440 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4441 MadeImprovement |= OrigV != OpV;
4442
4443 Constant *C = 0;
4444 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4445 C = SC->getValue();
4446 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4447 C = dyn_cast<Constant>(SU->getValue());
4448 if (!C) return V;
4449 if (C->getType() != Op->getType())
4450 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4451 Op->getType(),
4452 false),
4453 C, Op->getType());
4454 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004455 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004456
Dan Gohman11046452010-06-29 23:43:06 +00004457 // Check to see if getSCEVAtScope actually made an improvement.
4458 if (MadeImprovement) {
4459 Constant *C = 0;
4460 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4461 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4462 Operands[0], Operands[1], TD);
4463 else
4464 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4465 &Operands[0], Operands.size(), TD);
4466 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004467 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004468 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004469 }
4470 }
4471
4472 // This is some other type of SCEVUnknown, just return it.
4473 return V;
4474 }
4475
Dan Gohman622ed672009-05-04 22:02:23 +00004476 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004477 // Avoid performing the look-up in the common case where the specified
4478 // expression has no loop-variant portions.
4479 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004480 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004481 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004482 // Okay, at least one of these operands is loop variant but might be
4483 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004484 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4485 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004486 NewOps.push_back(OpAtScope);
4487
4488 for (++i; i != e; ++i) {
4489 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004490 NewOps.push_back(OpAtScope);
4491 }
4492 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004493 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004494 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004495 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004496 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004497 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004498 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004499 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004500 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004501 }
4502 }
4503 // If we got here, all operands are loop invariant.
4504 return Comm;
4505 }
4506
Dan Gohman622ed672009-05-04 22:02:23 +00004507 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004508 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4509 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004510 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4511 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004512 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004513 }
4514
4515 // If this is a loop recurrence for a loop that does not contain L, then we
4516 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004517 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004518 // First, attempt to evaluate each operand.
4519 // Avoid performing the look-up in the common case where the specified
4520 // expression has no loop-variant portions.
4521 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4522 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4523 if (OpAtScope == AddRec->getOperand(i))
4524 continue;
4525
4526 // Okay, at least one of these operands is loop variant but might be
4527 // foldable. Build a new instance of the folded commutative expression.
4528 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4529 AddRec->op_begin()+i);
4530 NewOps.push_back(OpAtScope);
4531 for (++i; i != e; ++i)
4532 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4533
4534 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4535 break;
4536 }
4537
4538 // If the scope is outside the addrec's loop, evaluate it by using the
4539 // loop exit value of the addrec.
4540 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004541 // To evaluate this recurrence, we need to know how many times the AddRec
4542 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004543 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004544 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004545
Eli Friedmanb42a6262008-08-04 23:49:06 +00004546 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004547 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004548 }
Dan Gohman11046452010-06-29 23:43:06 +00004549
Dan Gohmand594e6f2009-05-24 23:25:42 +00004550 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004551 }
4552
Dan Gohman622ed672009-05-04 22:02:23 +00004553 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004554 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004555 if (Op == Cast->getOperand())
4556 return Cast; // must be loop invariant
4557 return getZeroExtendExpr(Op, Cast->getType());
4558 }
4559
Dan Gohman622ed672009-05-04 22:02:23 +00004560 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004561 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004562 if (Op == Cast->getOperand())
4563 return Cast; // must be loop invariant
4564 return getSignExtendExpr(Op, Cast->getType());
4565 }
4566
Dan Gohman622ed672009-05-04 22:02:23 +00004567 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004568 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004569 if (Op == Cast->getOperand())
4570 return Cast; // must be loop invariant
4571 return getTruncateExpr(Op, Cast->getType());
4572 }
4573
Torok Edwinc23197a2009-07-14 16:55:14 +00004574 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004575 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004576}
4577
Dan Gohman66a7e852009-05-08 20:38:54 +00004578/// getSCEVAtScope - This is a convenience function which does
4579/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004580const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004581 return getSCEVAtScope(getSCEV(V), L);
4582}
4583
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004584/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4585/// following equation:
4586///
4587/// A * X = B (mod N)
4588///
4589/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4590/// A and B isn't important.
4591///
4592/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004593static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004594 ScalarEvolution &SE) {
4595 uint32_t BW = A.getBitWidth();
4596 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4597 assert(A != 0 && "A must be non-zero.");
4598
4599 // 1. D = gcd(A, N)
4600 //
4601 // The gcd of A and N may have only one prime factor: 2. The number of
4602 // trailing zeros in A is its multiplicity
4603 uint32_t Mult2 = A.countTrailingZeros();
4604 // D = 2^Mult2
4605
4606 // 2. Check if B is divisible by D.
4607 //
4608 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4609 // is not less than multiplicity of this prime factor for D.
4610 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004611 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004612
4613 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4614 // modulo (N / D).
4615 //
4616 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4617 // bit width during computations.
4618 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4619 APInt Mod(BW + 1, 0);
4620 Mod.set(BW - Mult2); // Mod = N / D
4621 APInt I = AD.multiplicativeInverse(Mod);
4622
4623 // 4. Compute the minimum unsigned root of the equation:
4624 // I * (B / D) mod (N / D)
4625 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4626
4627 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4628 // bits.
4629 return SE.getConstant(Result.trunc(BW));
4630}
Chris Lattner53e677a2004-04-02 20:23:17 +00004631
4632/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4633/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4634/// might be the same) or two SCEVCouldNotCompute objects.
4635///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004636static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004637SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004638 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004639 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4640 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4641 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004642
Chris Lattner53e677a2004-04-02 20:23:17 +00004643 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004644 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004645 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004646 return std::make_pair(CNC, CNC);
4647 }
4648
Reid Spencere8019bb2007-03-01 07:25:48 +00004649 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004650 const APInt &L = LC->getValue()->getValue();
4651 const APInt &M = MC->getValue()->getValue();
4652 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004653 APInt Two(BitWidth, 2);
4654 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004655
Dan Gohman64a845e2009-06-24 04:48:43 +00004656 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004657 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004658 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004659 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4660 // The B coefficient is M-N/2
4661 APInt B(M);
4662 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004663
Reid Spencere8019bb2007-03-01 07:25:48 +00004664 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004665 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004666
Reid Spencere8019bb2007-03-01 07:25:48 +00004667 // Compute the B^2-4ac term.
4668 APInt SqrtTerm(B);
4669 SqrtTerm *= B;
4670 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004671
Reid Spencere8019bb2007-03-01 07:25:48 +00004672 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4673 // integer value or else APInt::sqrt() will assert.
4674 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004675
Dan Gohman64a845e2009-06-24 04:48:43 +00004676 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004677 // The divisions must be performed as signed divisions.
4678 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004679 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004680 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004681 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004682 return std::make_pair(CNC, CNC);
4683 }
4684
Owen Andersone922c022009-07-22 00:24:57 +00004685 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004686
4687 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004688 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004689 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004690 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004691
Dan Gohman64a845e2009-06-24 04:48:43 +00004692 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004693 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004694 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004695}
4696
4697/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004698/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004699ScalarEvolution::BackedgeTakenInfo
4700ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004701 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004702 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004703 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004704 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004705 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004706 }
4707
Dan Gohman35738ac2009-05-04 22:30:44 +00004708 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004709 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004710 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004711
4712 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004713 // If this is an affine expression, the execution count of this branch is
4714 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004715 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004716 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004717 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004718 // equivalent to:
4719 //
4720 // Step*N = -Start (mod 2^BW)
4721 //
4722 // where BW is the common bit width of Start and Step.
4723
Chris Lattner53e677a2004-04-02 20:23:17 +00004724 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004725 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4726 L->getParentLoop());
4727 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4728 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004729
Dan Gohman622ed672009-05-04 22:02:23 +00004730 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004731 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004732
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004733 // First, handle unitary steps.
4734 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004735 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004736 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4737 return Start; // N = Start (as unsigned)
4738
4739 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004740 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004741 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004742 -StartC->getValue()->getValue(),
4743 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004744 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004745 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004746 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4747 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004748 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004749 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004750 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4751 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004752 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004753#if 0
David Greene25e0e872009-12-23 22:18:14 +00004754 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004755 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004756#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004757 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004758 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004759 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004760 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004761 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004762 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004763
Chris Lattner53e677a2004-04-02 20:23:17 +00004764 // We can only use this value if the chrec ends up with an exact zero
4765 // value at this index. When solving for "X*X != 5", for example, we
4766 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004767 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004768 if (Val->isZero())
4769 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004770 }
4771 }
4772 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004773
Dan Gohman1c343752009-06-27 21:21:31 +00004774 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004775}
4776
4777/// HowFarToNonZero - Return the number of times a backedge checking the
4778/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004779/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004780ScalarEvolution::BackedgeTakenInfo
4781ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004782 // Loops that look like: while (X == 0) are very strange indeed. We don't
4783 // handle them yet except for the trivial case. This could be expanded in the
4784 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004785
Chris Lattner53e677a2004-04-02 20:23:17 +00004786 // If the value is a constant, check to see if it is known to be non-zero
4787 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004788 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004789 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004790 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004791 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004792 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004793
Chris Lattner53e677a2004-04-02 20:23:17 +00004794 // We could implement others, but I really doubt anyone writes loops like
4795 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004796 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004797}
4798
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004799/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4800/// (which may not be an immediate predecessor) which has exactly one
4801/// successor from which BB is reachable, or null if no such block is
4802/// found.
4803///
Dan Gohman005752b2010-04-15 16:19:08 +00004804std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004805ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004806 // If the block has a unique predecessor, then there is no path from the
4807 // predecessor to the block that does not go through the direct edge
4808 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004809 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004810 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004811
4812 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004813 // If the header has a unique predecessor outside the loop, it must be
4814 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004815 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004816 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004817
Dan Gohman005752b2010-04-15 16:19:08 +00004818 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004819}
4820
Dan Gohman763bad12009-06-20 00:35:32 +00004821/// HasSameValue - SCEV structural equivalence is usually sufficient for
4822/// testing whether two expressions are equal, however for the purposes of
4823/// looking for a condition guarding a loop, it can be useful to be a little
4824/// more general, since a front-end may have replicated the controlling
4825/// expression.
4826///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004827static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004828 // Quick check to see if they are the same SCEV.
4829 if (A == B) return true;
4830
4831 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4832 // two different instructions with the same value. Check for this case.
4833 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4834 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4835 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4836 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004837 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004838 return true;
4839
4840 // Otherwise assume they may have a different value.
4841 return false;
4842}
4843
Dan Gohmane9796502010-04-24 01:28:42 +00004844/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4845/// predicate Pred. Return true iff any changes were made.
4846///
4847bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4848 const SCEV *&LHS, const SCEV *&RHS) {
4849 bool Changed = false;
4850
4851 // Canonicalize a constant to the right side.
4852 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4853 // Check for both operands constant.
4854 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4855 if (ConstantExpr::getICmp(Pred,
4856 LHSC->getValue(),
4857 RHSC->getValue())->isNullValue())
4858 goto trivially_false;
4859 else
4860 goto trivially_true;
4861 }
4862 // Otherwise swap the operands to put the constant on the right.
4863 std::swap(LHS, RHS);
4864 Pred = ICmpInst::getSwappedPredicate(Pred);
4865 Changed = true;
4866 }
4867
4868 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004869 // addrec's loop, put the addrec on the left. Also make a dominance check,
4870 // as both operands could be addrecs loop-invariant in each other's loop.
4871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4872 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00004873 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00004874 std::swap(LHS, RHS);
4875 Pred = ICmpInst::getSwappedPredicate(Pred);
4876 Changed = true;
4877 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004878 }
Dan Gohmane9796502010-04-24 01:28:42 +00004879
4880 // If there's a constant operand, canonicalize comparisons with boundary
4881 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4882 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4883 const APInt &RA = RC->getValue()->getValue();
4884 switch (Pred) {
4885 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4886 case ICmpInst::ICMP_EQ:
4887 case ICmpInst::ICMP_NE:
4888 break;
4889 case ICmpInst::ICMP_UGE:
4890 if ((RA - 1).isMinValue()) {
4891 Pred = ICmpInst::ICMP_NE;
4892 RHS = getConstant(RA - 1);
4893 Changed = true;
4894 break;
4895 }
4896 if (RA.isMaxValue()) {
4897 Pred = ICmpInst::ICMP_EQ;
4898 Changed = true;
4899 break;
4900 }
4901 if (RA.isMinValue()) goto trivially_true;
4902
4903 Pred = ICmpInst::ICMP_UGT;
4904 RHS = getConstant(RA - 1);
4905 Changed = true;
4906 break;
4907 case ICmpInst::ICMP_ULE:
4908 if ((RA + 1).isMaxValue()) {
4909 Pred = ICmpInst::ICMP_NE;
4910 RHS = getConstant(RA + 1);
4911 Changed = true;
4912 break;
4913 }
4914 if (RA.isMinValue()) {
4915 Pred = ICmpInst::ICMP_EQ;
4916 Changed = true;
4917 break;
4918 }
4919 if (RA.isMaxValue()) goto trivially_true;
4920
4921 Pred = ICmpInst::ICMP_ULT;
4922 RHS = getConstant(RA + 1);
4923 Changed = true;
4924 break;
4925 case ICmpInst::ICMP_SGE:
4926 if ((RA - 1).isMinSignedValue()) {
4927 Pred = ICmpInst::ICMP_NE;
4928 RHS = getConstant(RA - 1);
4929 Changed = true;
4930 break;
4931 }
4932 if (RA.isMaxSignedValue()) {
4933 Pred = ICmpInst::ICMP_EQ;
4934 Changed = true;
4935 break;
4936 }
4937 if (RA.isMinSignedValue()) goto trivially_true;
4938
4939 Pred = ICmpInst::ICMP_SGT;
4940 RHS = getConstant(RA - 1);
4941 Changed = true;
4942 break;
4943 case ICmpInst::ICMP_SLE:
4944 if ((RA + 1).isMaxSignedValue()) {
4945 Pred = ICmpInst::ICMP_NE;
4946 RHS = getConstant(RA + 1);
4947 Changed = true;
4948 break;
4949 }
4950 if (RA.isMinSignedValue()) {
4951 Pred = ICmpInst::ICMP_EQ;
4952 Changed = true;
4953 break;
4954 }
4955 if (RA.isMaxSignedValue()) goto trivially_true;
4956
4957 Pred = ICmpInst::ICMP_SLT;
4958 RHS = getConstant(RA + 1);
4959 Changed = true;
4960 break;
4961 case ICmpInst::ICMP_UGT:
4962 if (RA.isMinValue()) {
4963 Pred = ICmpInst::ICMP_NE;
4964 Changed = true;
4965 break;
4966 }
4967 if ((RA + 1).isMaxValue()) {
4968 Pred = ICmpInst::ICMP_EQ;
4969 RHS = getConstant(RA + 1);
4970 Changed = true;
4971 break;
4972 }
4973 if (RA.isMaxValue()) goto trivially_false;
4974 break;
4975 case ICmpInst::ICMP_ULT:
4976 if (RA.isMaxValue()) {
4977 Pred = ICmpInst::ICMP_NE;
4978 Changed = true;
4979 break;
4980 }
4981 if ((RA - 1).isMinValue()) {
4982 Pred = ICmpInst::ICMP_EQ;
4983 RHS = getConstant(RA - 1);
4984 Changed = true;
4985 break;
4986 }
4987 if (RA.isMinValue()) goto trivially_false;
4988 break;
4989 case ICmpInst::ICMP_SGT:
4990 if (RA.isMinSignedValue()) {
4991 Pred = ICmpInst::ICMP_NE;
4992 Changed = true;
4993 break;
4994 }
4995 if ((RA + 1).isMaxSignedValue()) {
4996 Pred = ICmpInst::ICMP_EQ;
4997 RHS = getConstant(RA + 1);
4998 Changed = true;
4999 break;
5000 }
5001 if (RA.isMaxSignedValue()) goto trivially_false;
5002 break;
5003 case ICmpInst::ICMP_SLT:
5004 if (RA.isMaxSignedValue()) {
5005 Pred = ICmpInst::ICMP_NE;
5006 Changed = true;
5007 break;
5008 }
5009 if ((RA - 1).isMinSignedValue()) {
5010 Pred = ICmpInst::ICMP_EQ;
5011 RHS = getConstant(RA - 1);
5012 Changed = true;
5013 break;
5014 }
5015 if (RA.isMinSignedValue()) goto trivially_false;
5016 break;
5017 }
5018 }
5019
5020 // Check for obvious equality.
5021 if (HasSameValue(LHS, RHS)) {
5022 if (ICmpInst::isTrueWhenEqual(Pred))
5023 goto trivially_true;
5024 if (ICmpInst::isFalseWhenEqual(Pred))
5025 goto trivially_false;
5026 }
5027
Dan Gohman03557dc2010-05-03 16:35:17 +00005028 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5029 // adding or subtracting 1 from one of the operands.
5030 switch (Pred) {
5031 case ICmpInst::ICMP_SLE:
5032 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5033 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5034 /*HasNUW=*/false, /*HasNSW=*/true);
5035 Pred = ICmpInst::ICMP_SLT;
5036 Changed = true;
5037 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005038 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005039 /*HasNUW=*/false, /*HasNSW=*/true);
5040 Pred = ICmpInst::ICMP_SLT;
5041 Changed = true;
5042 }
5043 break;
5044 case ICmpInst::ICMP_SGE:
5045 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005046 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005047 /*HasNUW=*/false, /*HasNSW=*/true);
5048 Pred = ICmpInst::ICMP_SGT;
5049 Changed = true;
5050 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5051 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5052 /*HasNUW=*/false, /*HasNSW=*/true);
5053 Pred = ICmpInst::ICMP_SGT;
5054 Changed = true;
5055 }
5056 break;
5057 case ICmpInst::ICMP_ULE:
5058 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005059 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005060 /*HasNUW=*/true, /*HasNSW=*/false);
5061 Pred = ICmpInst::ICMP_ULT;
5062 Changed = true;
5063 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005064 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005065 /*HasNUW=*/true, /*HasNSW=*/false);
5066 Pred = ICmpInst::ICMP_ULT;
5067 Changed = true;
5068 }
5069 break;
5070 case ICmpInst::ICMP_UGE:
5071 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005072 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005073 /*HasNUW=*/true, /*HasNSW=*/false);
5074 Pred = ICmpInst::ICMP_UGT;
5075 Changed = true;
5076 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005077 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005078 /*HasNUW=*/true, /*HasNSW=*/false);
5079 Pred = ICmpInst::ICMP_UGT;
5080 Changed = true;
5081 }
5082 break;
5083 default:
5084 break;
5085 }
5086
Dan Gohmane9796502010-04-24 01:28:42 +00005087 // TODO: More simplifications are possible here.
5088
5089 return Changed;
5090
5091trivially_true:
5092 // Return 0 == 0.
5093 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5094 Pred = ICmpInst::ICMP_EQ;
5095 return true;
5096
5097trivially_false:
5098 // Return 0 != 0.
5099 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5100 Pred = ICmpInst::ICMP_NE;
5101 return true;
5102}
5103
Dan Gohman85b05a22009-07-13 21:35:55 +00005104bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5105 return getSignedRange(S).getSignedMax().isNegative();
5106}
5107
5108bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5109 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5110}
5111
5112bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5113 return !getSignedRange(S).getSignedMin().isNegative();
5114}
5115
5116bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5117 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5118}
5119
5120bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5121 return isKnownNegative(S) || isKnownPositive(S);
5122}
5123
5124bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5125 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005126 // Canonicalize the inputs first.
5127 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5128
Dan Gohman53c66ea2010-04-11 22:16:48 +00005129 // If LHS or RHS is an addrec, check to see if the condition is true in
5130 // every iteration of the loop.
5131 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5132 if (isLoopEntryGuardedByCond(
5133 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5134 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005135 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005136 return true;
5137 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5138 if (isLoopEntryGuardedByCond(
5139 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5140 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005141 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005142 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005143
Dan Gohman53c66ea2010-04-11 22:16:48 +00005144 // Otherwise see what can be done with known constant ranges.
5145 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5146}
5147
5148bool
5149ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5150 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005151 if (HasSameValue(LHS, RHS))
5152 return ICmpInst::isTrueWhenEqual(Pred);
5153
Dan Gohman53c66ea2010-04-11 22:16:48 +00005154 // This code is split out from isKnownPredicate because it is called from
5155 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005156 switch (Pred) {
5157 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005158 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005159 break;
5160 case ICmpInst::ICMP_SGT:
5161 Pred = ICmpInst::ICMP_SLT;
5162 std::swap(LHS, RHS);
5163 case ICmpInst::ICMP_SLT: {
5164 ConstantRange LHSRange = getSignedRange(LHS);
5165 ConstantRange RHSRange = getSignedRange(RHS);
5166 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5167 return true;
5168 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5169 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005170 break;
5171 }
5172 case ICmpInst::ICMP_SGE:
5173 Pred = ICmpInst::ICMP_SLE;
5174 std::swap(LHS, RHS);
5175 case ICmpInst::ICMP_SLE: {
5176 ConstantRange LHSRange = getSignedRange(LHS);
5177 ConstantRange RHSRange = getSignedRange(RHS);
5178 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5179 return true;
5180 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5181 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005182 break;
5183 }
5184 case ICmpInst::ICMP_UGT:
5185 Pred = ICmpInst::ICMP_ULT;
5186 std::swap(LHS, RHS);
5187 case ICmpInst::ICMP_ULT: {
5188 ConstantRange LHSRange = getUnsignedRange(LHS);
5189 ConstantRange RHSRange = getUnsignedRange(RHS);
5190 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5191 return true;
5192 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5193 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005194 break;
5195 }
5196 case ICmpInst::ICMP_UGE:
5197 Pred = ICmpInst::ICMP_ULE;
5198 std::swap(LHS, RHS);
5199 case ICmpInst::ICMP_ULE: {
5200 ConstantRange LHSRange = getUnsignedRange(LHS);
5201 ConstantRange RHSRange = getUnsignedRange(RHS);
5202 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5203 return true;
5204 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5205 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005206 break;
5207 }
5208 case ICmpInst::ICMP_NE: {
5209 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5210 return true;
5211 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5212 return true;
5213
5214 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5215 if (isKnownNonZero(Diff))
5216 return true;
5217 break;
5218 }
5219 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005220 // The check at the top of the function catches the case where
5221 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005222 break;
5223 }
5224 return false;
5225}
5226
5227/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5228/// protected by a conditional between LHS and RHS. This is used to
5229/// to eliminate casts.
5230bool
5231ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5232 ICmpInst::Predicate Pred,
5233 const SCEV *LHS, const SCEV *RHS) {
5234 // Interpret a null as meaning no loop, where there is obviously no guard
5235 // (interprocedural conditions notwithstanding).
5236 if (!L) return true;
5237
5238 BasicBlock *Latch = L->getLoopLatch();
5239 if (!Latch)
5240 return false;
5241
5242 BranchInst *LoopContinuePredicate =
5243 dyn_cast<BranchInst>(Latch->getTerminator());
5244 if (!LoopContinuePredicate ||
5245 LoopContinuePredicate->isUnconditional())
5246 return false;
5247
Dan Gohmanaf08a362010-08-10 23:46:30 +00005248 return isImpliedCond(Pred, LHS, RHS,
5249 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005250 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005251}
5252
Dan Gohman3948d0b2010-04-11 19:27:13 +00005253/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005254/// by a conditional between LHS and RHS. This is used to help avoid max
5255/// expressions in loop trip counts, and to eliminate casts.
5256bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005257ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5258 ICmpInst::Predicate Pred,
5259 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005260 // Interpret a null as meaning no loop, where there is obviously no guard
5261 // (interprocedural conditions notwithstanding).
5262 if (!L) return false;
5263
Dan Gohman859b4822009-05-18 15:36:09 +00005264 // Starting at the loop predecessor, climb up the predecessor chain, as long
5265 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005266 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005267 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005268 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005269 Pair.first;
5270 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005271
5272 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005273 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005274 if (!LoopEntryPredicate ||
5275 LoopEntryPredicate->isUnconditional())
5276 continue;
5277
Dan Gohmanaf08a362010-08-10 23:46:30 +00005278 if (isImpliedCond(Pred, LHS, RHS,
5279 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005280 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005281 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005282 }
5283
Dan Gohman38372182008-08-12 20:17:31 +00005284 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005285}
5286
Dan Gohman0f4b2852009-07-21 23:03:19 +00005287/// isImpliedCond - Test whether the condition described by Pred, LHS,
5288/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005289bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005290 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005291 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005292 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005293 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005294 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005295 if (BO->getOpcode() == Instruction::And) {
5296 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005297 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5298 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005299 } else if (BO->getOpcode() == Instruction::Or) {
5300 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005301 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5302 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005303 }
5304 }
5305
Dan Gohmanaf08a362010-08-10 23:46:30 +00005306 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005307 if (!ICI) return false;
5308
Dan Gohman85b05a22009-07-13 21:35:55 +00005309 // Bail if the ICmp's operands' types are wider than the needed type
5310 // before attempting to call getSCEV on them. This avoids infinite
5311 // recursion, since the analysis of widening casts can require loop
5312 // exit condition information for overflow checking, which would
5313 // lead back here.
5314 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005315 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005316 return false;
5317
Dan Gohman0f4b2852009-07-21 23:03:19 +00005318 // Now that we found a conditional branch that dominates the loop, check to
5319 // see if it is the comparison we are looking for.
5320 ICmpInst::Predicate FoundPred;
5321 if (Inverse)
5322 FoundPred = ICI->getInversePredicate();
5323 else
5324 FoundPred = ICI->getPredicate();
5325
5326 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5327 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005328
5329 // Balance the types. The case where FoundLHS' type is wider than
5330 // LHS' type is checked for above.
5331 if (getTypeSizeInBits(LHS->getType()) >
5332 getTypeSizeInBits(FoundLHS->getType())) {
5333 if (CmpInst::isSigned(Pred)) {
5334 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5335 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5336 } else {
5337 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5338 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5339 }
5340 }
5341
Dan Gohman0f4b2852009-07-21 23:03:19 +00005342 // Canonicalize the query to match the way instcombine will have
5343 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005344 if (SimplifyICmpOperands(Pred, LHS, RHS))
5345 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005346 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005347 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5348 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005349 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005350
5351 // Check to see if we can make the LHS or RHS match.
5352 if (LHS == FoundRHS || RHS == FoundLHS) {
5353 if (isa<SCEVConstant>(RHS)) {
5354 std::swap(FoundLHS, FoundRHS);
5355 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5356 } else {
5357 std::swap(LHS, RHS);
5358 Pred = ICmpInst::getSwappedPredicate(Pred);
5359 }
5360 }
5361
5362 // Check whether the found predicate is the same as the desired predicate.
5363 if (FoundPred == Pred)
5364 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5365
5366 // Check whether swapping the found predicate makes it the same as the
5367 // desired predicate.
5368 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5369 if (isa<SCEVConstant>(RHS))
5370 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5371 else
5372 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5373 RHS, LHS, FoundLHS, FoundRHS);
5374 }
5375
5376 // Check whether the actual condition is beyond sufficient.
5377 if (FoundPred == ICmpInst::ICMP_EQ)
5378 if (ICmpInst::isTrueWhenEqual(Pred))
5379 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5380 return true;
5381 if (Pred == ICmpInst::ICMP_NE)
5382 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5383 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5384 return true;
5385
5386 // Otherwise assume the worst.
5387 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005388}
5389
Dan Gohman0f4b2852009-07-21 23:03:19 +00005390/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005391/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005392/// and FoundRHS is true.
5393bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5394 const SCEV *LHS, const SCEV *RHS,
5395 const SCEV *FoundLHS,
5396 const SCEV *FoundRHS) {
5397 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5398 FoundLHS, FoundRHS) ||
5399 // ~x < ~y --> x > y
5400 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5401 getNotSCEV(FoundRHS),
5402 getNotSCEV(FoundLHS));
5403}
5404
5405/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005406/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005407/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005408bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005409ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5410 const SCEV *LHS, const SCEV *RHS,
5411 const SCEV *FoundLHS,
5412 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005413 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005414 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5415 case ICmpInst::ICMP_EQ:
5416 case ICmpInst::ICMP_NE:
5417 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5418 return true;
5419 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005420 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005421 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005422 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5423 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005424 return true;
5425 break;
5426 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005427 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005428 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5429 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005430 return true;
5431 break;
5432 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005433 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005434 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5435 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005436 return true;
5437 break;
5438 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005439 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005440 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5441 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005442 return true;
5443 break;
5444 }
5445
5446 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005447}
5448
Dan Gohman51f53b72009-06-21 23:46:38 +00005449/// getBECount - Subtract the end and start values and divide by the step,
5450/// rounding up, to get the number of times the backedge is executed. Return
5451/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005452const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005453 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005454 const SCEV *Step,
5455 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005456 assert(!isKnownNegative(Step) &&
5457 "This code doesn't handle negative strides yet!");
5458
Dan Gohman51f53b72009-06-21 23:46:38 +00005459 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005460 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005461 const SCEV *Diff = getMinusSCEV(End, Start);
5462 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005463
5464 // Add an adjustment to the difference between End and Start so that
5465 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005466 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005467
Dan Gohman1f96e672009-09-17 18:05:20 +00005468 if (!NoWrap) {
5469 // Check Add for unsigned overflow.
5470 // TODO: More sophisticated things could be done here.
5471 const Type *WideTy = IntegerType::get(getContext(),
5472 getTypeSizeInBits(Ty) + 1);
5473 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5474 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5475 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5476 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5477 return getCouldNotCompute();
5478 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005479
5480 return getUDivExpr(Add, Step);
5481}
5482
Chris Lattnerdb25de42005-08-15 23:33:51 +00005483/// HowManyLessThans - Return the number of times a backedge containing the
5484/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005485/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005486ScalarEvolution::BackedgeTakenInfo
5487ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5488 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005489 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005490 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005491
Dan Gohman35738ac2009-05-04 22:30:44 +00005492 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005493 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005494 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005495
Dan Gohman1f96e672009-09-17 18:05:20 +00005496 // Check to see if we have a flag which makes analysis easy.
5497 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5498 AddRec->hasNoUnsignedWrap();
5499
Chris Lattnerdb25de42005-08-15 23:33:51 +00005500 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005501 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005502 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005503
Dan Gohman52fddd32010-01-26 04:40:18 +00005504 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005505 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005506 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005507 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005508 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005509 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005510 // value and past the maximum value for its type in a single step.
5511 // Note that it's not sufficient to check NoWrap here, because even
5512 // though the value after a wrap is undefined, it's not undefined
5513 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005514 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005515 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005516 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005517 if (isSigned) {
5518 APInt Max = APInt::getSignedMaxValue(BitWidth);
5519 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5520 .slt(getSignedRange(RHS).getSignedMax()))
5521 return getCouldNotCompute();
5522 } else {
5523 APInt Max = APInt::getMaxValue(BitWidth);
5524 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5525 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5526 return getCouldNotCompute();
5527 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005528 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005529 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005530 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005531
Dan Gohmana1af7572009-04-30 20:47:05 +00005532 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5533 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5534 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005535 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005536
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005537 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005538 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005539
Dan Gohmana1af7572009-04-30 20:47:05 +00005540 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005541 const SCEV *MinStart = getConstant(isSigned ?
5542 getSignedRange(Start).getSignedMin() :
5543 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005544
Dan Gohmana1af7572009-04-30 20:47:05 +00005545 // If we know that the condition is true in order to enter the loop,
5546 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005547 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5548 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005549 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005550 if (!isLoopEntryGuardedByCond(L,
5551 isSigned ? ICmpInst::ICMP_SLT :
5552 ICmpInst::ICMP_ULT,
5553 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005554 End = isSigned ? getSMaxExpr(RHS, Start)
5555 : getUMaxExpr(RHS, Start);
5556
5557 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005558 const SCEV *MaxEnd = getConstant(isSigned ?
5559 getSignedRange(End).getSignedMax() :
5560 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005561
Dan Gohman52fddd32010-01-26 04:40:18 +00005562 // If MaxEnd is within a step of the maximum integer value in its type,
5563 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005564 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005565 // compute the correct value.
5566 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005567 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005568 MaxEnd = isSigned ?
5569 getSMinExpr(MaxEnd,
5570 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5571 StepMinusOne)) :
5572 getUMinExpr(MaxEnd,
5573 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5574 StepMinusOne));
5575
Dan Gohmana1af7572009-04-30 20:47:05 +00005576 // Finally, we subtract these two values and divide, rounding up, to get
5577 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005578 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005579
5580 // The maximum backedge count is similar, except using the minimum start
5581 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005582 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005583
5584 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005585 }
5586
Dan Gohman1c343752009-06-27 21:21:31 +00005587 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005588}
5589
Chris Lattner53e677a2004-04-02 20:23:17 +00005590/// getNumIterationsInRange - Return the number of iterations of this loop that
5591/// produce values in the specified constant range. Another way of looking at
5592/// this is that it returns the first iteration number where the value is not in
5593/// the condition, thus computing the exit count. If the iteration count can't
5594/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005595const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005596 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005597 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005598 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005599
5600 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005601 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005602 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005603 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005604 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005605 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005606 if (const SCEVAddRecExpr *ShiftedAddRec =
5607 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005608 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005609 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005610 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005611 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005612 }
5613
5614 // The only time we can solve this is when we have all constant indices.
5615 // Otherwise, we cannot determine the overflow conditions.
5616 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5617 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005618 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005619
5620
5621 // Okay at this point we know that all elements of the chrec are constants and
5622 // that the start element is zero.
5623
5624 // First check to see if the range contains zero. If not, the first
5625 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005626 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005627 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005628 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005629
Chris Lattner53e677a2004-04-02 20:23:17 +00005630 if (isAffine()) {
5631 // If this is an affine expression then we have this situation:
5632 // Solve {0,+,A} in Range === Ax in Range
5633
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005634 // We know that zero is in the range. If A is positive then we know that
5635 // the upper value of the range must be the first possible exit value.
5636 // If A is negative then the lower of the range is the last possible loop
5637 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005638 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005639 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5640 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005641
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005642 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005643 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005644 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005645
5646 // Evaluate at the exit value. If we really did fall out of the valid
5647 // range, then we computed our trip count, otherwise wrap around or other
5648 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005649 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005650 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005651 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005652
5653 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005654 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005655 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005656 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005657 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005658 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005659 } else if (isQuadratic()) {
5660 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5661 // quadratic equation to solve it. To do this, we must frame our problem in
5662 // terms of figuring out when zero is crossed, instead of when
5663 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005664 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005665 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005666 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005667
5668 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005669 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005670 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005671 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5672 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005673 if (R1) {
5674 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005675 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005676 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005677 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005678 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005679 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005680
Chris Lattner53e677a2004-04-02 20:23:17 +00005681 // Make sure the root is not off by one. The returned iteration should
5682 // not be in the range, but the previous one should be. When solving
5683 // for "X*X < 5", for example, we should not return a root of 2.
5684 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005685 R1->getValue(),
5686 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005687 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005688 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005689 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005690 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005691
Dan Gohman246b2562007-10-22 18:31:58 +00005692 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005693 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005694 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005695 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005696 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005697
Chris Lattner53e677a2004-04-02 20:23:17 +00005698 // If R1 was not in the range, then it is a good return value. Make
5699 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005700 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005701 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005702 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005703 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005704 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005705 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005706 }
5707 }
5708 }
5709
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005710 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005711}
5712
5713
5714
5715//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005716// SCEVCallbackVH Class Implementation
5717//===----------------------------------------------------------------------===//
5718
Dan Gohman1959b752009-05-19 19:22:47 +00005719void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005720 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005721 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5722 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005723 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00005724 // this now dangles!
5725}
5726
Dan Gohman81f91212010-07-28 01:09:07 +00005727void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005728 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005729
Dan Gohman35738ac2009-05-04 22:30:44 +00005730 // Forget all the expressions associated with users of the old value,
5731 // so that future queries will recompute the expressions using the new
5732 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005733 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005734 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005735 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005736 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5737 UI != UE; ++UI)
5738 Worklist.push_back(*UI);
5739 while (!Worklist.empty()) {
5740 User *U = Worklist.pop_back_val();
5741 // Deleting the Old value will cause this to dangle. Postpone
5742 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005743 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005744 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005745 if (!Visited.insert(U))
5746 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005747 if (PHINode *PN = dyn_cast<PHINode>(U))
5748 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005749 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00005750 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5751 UI != UE; ++UI)
5752 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005753 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005754 // Delete the Old value.
5755 if (PHINode *PN = dyn_cast<PHINode>(Old))
5756 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005757 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00005758 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005759}
5760
Dan Gohman1959b752009-05-19 19:22:47 +00005761ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005762 : CallbackVH(V), SE(se) {}
5763
5764//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005765// ScalarEvolution Class Implementation
5766//===----------------------------------------------------------------------===//
5767
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005768ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005769 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00005770 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005771}
5772
Chris Lattner53e677a2004-04-02 20:23:17 +00005773bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005774 this->F = &F;
5775 LI = &getAnalysis<LoopInfo>();
5776 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005777 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005778 return false;
5779}
5780
5781void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005782 // Iterate through all the SCEVUnknown instances and call their
5783 // destructors, so that they release their references to their values.
5784 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5785 U->~SCEVUnknown();
5786 FirstUnknown = 0;
5787
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005788 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005789 BackedgeTakenCounts.clear();
5790 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005791 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00005792 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00005793 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00005794 UnsignedRanges.clear();
5795 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005796 UniqueSCEVs.clear();
5797 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005798}
5799
5800void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5801 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005802 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005803 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005804}
5805
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005806bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005807 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005808}
5809
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005810static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005811 const Loop *L) {
5812 // Print all inner loops first
5813 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5814 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005815
Dan Gohman30733292010-01-09 18:17:45 +00005816 OS << "Loop ";
5817 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5818 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005819
Dan Gohman5d984912009-12-18 01:14:11 +00005820 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005821 L->getExitBlocks(ExitBlocks);
5822 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005823 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005824
Dan Gohman46bdfb02009-02-24 18:55:53 +00005825 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5826 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005827 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005828 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005829 }
5830
Dan Gohman30733292010-01-09 18:17:45 +00005831 OS << "\n"
5832 "Loop ";
5833 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5834 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005835
5836 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5837 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5838 } else {
5839 OS << "Unpredictable max backedge-taken count. ";
5840 }
5841
5842 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005843}
5844
Dan Gohman5d984912009-12-18 01:14:11 +00005845void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005846 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005847 // out SCEV values of all instructions that are interesting. Doing
5848 // this potentially causes it to create new SCEV objects though,
5849 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005850 // observable from outside the class though, so casting away the
5851 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005852 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005853
Dan Gohman30733292010-01-09 18:17:45 +00005854 OS << "Classifying expressions for: ";
5855 WriteAsOperand(OS, F, /*PrintType=*/false);
5856 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005857 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005858 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005859 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005860 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005861 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005862 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005863
Dan Gohman0c689c52009-06-19 17:49:54 +00005864 const Loop *L = LI->getLoopFor((*I).getParent());
5865
Dan Gohman0bba49c2009-07-07 17:06:11 +00005866 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005867 if (AtUse != SV) {
5868 OS << " --> ";
5869 AtUse->print(OS);
5870 }
5871
5872 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005873 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005874 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00005875 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005876 OS << "<<Unknown>>";
5877 } else {
5878 OS << *ExitValue;
5879 }
5880 }
5881
Chris Lattner53e677a2004-04-02 20:23:17 +00005882 OS << "\n";
5883 }
5884
Dan Gohman30733292010-01-09 18:17:45 +00005885 OS << "Determining loop execution counts for: ";
5886 WriteAsOperand(OS, F, /*PrintType=*/false);
5887 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005888 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5889 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005890}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005891
Dan Gohman714b5292010-11-17 23:21:44 +00005892ScalarEvolution::LoopDisposition
5893ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
5894 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
5895 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
5896 Values.insert(std::make_pair(L, LoopVariant));
5897 if (!Pair.second)
5898 return Pair.first->second;
5899
5900 LoopDisposition D = computeLoopDisposition(S, L);
5901 return LoopDispositions[S][L] = D;
5902}
5903
5904ScalarEvolution::LoopDisposition
5905ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00005906 switch (S->getSCEVType()) {
5907 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00005908 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005909 case scTruncate:
5910 case scZeroExtend:
5911 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00005912 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00005913 case scAddRecExpr: {
5914 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
5915
Dan Gohman714b5292010-11-17 23:21:44 +00005916 // If L is the addrec's loop, it's computable.
5917 if (AR->getLoop() == L)
5918 return LoopComputable;
5919
Dan Gohman17ead4f2010-11-17 21:23:15 +00005920 // Add recurrences are never invariant in the function-body (null loop).
5921 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00005922 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005923
5924 // This recurrence is variant w.r.t. L if L contains AR's loop.
5925 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00005926 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005927
5928 // This recurrence is invariant w.r.t. L if AR's loop contains L.
5929 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00005930 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005931
5932 // This recurrence is variant w.r.t. L if any of its operands
5933 // are variant.
5934 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
5935 I != E; ++I)
5936 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00005937 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005938
5939 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00005940 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005941 }
5942 case scAddExpr:
5943 case scMulExpr:
5944 case scUMaxExpr:
5945 case scSMaxExpr: {
5946 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00005947 bool HasVarying = false;
5948 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
5949 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00005950 LoopDisposition D = getLoopDisposition(*I, L);
5951 if (D == LoopVariant)
5952 return LoopVariant;
5953 if (D == LoopComputable)
5954 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005955 }
Dan Gohman714b5292010-11-17 23:21:44 +00005956 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005957 }
5958 case scUDivExpr: {
5959 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00005960 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
5961 if (LD == LoopVariant)
5962 return LoopVariant;
5963 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
5964 if (RD == LoopVariant)
5965 return LoopVariant;
5966 return (LD == LoopInvariant && RD == LoopInvariant) ?
5967 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005968 }
5969 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00005970 // All non-instruction values are loop invariant. All instructions are loop
5971 // invariant if they are not contained in the specified loop.
5972 // Instructions are never considered invariant in the function body
5973 // (null loop) because they are defined within the "loop".
5974 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
5975 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
5976 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005977 case scCouldNotCompute:
5978 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00005979 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005980 default: break;
5981 }
5982 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00005983 return LoopVariant;
5984}
5985
5986bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
5987 return getLoopDisposition(S, L) == LoopInvariant;
5988}
5989
5990bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
5991 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00005992}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005993
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00005994ScalarEvolution::BlockDisposition
5995ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
5996 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
5997 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
5998 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
5999 if (!Pair.second)
6000 return Pair.first->second;
6001
6002 BlockDisposition D = computeBlockDisposition(S, BB);
6003 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006004}
6005
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006006ScalarEvolution::BlockDisposition
6007ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006008 switch (S->getSCEVType()) {
6009 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006010 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006011 case scTruncate:
6012 case scZeroExtend:
6013 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006014 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006015 case scAddRecExpr: {
6016 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006017 // to test for proper dominance too, because the instruction which
6018 // produces the addrec's value is a PHI, and a PHI effectively properly
6019 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006020 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6021 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006022 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006023 }
6024 // FALL THROUGH into SCEVNAryExpr handling.
6025 case scAddExpr:
6026 case scMulExpr:
6027 case scUMaxExpr:
6028 case scSMaxExpr: {
6029 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006030 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006031 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006032 I != E; ++I) {
6033 BlockDisposition D = getBlockDisposition(*I, BB);
6034 if (D == DoesNotDominateBlock)
6035 return DoesNotDominateBlock;
6036 if (D == DominatesBlock)
6037 Proper = false;
6038 }
6039 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006040 }
6041 case scUDivExpr: {
6042 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006043 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6044 BlockDisposition LD = getBlockDisposition(LHS, BB);
6045 if (LD == DoesNotDominateBlock)
6046 return DoesNotDominateBlock;
6047 BlockDisposition RD = getBlockDisposition(RHS, BB);
6048 if (RD == DoesNotDominateBlock)
6049 return DoesNotDominateBlock;
6050 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6051 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006052 }
6053 case scUnknown:
6054 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006055 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6056 if (I->getParent() == BB)
6057 return DominatesBlock;
6058 if (DT->properlyDominates(I->getParent(), BB))
6059 return ProperlyDominatesBlock;
6060 return DoesNotDominateBlock;
6061 }
6062 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006063 case scCouldNotCompute:
6064 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006065 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006066 default: break;
6067 }
6068 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006069 return DoesNotDominateBlock;
6070}
6071
6072bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6073 return getBlockDisposition(S, BB) >= DominatesBlock;
6074}
6075
6076bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6077 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006078}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006079
6080bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6081 switch (S->getSCEVType()) {
6082 case scConstant:
6083 return false;
6084 case scTruncate:
6085 case scZeroExtend:
6086 case scSignExtend: {
6087 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6088 const SCEV *CastOp = Cast->getOperand();
6089 return Op == CastOp || hasOperand(CastOp, Op);
6090 }
6091 case scAddRecExpr:
6092 case scAddExpr:
6093 case scMulExpr:
6094 case scUMaxExpr:
6095 case scSMaxExpr: {
6096 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6097 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6098 I != E; ++I) {
6099 const SCEV *NAryOp = *I;
6100 if (NAryOp == Op || hasOperand(NAryOp, Op))
6101 return true;
6102 }
6103 return false;
6104 }
6105 case scUDivExpr: {
6106 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6107 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6108 return LHS == Op || hasOperand(LHS, Op) ||
6109 RHS == Op || hasOperand(RHS, Op);
6110 }
6111 case scUnknown:
6112 return false;
6113 case scCouldNotCompute:
6114 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6115 return false;
6116 default: break;
6117 }
6118 llvm_unreachable("Unknown SCEV kind!");
6119 return false;
6120}
Dan Gohman56a75682010-11-17 23:28:48 +00006121
6122void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6123 ValuesAtScopes.erase(S);
6124 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006125 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006126 UnsignedRanges.erase(S);
6127 SignedRanges.erase(S);
6128}