blob: 50a25252d2fac148f9e6dd64253171999b26f795 [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 << "}<";
Andrew Trick3228cc22011-03-14 16:50:06 +0000160 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnerf1859892011-01-09 02:16:18 +0000161 OS << "nuw><";
Andrew Trick3228cc22011-03-14 16:50:06 +0000162 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnerf1859892011-01-09 02:16:18 +0000163 OS << "nsw><";
Andrew Trick3228cc22011-03-14 16:50:06 +0000164 if (AR->getNoWrapFlags(FlagNW) &&
165 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
166 OS << "nw><";
Dan Gohman4ce32db2010-11-17 22:27:42 +0000167 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
168 OS << ">";
169 return;
170 }
171 case scAddExpr:
172 case scMulExpr:
173 case scUMaxExpr:
174 case scSMaxExpr: {
175 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Benjamin Kramerb458b152010-11-19 11:37:26 +0000176 const char *OpStr = 0;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000177 switch (NAry->getSCEVType()) {
178 case scAddExpr: OpStr = " + "; break;
179 case scMulExpr: OpStr = " * "; break;
180 case scUMaxExpr: OpStr = " umax "; break;
181 case scSMaxExpr: OpStr = " smax "; break;
182 }
183 OS << "(";
184 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
185 I != E; ++I) {
186 OS << **I;
187 if (llvm::next(I) != E)
188 OS << OpStr;
189 }
190 OS << ")";
191 return;
192 }
193 case scUDivExpr: {
194 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
195 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
196 return;
197 }
198 case scUnknown: {
199 const SCEVUnknown *U = cast<SCEVUnknown>(this);
200 const Type *AllocTy;
201 if (U->isSizeOf(AllocTy)) {
202 OS << "sizeof(" << *AllocTy << ")";
203 return;
204 }
205 if (U->isAlignOf(AllocTy)) {
206 OS << "alignof(" << *AllocTy << ")";
207 return;
208 }
Andrew Trick635f7182011-03-09 17:23:39 +0000209
Dan Gohman4ce32db2010-11-17 22:27:42 +0000210 const Type *CTy;
211 Constant *FieldNo;
212 if (U->isOffsetOf(CTy, FieldNo)) {
213 OS << "offsetof(" << *CTy << ", ";
214 WriteAsOperand(OS, FieldNo, false);
215 OS << ")";
216 return;
217 }
Andrew Trick635f7182011-03-09 17:23:39 +0000218
Dan Gohman4ce32db2010-11-17 22:27:42 +0000219 // Otherwise just print it normally.
220 WriteAsOperand(OS, U->getValue(), false);
221 return;
222 }
223 case scCouldNotCompute:
224 OS << "***COULDNOTCOMPUTE***";
225 return;
226 default: break;
227 }
228 llvm_unreachable("Unknown SCEV kind!");
229}
230
231const Type *SCEV::getType() const {
232 switch (getSCEVType()) {
233 case scConstant:
234 return cast<SCEVConstant>(this)->getType();
235 case scTruncate:
236 case scZeroExtend:
237 case scSignExtend:
238 return cast<SCEVCastExpr>(this)->getType();
239 case scAddRecExpr:
240 case scMulExpr:
241 case scUMaxExpr:
242 case scSMaxExpr:
243 return cast<SCEVNAryExpr>(this)->getType();
244 case scAddExpr:
245 return cast<SCEVAddExpr>(this)->getType();
246 case scUDivExpr:
247 return cast<SCEVUDivExpr>(this)->getType();
248 case scUnknown:
249 return cast<SCEVUnknown>(this)->getType();
250 case scCouldNotCompute:
251 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
252 return 0;
253 default: break;
254 }
255 llvm_unreachable("Unknown SCEV kind!");
256 return 0;
257}
258
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000259bool SCEV::isZero() const {
260 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
261 return SC->getValue()->isZero();
262 return false;
263}
264
Dan Gohman70a1fe72009-05-18 15:22:39 +0000265bool SCEV::isOne() const {
266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
267 return SC->getValue()->isOne();
268 return false;
269}
Chris Lattner53e677a2004-04-02 20:23:17 +0000270
Dan Gohman4d289bf2009-06-24 00:30:26 +0000271bool SCEV::isAllOnesValue() const {
272 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
273 return SC->getValue()->isAllOnesValue();
274 return false;
275}
276
Owen Anderson753ad612009-06-22 21:57:23 +0000277SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000278 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000279
Chris Lattner53e677a2004-04-02 20:23:17 +0000280bool SCEVCouldNotCompute::classof(const SCEV *S) {
281 return S->getSCEVType() == scCouldNotCompute;
282}
283
Dan Gohman0bba49c2009-07-07 17:06:11 +0000284const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000285 FoldingSetNodeID ID;
286 ID.AddInteger(scConstant);
287 ID.AddPointer(V);
288 void *IP = 0;
289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000290 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000291 UniqueSCEVs.InsertNode(S, IP);
292 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000293}
Chris Lattner53e677a2004-04-02 20:23:17 +0000294
Dan Gohman0bba49c2009-07-07 17:06:11 +0000295const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000296 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000297}
298
Dan Gohman0bba49c2009-07-07 17:06:11 +0000299const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000300ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000301 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
302 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000303}
304
Dan Gohman3bf63762010-06-18 19:54:20 +0000305SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000306 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000307 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000308
Dan Gohman3bf63762010-06-18 19:54:20 +0000309SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000310 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000311 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000312 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
313 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315}
Chris Lattner53e677a2004-04-02 20:23:17 +0000316
Dan Gohman3bf63762010-06-18 19:54:20 +0000317SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000318 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000319 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000320 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
321 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000323}
324
Dan Gohman3bf63762010-06-18 19:54:20 +0000325SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000326 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000327 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000328 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
329 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000330 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000331}
332
Dan Gohmanab37f502010-08-02 23:49:30 +0000333void SCEVUnknown::deleted() {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000334 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000335 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000336
337 // Remove this SCEVUnknown from the uniquing map.
338 SE->UniqueSCEVs.RemoveNode(this);
339
340 // Release the value.
341 setValPtr(0);
342}
343
344void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000345 // Clear this SCEVUnknown from various maps.
Dan Gohman56a75682010-11-17 23:28:48 +0000346 SE->forgetMemoizedResults(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000347
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
350
351 // Update this SCEVUnknown to point to the new value. This is needed
352 // because there may still be outstanding SCEVs which still point to
353 // this SCEVUnknown.
354 setValPtr(New);
355}
356
Dan Gohman0f5efe52010-01-28 02:15:55 +0000357bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000358 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000359 if (VCE->getOpcode() == Instruction::PtrToInt)
360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000361 if (CE->getOpcode() == Instruction::GetElementPtr &&
362 CE->getOperand(0)->isNullValue() &&
363 CE->getNumOperands() == 2)
364 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
365 if (CI->isOne()) {
366 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
367 ->getElementType();
368 return true;
369 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000370
371 return false;
372}
373
374bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000375 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000376 if (VCE->getOpcode() == Instruction::PtrToInt)
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000378 if (CE->getOpcode() == Instruction::GetElementPtr &&
379 CE->getOperand(0)->isNullValue()) {
380 const Type *Ty =
381 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
382 if (const StructType *STy = dyn_cast<StructType>(Ty))
383 if (!STy->isPacked() &&
384 CE->getNumOperands() == 3 &&
385 CE->getOperand(1)->isNullValue()) {
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
387 if (CI->isOne() &&
388 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000389 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000390 AllocTy = STy->getElementType(1);
391 return true;
392 }
393 }
394 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000395
396 return false;
397}
398
Dan Gohman4f8eea82010-02-01 18:27:38 +0000399bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000400 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000401 if (VCE->getOpcode() == Instruction::PtrToInt)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
403 if (CE->getOpcode() == Instruction::GetElementPtr &&
404 CE->getNumOperands() == 3 &&
405 CE->getOperand(0)->isNullValue() &&
406 CE->getOperand(1)->isNullValue()) {
407 const Type *Ty =
408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
409 // Ignore vector types here so that ScalarEvolutionExpander doesn't
410 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000411 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000412 CTy = Ty;
413 FieldNo = CE->getOperand(2);
414 return true;
415 }
416 }
417
418 return false;
419}
420
Chris Lattner8d741b82004-06-20 06:23:15 +0000421//===----------------------------------------------------------------------===//
422// SCEV Utilities
423//===----------------------------------------------------------------------===//
424
425namespace {
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
428 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000429 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000430 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000431 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000432 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000433
Dan Gohman67ef74e2010-08-27 15:26:01 +0000434 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000435 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman67ef74e2010-08-27 15:26:01 +0000436 return compare(LHS, RHS) < 0;
437 }
438
439 // Return negative, zero, or positive, if LHS is less than, equal to, or
440 // greater than RHS, respectively. A three-way result allows recursive
441 // comparisons to be more efficient.
442 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000443 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
444 if (LHS == RHS)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000445 return 0;
Dan Gohman42214892009-08-31 21:15:23 +0000446
Dan Gohman72861302009-05-07 14:39:04 +0000447 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000448 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
449 if (LType != RType)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000450 return (int)LType - (int)RType;
Dan Gohman72861302009-05-07 14:39:04 +0000451
Dan Gohman3bf63762010-06-18 19:54:20 +0000452 // Aside from the getSCEVType() ordering, the particular ordering
453 // isn't very important except that it's beneficial to be consistent,
454 // so that (a + b) and (b + a) don't end up as different expressions.
Dan Gohman67ef74e2010-08-27 15:26:01 +0000455 switch (LType) {
456 case scUnknown: {
457 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000458 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000459
460 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
461 // not as complete as it could be.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000462 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000463
464 // Order pointer values after integer values. This helps SCEVExpander
465 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000466 bool LIsPointer = LV->getType()->isPointerTy(),
467 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000468 if (LIsPointer != RIsPointer)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000469 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000470
471 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000472 unsigned LID = LV->getValueID(),
473 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000474 if (LID != RID)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000475 return (int)LID - (int)RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000476
477 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000478 if (const Argument *LA = dyn_cast<Argument>(LV)) {
479 const Argument *RA = cast<Argument>(RV);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000480 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
481 return (int)LArgNo - (int)RArgNo;
Dan Gohman3bf63762010-06-18 19:54:20 +0000482 }
483
Dan Gohman67ef74e2010-08-27 15:26:01 +0000484 // For instructions, compare their loop depth, and their operand
485 // count. This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000486 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
487 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000488
489 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000490 const BasicBlock *LParent = LInst->getParent(),
491 *RParent = RInst->getParent();
492 if (LParent != RParent) {
493 unsigned LDepth = LI->getLoopDepth(LParent),
494 RDepth = LI->getLoopDepth(RParent);
495 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000496 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000497 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000498
499 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000500 unsigned LNumOps = LInst->getNumOperands(),
501 RNumOps = RInst->getNumOperands();
Dan Gohman67ef74e2010-08-27 15:26:01 +0000502 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000503 }
504
Dan Gohman67ef74e2010-08-27 15:26:01 +0000505 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000506 }
507
Dan Gohman67ef74e2010-08-27 15:26:01 +0000508 case scConstant: {
509 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000510 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000511
512 // Compare constant values.
Dan Gohmane28d7922010-08-16 16:25:35 +0000513 const APInt &LA = LC->getValue()->getValue();
514 const APInt &RA = RC->getValue()->getValue();
515 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000516 if (LBitWidth != RBitWidth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000517 return (int)LBitWidth - (int)RBitWidth;
518 return LA.ult(RA) ? -1 : 1;
Dan Gohman3bf63762010-06-18 19:54:20 +0000519 }
520
Dan Gohman67ef74e2010-08-27 15:26:01 +0000521 case scAddRecExpr: {
522 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000523 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000524
525 // Compare addrec loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000526 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
527 if (LLoop != RLoop) {
528 unsigned LDepth = LLoop->getLoopDepth(),
529 RDepth = RLoop->getLoopDepth();
530 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000531 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000532 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000533
534 // Addrec complexity grows with operand count.
535 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
536 if (LNumOps != RNumOps)
537 return (int)LNumOps - (int)RNumOps;
538
539 // Lexicographically compare.
540 for (unsigned i = 0; i != LNumOps; ++i) {
541 long X = compare(LA->getOperand(i), RA->getOperand(i));
542 if (X != 0)
543 return X;
544 }
545
546 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000547 }
548
Dan Gohman67ef74e2010-08-27 15:26:01 +0000549 case scAddExpr:
550 case scMulExpr:
551 case scSMaxExpr:
552 case scUMaxExpr: {
553 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000554 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000555
556 // Lexicographically compare n-ary expressions.
Dan Gohman304a7a62010-07-23 21:20:52 +0000557 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
558 for (unsigned i = 0; i != LNumOps; ++i) {
559 if (i >= RNumOps)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000560 return 1;
561 long X = compare(LC->getOperand(i), RC->getOperand(i));
562 if (X != 0)
563 return X;
Dan Gohman3bf63762010-06-18 19:54:20 +0000564 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000565 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000566 }
567
Dan Gohman67ef74e2010-08-27 15:26:01 +0000568 case scUDivExpr: {
569 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000570 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000571
572 // Lexicographically compare udiv expressions.
573 long X = compare(LC->getLHS(), RC->getLHS());
574 if (X != 0)
575 return X;
576 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman3bf63762010-06-18 19:54:20 +0000577 }
578
Dan Gohman67ef74e2010-08-27 15:26:01 +0000579 case scTruncate:
580 case scZeroExtend:
581 case scSignExtend: {
582 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000583 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000584
585 // Compare cast expressions by operand.
586 return compare(LC->getOperand(), RC->getOperand());
587 }
588
589 default:
590 break;
Dan Gohman3bf63762010-06-18 19:54:20 +0000591 }
592
593 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman67ef74e2010-08-27 15:26:01 +0000594 return 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000595 }
596 };
597}
598
599/// GroupByComplexity - Given a list of SCEV objects, order them by their
600/// complexity, and group objects of the same complexity together by value.
601/// When this routine is finished, we know that any duplicates in the vector are
602/// consecutive and that complexity is monotonically increasing.
603///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000604/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000605/// results from this routine. In other words, we don't want the results of
606/// this to depend on where the addresses of various SCEV objects happened to
607/// land in memory.
608///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000609static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000610 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000611 if (Ops.size() < 2) return; // Noop
612 if (Ops.size() == 2) {
613 // This is the common case, which also happens to be trivially simple.
614 // Special case it.
Dan Gohmanc6a8e992010-08-29 15:07:13 +0000615 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
616 if (SCEVComplexityCompare(LI)(RHS, LHS))
617 std::swap(LHS, RHS);
Chris Lattner8d741b82004-06-20 06:23:15 +0000618 return;
619 }
620
Dan Gohman3bf63762010-06-18 19:54:20 +0000621 // Do the rough sort by complexity.
622 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
623
624 // Now that we are sorted by complexity, group elements of the same
625 // complexity. Note that this is, at worst, N^2, but the vector is likely to
626 // be extremely short in practice. Note that we take this approach because we
627 // do not want to depend on the addresses of the objects we are grouping.
628 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
629 const SCEV *S = Ops[i];
630 unsigned Complexity = S->getSCEVType();
631
632 // If there are any objects of the same complexity and same value as this
633 // one, group them.
634 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
635 if (Ops[j] == S) { // Found a duplicate.
636 // Move it to immediately after i'th element.
637 std::swap(Ops[i+1], Ops[j]);
638 ++i; // no need to rescan it.
639 if (i == e-2) return; // Done!
640 }
641 }
642 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645
Chris Lattner53e677a2004-04-02 20:23:17 +0000646
647//===----------------------------------------------------------------------===//
648// Simple SCEV method implementations
649//===----------------------------------------------------------------------===//
650
Eli Friedmanb42a6262008-08-04 23:49:06 +0000651/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000652/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000653static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000654 ScalarEvolution &SE,
655 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000656 // Handle the simplest case efficiently.
657 if (K == 1)
658 return SE.getTruncateOrZeroExtend(It, ResultTy);
659
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000660 // We are using the following formula for BC(It, K):
661 //
662 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
663 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000664 // Suppose, W is the bitwidth of the return value. We must be prepared for
665 // overflow. Hence, we must assure that the result of our computation is
666 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
667 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000668 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000670 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
672 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000673 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000674 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000675 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000676 // This formula is trivially equivalent to the previous formula. However,
677 // this formula can be implemented much more efficiently. The trick is that
678 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
679 // arithmetic. To do exact division in modular arithmetic, all we have
680 // to do is multiply by the inverse. Therefore, this step can be done at
681 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000682 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000683 // The next issue is how to safely do the division by 2^T. The way this
684 // is done is by doing the multiplication step at a width of at least W + T
685 // bits. This way, the bottom W+T bits of the product are accurate. Then,
686 // when we perform the division by 2^T (which is equivalent to a right shift
687 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
688 // truncated out after the division by 2^T.
689 //
690 // In comparison to just directly using the first formula, this technique
691 // is much more efficient; using the first formula requires W * K bits,
692 // but this formula less than W + K bits. Also, the first formula requires
693 // a division step, whereas this formula only requires multiplies and shifts.
694 //
695 // It doesn't matter whether the subtraction step is done in the calculation
696 // width or the input iteration count's width; if the subtraction overflows,
697 // the result must be zero anyway. We prefer here to do it in the width of
698 // the induction variable because it helps a lot for certain cases; CodeGen
699 // isn't smart enough to ignore the overflow, which leads to much less
700 // efficient code if the width of the subtraction is wider than the native
701 // register width.
702 //
703 // (It's possible to not widen at all by pulling out factors of 2 before
704 // the multiplication; for example, K=2 can be calculated as
705 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
706 // extra arithmetic, so it's not an obvious win, and it gets
707 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000708
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709 // Protection from insane SCEVs; this bound is conservative,
710 // but it probably doesn't matter.
711 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000712 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000713
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000714 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000715
Eli Friedmanb42a6262008-08-04 23:49:06 +0000716 // Calculate K! / 2^T and T; we divide out the factors of two before
717 // multiplying for calculating K! / 2^T to avoid overflow.
718 // Other overflow doesn't matter because we only care about the bottom
719 // W bits of the result.
720 APInt OddFactorial(W, 1);
721 unsigned T = 1;
722 for (unsigned i = 3; i <= K; ++i) {
723 APInt Mult(W, i);
724 unsigned TwoFactors = Mult.countTrailingZeros();
725 T += TwoFactors;
726 Mult = Mult.lshr(TwoFactors);
727 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000728 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000729
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000731 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000732
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000733 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000734 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
735
736 // Calculate the multiplicative inverse of K! / 2^T;
737 // this multiplication factor will perform the exact division by
738 // K! / 2^T.
739 APInt Mod = APInt::getSignedMinValue(W+1);
740 APInt MultiplyFactor = OddFactorial.zext(W+1);
741 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
742 MultiplyFactor = MultiplyFactor.trunc(W);
743
744 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000745 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
746 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000747 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000748 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000749 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000750 Dividend = SE.getMulExpr(Dividend,
751 SE.getTruncateOrZeroExtend(S, CalculationTy));
752 }
753
754 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000755 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000756
757 // Truncate the result, and divide by K! / 2^T.
758
759 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
760 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000761}
762
Chris Lattner53e677a2004-04-02 20:23:17 +0000763/// evaluateAtIteration - Return the value of this chain of recurrences at
764/// the specified iteration number. We can evaluate this recurrence by
765/// multiplying each element in the chain by the binomial coefficient
766/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
767///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000768/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000769///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000770/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000771///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000772const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000773 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000774 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000775 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000776 // The computation is correct in the face of overflow provided that the
777 // multiplication is performed _after_ the evaluation of the binomial
778 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000779 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000780 if (isa<SCEVCouldNotCompute>(Coeff))
781 return Coeff;
782
783 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000784 }
785 return Result;
786}
787
Chris Lattner53e677a2004-04-02 20:23:17 +0000788//===----------------------------------------------------------------------===//
789// SCEV Expression folder implementations
790//===----------------------------------------------------------------------===//
791
Dan Gohman0bba49c2009-07-07 17:06:11 +0000792const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000793 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000794 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000795 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000796 assert(isSCEVable(Ty) &&
797 "This is not a conversion to a SCEVable type!");
798 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000799
Dan Gohmanc050fd92009-07-13 20:50:19 +0000800 FoldingSetNodeID ID;
801 ID.AddInteger(scTruncate);
802 ID.AddPointer(Op);
803 ID.AddPointer(Ty);
804 void *IP = 0;
805 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
806
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000807 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000808 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000809 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000810 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
811 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000812
Dan Gohman20900ca2009-04-22 16:20:48 +0000813 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000814 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000815 return getTruncateExpr(ST->getOperand(), Ty);
816
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000817 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000818 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000819 return getTruncateOrSignExtend(SS->getOperand(), Ty);
820
821 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000823 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
824
Nick Lewycky30aa8b12011-01-19 16:59:46 +0000825 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
826 // eliminate all the truncates.
827 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
828 SmallVector<const SCEV *, 4> Operands;
829 bool hasTrunc = false;
830 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
831 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
832 hasTrunc = isa<SCEVTruncateExpr>(S);
833 Operands.push_back(S);
834 }
835 if (!hasTrunc)
Andrew Trick3228cc22011-03-14 16:50:06 +0000836 return getAddExpr(Operands);
Nick Lewyckye19b7b82011-01-26 08:40:22 +0000837 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky30aa8b12011-01-19 16:59:46 +0000838 }
839
Nick Lewycky5c6fc1c2011-01-19 18:56:00 +0000840 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
841 // eliminate all the truncates.
842 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
843 SmallVector<const SCEV *, 4> Operands;
844 bool hasTrunc = false;
845 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
846 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
847 hasTrunc = isa<SCEVTruncateExpr>(S);
848 Operands.push_back(S);
849 }
850 if (!hasTrunc)
Andrew Trick3228cc22011-03-14 16:50:06 +0000851 return getMulExpr(Operands);
Nick Lewyckye19b7b82011-01-26 08:40:22 +0000852 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c6fc1c2011-01-19 18:56:00 +0000853 }
854
Dan Gohman6864db62009-06-18 16:24:47 +0000855 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000856 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000857 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000859 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Andrew Trick3228cc22011-03-14 16:50:06 +0000860 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +0000861 }
862
Dan Gohmanf53462d2010-07-15 20:02:11 +0000863 // As a special case, fold trunc(undef) to undef. We don't want to
864 // know too much about SCEVUnknowns, but this special case is handy
865 // and harmless.
866 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
867 if (isa<UndefValue>(U->getValue()))
868 return getSCEV(UndefValue::get(Ty));
869
Dan Gohman420ab912010-06-25 18:47:08 +0000870 // The cast wasn't folded; create an explicit cast node. We can reuse
871 // the existing insert position since if we get here, we won't have
872 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000873 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
874 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000875 UniqueSCEVs.InsertNode(S, IP);
876 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000877}
878
Dan Gohman0bba49c2009-07-07 17:06:11 +0000879const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000880 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000881 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000882 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000883 assert(isSCEVable(Ty) &&
884 "This is not a conversion to a SCEVable type!");
885 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000886
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000887 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000888 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
889 return getConstant(
890 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
891 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000892
Dan Gohman20900ca2009-04-22 16:20:48 +0000893 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000894 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000895 return getZeroExtendExpr(SZ->getOperand(), Ty);
896
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000897 // Before doing any expensive analysis, check to see if we've already
898 // computed a SCEV for this Op and Ty.
899 FoldingSetNodeID ID;
900 ID.AddInteger(scZeroExtend);
901 ID.AddPointer(Op);
902 ID.AddPointer(Ty);
903 void *IP = 0;
904 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
905
Nick Lewycky630d85a2011-01-23 06:20:19 +0000906 // zext(trunc(x)) --> zext(x) or x or trunc(x)
907 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
908 // It's possible the bits taken off by the truncate were all zero bits. If
909 // so, we should be able to simplify this further.
910 const SCEV *X = ST->getOperand();
911 ConstantRange CR = getUnsignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +0000912 unsigned TruncBits = getTypeSizeInBits(ST->getType());
913 unsigned NewBits = getTypeSizeInBits(Ty);
914 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +0000915 CR.zextOrTrunc(NewBits)))
916 return getTruncateOrZeroExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +0000917 }
918
Dan Gohman01ecca22009-04-27 20:16:15 +0000919 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000920 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000921 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000922 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000924 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000925 const SCEV *Start = AR->getStart();
926 const SCEV *Step = AR->getStepRecurrence(*this);
927 unsigned BitWidth = getTypeSizeInBits(AR->getType());
928 const Loop *L = AR->getLoop();
929
Dan Gohmaneb490a72009-07-25 01:22:26 +0000930 // If we have special knowledge that this addrec won't overflow,
931 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +0000932 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmaneb490a72009-07-25 01:22:26 +0000933 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
934 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +0000935 L, AR->getNoWrapFlags());
Dan Gohmaneb490a72009-07-25 01:22:26 +0000936
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 // Check whether the backedge-taken count is SCEVCouldNotCompute.
938 // Note that this serves two purposes: It filters out loops that are
939 // simply not analyzable, and it covers the case where this code is
940 // being called from within backedge-taken count analysis, such that
941 // attempting to ask for the backedge-taken count would likely result
942 // in infinite recursion. In the later case, the analysis code will
943 // cope with a conservative value, and it will take care to purge
944 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000945 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000946 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000947 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000948 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000949
950 // Check whether the backedge-taken count can be losslessly casted to
951 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000953 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000954 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000955 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000957 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000958 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000959 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000960 const SCEV *Add = getAddExpr(Start, ZMul);
961 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000962 getAddExpr(getZeroExtendExpr(Start, WideTy),
963 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
964 getZeroExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +0000965 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
966 // Cache knowledge of AR NUW, which is propagated to this AddRec.
967 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000968 // Return the expression with the addrec on the outside.
969 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
970 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +0000971 L, AR->getNoWrapFlags());
972 }
Dan Gohman01ecca22009-04-27 20:16:15 +0000973 // Similar to above, only this time treat the step value as signed.
974 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000975 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000976 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000977 OperandExtendedAdd =
978 getAddExpr(getZeroExtendExpr(Start, WideTy),
979 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
980 getSignExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +0000981 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
982 // Cache knowledge of AR NW, which is propagated to this AddRec.
983 // Negative step causes unsigned wrap, but it still can't self-wrap.
984 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000985 // Return the expression with the addrec on the outside.
986 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
987 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +0000988 L, AR->getNoWrapFlags());
989 }
Dan Gohman85b05a22009-07-13 21:35:55 +0000990 }
991
992 // If the backedge is guarded by a comparison with the pre-inc value
993 // the addrec is safe. Also, if the entry is guarded by a comparison
994 // with the start value and the backedge is guarded by a comparison
995 // with the post-inc value, the addrec is safe.
996 if (isKnownPositive(Step)) {
997 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998 getUnsignedRange(Step).getUnsignedMax());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001002 AR->getPostIncExpr(*this), N))) {
1003 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1004 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman85b05a22009-07-13 21:35:55 +00001005 // Return the expression with the addrec on the outside.
1006 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1007 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001008 L, AR->getNoWrapFlags());
1009 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001010 } else if (isKnownNegative(Step)) {
1011 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1012 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001013 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1014 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001015 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001016 AR->getPostIncExpr(*this), N))) {
1017 // Cache knowledge of AR NW, which is propagated to this AddRec.
1018 // Negative step causes unsigned wrap, but it still can't self-wrap.
1019 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1020 // Return the expression with the addrec on the outside.
Dan Gohman85b05a22009-07-13 21:35:55 +00001021 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1022 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001023 L, AR->getNoWrapFlags());
1024 }
Dan Gohman01ecca22009-04-27 20:16:15 +00001025 }
1026 }
1027 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001028
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001029 // The cast wasn't folded; create an explicit cast node.
1030 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001031 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001032 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1033 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001034 UniqueSCEVs.InsertNode(S, IP);
1035 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001036}
1037
Dan Gohman0bba49c2009-07-07 17:06:11 +00001038const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001039 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001040 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001041 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001042 assert(isSCEVable(Ty) &&
1043 "This is not a conversion to a SCEVable type!");
1044 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001045
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001046 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001047 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1048 return getConstant(
1049 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1050 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001051
Dan Gohman20900ca2009-04-22 16:20:48 +00001052 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001053 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001054 return getSignExtendExpr(SS->getOperand(), Ty);
1055
Nick Lewycky73f565e2011-01-19 15:56:12 +00001056 // sext(zext(x)) --> zext(x)
1057 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1058 return getZeroExtendExpr(SZ->getOperand(), Ty);
1059
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001060 // Before doing any expensive analysis, check to see if we've already
1061 // computed a SCEV for this Op and Ty.
1062 FoldingSetNodeID ID;
1063 ID.AddInteger(scSignExtend);
1064 ID.AddPointer(Op);
1065 ID.AddPointer(Ty);
1066 void *IP = 0;
1067 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1068
Nick Lewycky9b8d2c22011-01-22 22:06:21 +00001069 // If the input value is provably positive, build a zext instead.
1070 if (isKnownNonNegative(Op))
1071 return getZeroExtendExpr(Op, Ty);
1072
Nick Lewycky630d85a2011-01-23 06:20:19 +00001073 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1074 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1075 // It's possible the bits taken off by the truncate were all sign bits. If
1076 // so, we should be able to simplify this further.
1077 const SCEV *X = ST->getOperand();
1078 ConstantRange CR = getSignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001079 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1080 unsigned NewBits = getTypeSizeInBits(Ty);
1081 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +00001082 CR.sextOrTrunc(NewBits)))
1083 return getTruncateOrSignExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001084 }
1085
Dan Gohman01ecca22009-04-27 20:16:15 +00001086 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001087 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001088 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001089 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001090 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001091 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001092 const SCEV *Start = AR->getStart();
1093 const SCEV *Step = AR->getStepRecurrence(*this);
1094 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1095 const Loop *L = AR->getLoop();
1096
Dan Gohmaneb490a72009-07-25 01:22:26 +00001097 // If we have special knowledge that this addrec won't overflow,
1098 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +00001099 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Dan Gohmaneb490a72009-07-25 01:22:26 +00001100 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1101 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001102 L, SCEV::FlagNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00001103
Dan Gohman01ecca22009-04-27 20:16:15 +00001104 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1105 // Note that this serves two purposes: It filters out loops that are
1106 // simply not analyzable, and it covers the case where this code is
1107 // being called from within backedge-taken count analysis, such that
1108 // attempting to ask for the backedge-taken count would likely result
1109 // in infinite recursion. In the later case, the analysis code will
1110 // cope with a conservative value, and it will take care to purge
1111 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001112 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001113 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001114 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001115 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001116
1117 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001118 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001119 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001120 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001121 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001122 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1123 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001124 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001125 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001126 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001127 const SCEV *Add = getAddExpr(Start, SMul);
1128 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001129 getAddExpr(getSignExtendExpr(Start, WideTy),
1130 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1131 getSignExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001132 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1133 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1134 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohmanac70cea2009-04-29 22:28:28 +00001135 // Return the expression with the addrec on the outside.
1136 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1137 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001138 L, AR->getNoWrapFlags());
1139 }
Dan Gohman850f7912009-07-16 17:34:36 +00001140 // Similar to above, only this time treat the step value as unsigned.
1141 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001142 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001143 Add = getAddExpr(Start, UMul);
1144 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001145 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001146 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1147 getZeroExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001148 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1149 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1150 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman850f7912009-07-16 17:34:36 +00001151 // Return the expression with the addrec on the outside.
1152 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1153 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001154 L, AR->getNoWrapFlags());
1155 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001156 }
1157
1158 // If the backedge is guarded by a comparison with the pre-inc value
1159 // the addrec is safe. Also, if the entry is guarded by a comparison
1160 // with the start value and the backedge is guarded by a comparison
1161 // with the post-inc value, the addrec is safe.
1162 if (isKnownPositive(Step)) {
1163 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1164 getSignedRange(Step).getSignedMax());
1165 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001166 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001167 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001168 AR->getPostIncExpr(*this), N))) {
1169 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1170 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman85b05a22009-07-13 21:35:55 +00001171 // Return the expression with the addrec on the outside.
1172 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1173 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001174 L, AR->getNoWrapFlags());
1175 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001176 } else if (isKnownNegative(Step)) {
1177 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1178 getSignedRange(Step).getSignedMin());
1179 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001180 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001181 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
Andrew Trickc343c1e2011-03-15 00:37:00 +00001182 AR->getPostIncExpr(*this), N))) {
1183 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1184 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman85b05a22009-07-13 21:35:55 +00001185 // Return the expression with the addrec on the outside.
1186 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1187 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001188 L, AR->getNoWrapFlags());
1189 }
Dan Gohman01ecca22009-04-27 20:16:15 +00001190 }
1191 }
1192 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001193
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001194 // The cast wasn't folded; create an explicit cast node.
1195 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001196 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001197 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1198 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001199 UniqueSCEVs.InsertNode(S, IP);
1200 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001201}
1202
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001203/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1204/// unspecified bits out to the given type.
1205///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001206const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001207 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001208 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1209 "This is not an extending conversion!");
1210 assert(isSCEVable(Ty) &&
1211 "This is not a conversion to a SCEVable type!");
1212 Ty = getEffectiveSCEVType(Ty);
1213
1214 // Sign-extend negative constants.
1215 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1216 if (SC->getValue()->getValue().isNegative())
1217 return getSignExtendExpr(Op, Ty);
1218
1219 // Peel off a truncate cast.
1220 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001221 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001222 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1223 return getAnyExtendExpr(NewOp, Ty);
1224 return getTruncateOrNoop(NewOp, Ty);
1225 }
1226
1227 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001228 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001229 if (!isa<SCEVZeroExtendExpr>(ZExt))
1230 return ZExt;
1231
1232 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001233 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001234 if (!isa<SCEVSignExtendExpr>(SExt))
1235 return SExt;
1236
Dan Gohmana10756e2010-01-21 02:09:26 +00001237 // Force the cast to be folded into the operands of an addrec.
1238 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1239 SmallVector<const SCEV *, 4> Ops;
1240 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1241 I != E; ++I)
1242 Ops.push_back(getAnyExtendExpr(*I, Ty));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001243 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00001244 }
1245
Dan Gohmanf53462d2010-07-15 20:02:11 +00001246 // As a special case, fold anyext(undef) to undef. We don't want to
1247 // know too much about SCEVUnknowns, but this special case is handy
1248 // and harmless.
1249 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1250 if (isa<UndefValue>(U->getValue()))
1251 return getSCEV(UndefValue::get(Ty));
1252
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001253 // If the expression is obviously signed, use the sext cast value.
1254 if (isa<SCEVSMaxExpr>(Op))
1255 return SExt;
1256
1257 // Absent any other information, use the zext cast value.
1258 return ZExt;
1259}
1260
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001261/// CollectAddOperandsWithScales - Process the given Ops list, which is
1262/// a list of operands to be added under the given scale, update the given
1263/// map. This is a helper function for getAddRecExpr. As an example of
1264/// what it does, given a sequence of operands that would form an add
1265/// expression like this:
1266///
1267/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1268///
1269/// where A and B are constants, update the map with these values:
1270///
1271/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1272///
1273/// and add 13 + A*B*29 to AccumulatedConstant.
1274/// This will allow getAddRecExpr to produce this:
1275///
1276/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1277///
1278/// This form often exposes folding opportunities that are hidden in
1279/// the original operand list.
1280///
1281/// Return true iff it appears that any interesting folding opportunities
1282/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1283/// the common case where no interesting opportunities are present, and
1284/// is also used as a check to avoid infinite recursion.
1285///
1286static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001287CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1288 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001289 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001290 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001291 const APInt &Scale,
1292 ScalarEvolution &SE) {
1293 bool Interesting = false;
1294
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001295 // Iterate over the add operands. They are sorted, with constants first.
1296 unsigned i = 0;
1297 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1298 ++i;
1299 // Pull a buried constant out to the outside.
1300 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1301 Interesting = true;
1302 AccumulatedConstant += Scale * C->getValue()->getValue();
1303 }
1304
1305 // Next comes everything else. We're especially interested in multiplies
1306 // here, but they're in the middle, so just visit the rest with one loop.
1307 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001308 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1309 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1310 APInt NewScale =
1311 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1312 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1313 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001314 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001315 Interesting |=
1316 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001317 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001318 NewScale, SE);
1319 } else {
1320 // A multiplication of a constant with some other value. Update
1321 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001322 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1323 const SCEV *Key = SE.getMulExpr(MulOps);
1324 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001325 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001326 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001327 NewOps.push_back(Pair.first->first);
1328 } else {
1329 Pair.first->second += NewScale;
1330 // The map already had an entry for this value, which may indicate
1331 // a folding opportunity.
1332 Interesting = true;
1333 }
1334 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001335 } else {
1336 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001337 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001338 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001339 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001340 NewOps.push_back(Pair.first->first);
1341 } else {
1342 Pair.first->second += Scale;
1343 // The map already had an entry for this value, which may indicate
1344 // a folding opportunity.
1345 Interesting = true;
1346 }
1347 }
1348 }
1349
1350 return Interesting;
1351}
1352
1353namespace {
1354 struct APIntCompare {
1355 bool operator()(const APInt &LHS, const APInt &RHS) const {
1356 return LHS.ult(RHS);
1357 }
1358 };
1359}
1360
Dan Gohman6c0866c2009-05-24 23:45:28 +00001361/// getAddExpr - Get a canonical add expression, or something simpler if
1362/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001363const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001364 SCEV::NoWrapFlags Flags) {
1365 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1366 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001368 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001369#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001370 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001371 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001372 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001373 "SCEVAddExpr operand types don't match!");
1374#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001375
Andrew Trick3228cc22011-03-14 16:50:06 +00001376 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001377 // And vice-versa.
1378 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1379 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1380 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001381 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001382 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1383 E = Ops.end(); I != E; ++I)
1384 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001385 All = false;
1386 break;
1387 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001388 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001389 }
1390
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001392 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001393
1394 // If there are any constants, fold them together.
1395 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001396 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001397 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001398 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001399 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001400 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001401 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1402 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001403 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001404 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001405 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001406 }
1407
1408 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001409 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 Ops.erase(Ops.begin());
1411 --Idx;
1412 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001413
Dan Gohmanbca091d2010-04-12 23:08:18 +00001414 if (Ops.size() == 1) return Ops[0];
1415 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001416
Dan Gohman68ff7762010-08-27 21:39:59 +00001417 // Okay, check to see if the same value occurs in the operand list more than
1418 // once. If so, merge them together into an multiply expression. Since we
1419 // sorted the list, these values are required to be adjacent.
Chris Lattner53e677a2004-04-02 20:23:17 +00001420 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001421 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001422 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001423 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001424 // Scan ahead to count how many equal operands there are.
1425 unsigned Count = 2;
1426 while (i+Count != e && Ops[i+Count] == Ops[i])
1427 ++Count;
1428 // Merge the values into a multiply.
1429 const SCEV *Scale = getConstant(Ty, Count);
1430 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1431 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001432 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001433 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001434 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001435 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001436 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001438 if (FoundMatch)
Andrew Trick3228cc22011-03-14 16:50:06 +00001439 return getAddExpr(Ops, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001440
Dan Gohman728c7f32009-05-08 21:03:19 +00001441 // Check for truncates. If all the operands are truncated from the same
1442 // type, see if factoring out the truncate would permit the result to be
1443 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1444 // if the contents of the resulting outer trunc fold to something simple.
1445 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1446 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1447 const Type *DstType = Trunc->getType();
1448 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001449 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001450 bool Ok = true;
1451 // Check all the operands to see if they can be represented in the
1452 // source type of the truncate.
1453 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1454 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1455 if (T->getOperand()->getType() != SrcType) {
1456 Ok = false;
1457 break;
1458 }
1459 LargeOps.push_back(T->getOperand());
1460 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001461 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001462 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001463 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001464 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1465 if (const SCEVTruncateExpr *T =
1466 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1467 if (T->getOperand()->getType() != SrcType) {
1468 Ok = false;
1469 break;
1470 }
1471 LargeMulOps.push_back(T->getOperand());
1472 } else if (const SCEVConstant *C =
1473 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001474 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001475 } else {
1476 Ok = false;
1477 break;
1478 }
1479 }
1480 if (Ok)
1481 LargeOps.push_back(getMulExpr(LargeMulOps));
1482 } else {
1483 Ok = false;
1484 break;
1485 }
1486 }
1487 if (Ok) {
1488 // Evaluate the expression in the larger type.
Andrew Trick3228cc22011-03-14 16:50:06 +00001489 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman728c7f32009-05-08 21:03:19 +00001490 // If it folds to something simple, use it. Otherwise, don't.
1491 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1492 return getTruncateExpr(Fold, DstType);
1493 }
1494 }
1495
1496 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001497 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1498 ++Idx;
1499
1500 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001501 if (Idx < Ops.size()) {
1502 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001503 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 // If we have an add, expand the add operands onto the end of the operands
1505 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001506 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001507 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 DeletedAdd = true;
1509 }
1510
1511 // If we deleted at least one add, we added operands to the end of the list,
1512 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001513 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001514 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001515 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001516 }
1517
1518 // Skip over the add expression until we get to a multiply.
1519 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1520 ++Idx;
1521
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001522 // Check to see if there are any folding opportunities present with
1523 // operands multiplied by constant values.
1524 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1525 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001526 DenseMap<const SCEV *, APInt> M;
1527 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001528 APInt AccumulatedConstant(BitWidth, 0);
1529 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001530 Ops.data(), Ops.size(),
1531 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001532 // Some interesting folding opportunity is present, so its worthwhile to
1533 // re-generate the operands list. Group the operands by constant scale,
1534 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001535 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001536 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001537 E = NewOps.end(); I != E; ++I)
1538 MulOpLists[M.find(*I)->second].push_back(*I);
1539 // Re-generate the operands list.
1540 Ops.clear();
1541 if (AccumulatedConstant != 0)
1542 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001543 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1544 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001545 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001546 Ops.push_back(getMulExpr(getConstant(I->first),
1547 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001548 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001549 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001550 if (Ops.size() == 1)
1551 return Ops[0];
1552 return getAddExpr(Ops);
1553 }
1554 }
1555
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 // If we are adding something to a multiply expression, make sure the
1557 // something is not already an operand of the multiply. If so, merge it into
1558 // the multiply.
1559 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001560 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001561 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001562 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001563 if (isa<SCEVConstant>(MulOpSCEV))
1564 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001566 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001568 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001569 if (Mul->getNumOperands() != 2) {
1570 // If the multiply has more than two operands, we must get the
1571 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001572 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1573 Mul->op_begin()+MulOp);
1574 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001575 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001577 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001578 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001579 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 if (Ops.size() == 2) return OuterMul;
1581 if (AddOp < Idx) {
1582 Ops.erase(Ops.begin()+AddOp);
1583 Ops.erase(Ops.begin()+Idx-1);
1584 } else {
1585 Ops.erase(Ops.begin()+Idx);
1586 Ops.erase(Ops.begin()+AddOp-1);
1587 }
1588 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001589 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001591
Chris Lattner53e677a2004-04-02 20:23:17 +00001592 // Check this multiply against other multiplies being added together.
1593 for (unsigned OtherMulIdx = Idx+1;
1594 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1595 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001596 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 // If MulOp occurs in OtherMul, we can fold the two multiplies
1598 // together.
1599 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1600 OMulOp != e; ++OMulOp)
1601 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1602 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001603 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001604 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001605 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001606 Mul->op_begin()+MulOp);
1607 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001608 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001609 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001610 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001611 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001612 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001613 OtherMul->op_begin()+OMulOp);
1614 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001615 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001616 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001617 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1618 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001620 Ops.erase(Ops.begin()+Idx);
1621 Ops.erase(Ops.begin()+OtherMulIdx-1);
1622 Ops.push_back(OuterMul);
1623 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001624 }
1625 }
1626 }
1627 }
1628
1629 // If there are any add recurrences in the operands list, see if any other
1630 // added values are loop invariant. If so, we can fold them into the
1631 // recurrence.
1632 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1633 ++Idx;
1634
1635 // Scan over all recurrences, trying to fold loop invariants into them.
1636 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1637 // Scan all of the other operands to this add and add them to the vector if
1638 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001639 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001640 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001641 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001642 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001643 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001644 LIOps.push_back(Ops[i]);
1645 Ops.erase(Ops.begin()+i);
1646 --i; --e;
1647 }
1648
1649 // If we found some loop invariants, fold them into the recurrence.
1650 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001651 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001652 LIOps.push_back(AddRec->getStart());
1653
Dan Gohman0bba49c2009-07-07 17:06:11 +00001654 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001655 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001656 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001657
Dan Gohmanb9f96512010-06-30 07:16:37 +00001658 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher87376832011-01-11 09:02:09 +00001659 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001660 // Always propagate NW.
1661 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick3228cc22011-03-14 16:50:06 +00001662 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman59de33e2009-12-18 18:45:31 +00001663
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 // If all of the other operands were loop invariant, we are done.
1665 if (Ops.size() == 1) return NewRec;
1666
1667 // Otherwise, add the folded AddRec by the non-liv parts.
1668 for (unsigned i = 0;; ++i)
1669 if (Ops[i] == AddRec) {
1670 Ops[i] = NewRec;
1671 break;
1672 }
Dan Gohman246b2562007-10-22 18:31:58 +00001673 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001674 }
1675
1676 // Okay, if there weren't any loop invariants to be folded, check to see if
1677 // there are multiple AddRec's with the same loop induction variable being
1678 // added together. If so, we can fold them.
1679 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001680 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1681 ++OtherIdx)
1682 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1683 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1684 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1685 AddRec->op_end());
1686 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1687 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001688 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001689 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001690 if (OtherAddRec->getLoop() == AddRecLoop) {
1691 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1692 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001693 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001694 AddRecOps.append(OtherAddRec->op_begin()+i,
1695 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001696 break;
1697 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001698 AddRecOps[i] = getAddExpr(AddRecOps[i],
1699 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001700 }
1701 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001702 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001703 // Step size has changed, so we cannot guarantee no self-wraparound.
1704 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohman32527152010-08-27 20:45:56 +00001705 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001706 }
1707
1708 // Otherwise couldn't fold anything into this recurrence. Move onto the
1709 // next one.
1710 }
1711
1712 // Okay, it looks like we really DO need an add expr. Check to see if we
1713 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001714 FoldingSetNodeID ID;
1715 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001716 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1717 ID.AddPointer(Ops[i]);
1718 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001719 SCEVAddExpr *S =
1720 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1721 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001722 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1723 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001724 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1725 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001726 UniqueSCEVs.InsertNode(S, IP);
1727 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001728 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001729 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001730}
1731
Dan Gohman6c0866c2009-05-24 23:45:28 +00001732/// getMulExpr - Get a canonical multiply expression, or something simpler if
1733/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001734const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001735 SCEV::NoWrapFlags Flags) {
1736 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1737 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001738 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001739 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001740#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001741 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001742 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001743 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001744 "SCEVMulExpr operand types don't match!");
1745#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001746
Andrew Trick3228cc22011-03-14 16:50:06 +00001747 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001748 // And vice-versa.
1749 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1750 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1751 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001752 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001753 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1754 E = Ops.end(); I != E; ++I)
1755 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001756 All = false;
1757 break;
1758 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001759 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001760 }
1761
Chris Lattner53e677a2004-04-02 20:23:17 +00001762 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001763 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001764
1765 // If there are any constants, fold them together.
1766 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001767 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001768
1769 // C1*(C2+V) -> C1*C2 + C1*V
1770 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001771 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001772 if (Add->getNumOperands() == 2 &&
1773 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001774 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1775 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001776
Chris Lattner53e677a2004-04-02 20:23:17 +00001777 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001778 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001779 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001780 ConstantInt *Fold = ConstantInt::get(getContext(),
1781 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001782 RHSC->getValue()->getValue());
1783 Ops[0] = getConstant(Fold);
1784 Ops.erase(Ops.begin()+1); // Erase the folded element
1785 if (Ops.size() == 1) return Ops[0];
1786 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001787 }
1788
1789 // If we are left with a constant one being multiplied, strip it off.
1790 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1791 Ops.erase(Ops.begin());
1792 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001793 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001794 // If we have a multiply of zero, it will always be zero.
1795 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001796 } else if (Ops[0]->isAllOnesValue()) {
1797 // If we have a mul by -1 of an add, try distributing the -1 among the
1798 // add operands.
Andrew Trick3228cc22011-03-14 16:50:06 +00001799 if (Ops.size() == 2) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001800 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1801 SmallVector<const SCEV *, 4> NewOps;
1802 bool AnyFolded = false;
Andrew Trick3228cc22011-03-14 16:50:06 +00001803 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1804 E = Add->op_end(); I != E; ++I) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001805 const SCEV *Mul = getMulExpr(Ops[0], *I);
1806 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1807 NewOps.push_back(Mul);
1808 }
1809 if (AnyFolded)
1810 return getAddExpr(NewOps);
1811 }
Andrew Tricka053b212011-03-14 17:38:54 +00001812 else if (const SCEVAddRecExpr *
1813 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1814 // Negation preserves a recurrence's no self-wrap property.
1815 SmallVector<const SCEV *, 4> Operands;
1816 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1817 E = AddRec->op_end(); I != E; ++I) {
1818 Operands.push_back(getMulExpr(Ops[0], *I));
1819 }
1820 return getAddRecExpr(Operands, AddRec->getLoop(),
1821 AddRec->getNoWrapFlags(SCEV::FlagNW));
1822 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001823 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001824 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001825
1826 if (Ops.size() == 1)
1827 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001828 }
1829
1830 // Skip over the add expression until we get to a multiply.
1831 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1832 ++Idx;
1833
Chris Lattner53e677a2004-04-02 20:23:17 +00001834 // If there are mul operands inline them all into this expression.
1835 if (Idx < Ops.size()) {
1836 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001837 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001838 // If we have an mul, expand the mul operands onto the end of the operands
1839 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001840 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001841 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001842 DeletedMul = true;
1843 }
1844
1845 // If we deleted at least one mul, we added operands to the end of the list,
1846 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001847 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001848 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001849 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001850 }
1851
1852 // If there are any add recurrences in the operands list, see if any other
1853 // added values are loop invariant. If so, we can fold them into the
1854 // recurrence.
1855 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1856 ++Idx;
1857
1858 // Scan over all recurrences, trying to fold loop invariants into them.
1859 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1860 // Scan all of the other operands to this mul and add them to the vector if
1861 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001862 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001863 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001864 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001865 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001866 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001867 LIOps.push_back(Ops[i]);
1868 Ops.erase(Ops.begin()+i);
1869 --i; --e;
1870 }
1871
1872 // If we found some loop invariants, fold them into the recurrence.
1873 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001874 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001875 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001876 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001877 const SCEV *Scale = getMulExpr(LIOps);
1878 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1879 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001880
Dan Gohmanb9f96512010-06-30 07:16:37 +00001881 // Build the new addrec. Propagate the NUW and NSW flags if both the
1882 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001883 //
1884 // No self-wrap cannot be guaranteed after changing the step size, but
1885 // will be infered if either NUW or NSW is true.
1886 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1887 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001888
1889 // If all of the other operands were loop invariant, we are done.
1890 if (Ops.size() == 1) return NewRec;
1891
1892 // Otherwise, multiply the folded AddRec by the non-liv parts.
1893 for (unsigned i = 0;; ++i)
1894 if (Ops[i] == AddRec) {
1895 Ops[i] = NewRec;
1896 break;
1897 }
Dan Gohman246b2562007-10-22 18:31:58 +00001898 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001899 }
1900
1901 // Okay, if there weren't any loop invariants to be folded, check to see if
1902 // there are multiple AddRec's with the same loop induction variable being
1903 // multiplied together. If so, we can fold them.
1904 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001905 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1906 ++OtherIdx)
1907 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1908 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1909 // {A*C,+,F*D + G*B + B*D}<L>
1910 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1911 ++OtherIdx)
1912 if (const SCEVAddRecExpr *OtherAddRec =
1913 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1914 if (OtherAddRec->getLoop() == AddRecLoop) {
1915 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1916 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1917 const SCEV *B = F->getStepRecurrence(*this);
1918 const SCEV *D = G->getStepRecurrence(*this);
1919 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1920 getMulExpr(G, B),
1921 getMulExpr(B, D));
1922 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Andrew Trick3228cc22011-03-14 16:50:06 +00001923 F->getLoop(),
1924 SCEV::FlagAnyWrap);
Dan Gohman6a0c1252010-08-31 22:52:12 +00001925 if (Ops.size() == 2) return NewAddRec;
1926 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1927 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1928 }
1929 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001930 }
1931
1932 // Otherwise couldn't fold anything into this recurrence. Move onto the
1933 // next one.
1934 }
1935
1936 // Okay, it looks like we really DO need an mul expr. Check to see if we
1937 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001938 FoldingSetNodeID ID;
1939 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001940 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1941 ID.AddPointer(Ops[i]);
1942 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001943 SCEVMulExpr *S =
1944 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1945 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001946 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1947 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001948 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1949 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001950 UniqueSCEVs.InsertNode(S, IP);
1951 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001952 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001953 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001954}
1955
Andreas Bolka8a11c982009-08-07 22:55:26 +00001956/// getUDivExpr - Get a canonical unsigned division expression, or something
1957/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001958const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1959 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001960 assert(getEffectiveSCEVType(LHS->getType()) ==
1961 getEffectiveSCEVType(RHS->getType()) &&
1962 "SCEVUDivExpr operand types don't match!");
1963
Dan Gohman622ed672009-05-04 22:02:23 +00001964 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001965 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001966 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001967 // If the denominator is zero, the result of the udiv is undefined. Don't
1968 // try to analyze it, because the resolution chosen here may differ from
1969 // the resolution chosen in other parts of the compiler.
1970 if (!RHSC->getValue()->isZero()) {
1971 // Determine if the division can be folded into the operands of
1972 // its operands.
1973 // TODO: Generalize this to non-constants by using known-bits information.
1974 const Type *Ty = LHS->getType();
1975 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001976 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001977 // For non-power-of-two values, effectively round the value up to the
1978 // nearest power of two.
1979 if (!RHSC->getValue()->getValue().isPowerOf2())
1980 ++MaxShiftAmt;
1981 const IntegerType *ExtTy =
1982 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1983 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1984 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1985 if (const SCEVConstant *Step =
1986 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1987 if (!Step->getValue()->getValue()
1988 .urem(RHSC->getValue()->getValue()) &&
1989 getZeroExtendExpr(AR, ExtTy) ==
1990 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1991 getZeroExtendExpr(Step, ExtTy),
Andrew Trick3228cc22011-03-14 16:50:06 +00001992 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001993 SmallVector<const SCEV *, 4> Operands;
1994 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1995 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick3228cc22011-03-14 16:50:06 +00001996 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001997 SCEV::FlagNW);
Dan Gohman185cf032009-05-08 20:18:49 +00001998 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001999 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2000 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2001 SmallVector<const SCEV *, 4> Operands;
2002 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2003 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2004 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2005 // Find an operand that's safely divisible.
2006 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2007 const SCEV *Op = M->getOperand(i);
2008 const SCEV *Div = getUDivExpr(Op, RHSC);
2009 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2010 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2011 M->op_end());
2012 Operands[i] = Div;
2013 return getMulExpr(Operands);
2014 }
2015 }
Dan Gohman185cf032009-05-08 20:18:49 +00002016 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002017 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2018 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
2019 SmallVector<const SCEV *, 4> Operands;
2020 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2021 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2022 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2023 Operands.clear();
2024 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2025 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2026 if (isa<SCEVUDivExpr>(Op) ||
2027 getMulExpr(Op, RHS) != A->getOperand(i))
2028 break;
2029 Operands.push_back(Op);
2030 }
2031 if (Operands.size() == A->getNumOperands())
2032 return getAddExpr(Operands);
2033 }
2034 }
Dan Gohman185cf032009-05-08 20:18:49 +00002035
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002036 // Fold if both operands are constant.
2037 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2038 Constant *LHSCV = LHSC->getValue();
2039 Constant *RHSCV = RHSC->getValue();
2040 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2041 RHSCV)));
2042 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002043 }
2044 }
2045
Dan Gohman1c343752009-06-27 21:21:31 +00002046 FoldingSetNodeID ID;
2047 ID.AddInteger(scUDivExpr);
2048 ID.AddPointer(LHS);
2049 ID.AddPointer(RHS);
2050 void *IP = 0;
2051 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002052 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2053 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00002054 UniqueSCEVs.InsertNode(S, IP);
2055 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002056}
2057
2058
Dan Gohman6c0866c2009-05-24 23:45:28 +00002059/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2060/// Simplify the expression as much as possible.
Andrew Trick3228cc22011-03-14 16:50:06 +00002061const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2062 const Loop *L,
2063 SCEV::NoWrapFlags Flags) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002064 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002065 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002066 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002067 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002068 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickc343c1e2011-03-15 00:37:00 +00002069 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattner53e677a2004-04-02 20:23:17 +00002070 }
2071
2072 Operands.push_back(Step);
Andrew Trick3228cc22011-03-14 16:50:06 +00002073 return getAddRecExpr(Operands, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002074}
2075
Dan Gohman6c0866c2009-05-24 23:45:28 +00002076/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2077/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002078const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002079ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick3228cc22011-03-14 16:50:06 +00002080 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002081 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002082#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002083 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002084 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002085 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002086 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00002087 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002088 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00002089 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00002090#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002091
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002092 if (Operands.back()->isZero()) {
2093 Operands.pop_back();
Andrew Trick3228cc22011-03-14 16:50:06 +00002094 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002095 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002096
Dan Gohmanbc028532010-02-19 18:49:22 +00002097 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2098 // use that information to infer NUW and NSW flags. However, computing a
2099 // BE count requires calling getAddRecExpr, so we may not yet have a
2100 // meaningful BE count at this point (and if we don't, we'd be stuck
2101 // with a SCEVCouldNotCompute as the cached BE count).
2102
Andrew Trick3228cc22011-03-14 16:50:06 +00002103 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002104 // And vice-versa.
2105 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2106 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2107 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002108 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002109 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2110 E = Operands.end(); I != E; ++I)
2111 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002112 All = false;
2113 break;
2114 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00002115 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00002116 }
2117
Dan Gohmand9cc7492008-08-08 18:33:12 +00002118 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002119 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002120 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002121 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002122 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002123 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002124 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002125 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002126 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002127 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002128 // AddRecs require their operands be loop-invariant with respect to their
2129 // loops. Don't perform this transformation if it would break this
2130 // requirement.
2131 bool AllInvariant = true;
2132 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002133 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002134 AllInvariant = false;
2135 break;
2136 }
2137 if (AllInvariant) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002138 // Create a recurrence for the outer loop with the same step size.
2139 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002140 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2141 // inner recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002142 SCEV::NoWrapFlags OuterFlags =
2143 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick3228cc22011-03-14 16:50:06 +00002144
2145 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohman9a80b452009-06-26 22:36:20 +00002146 AllInvariant = true;
2147 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002148 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002149 AllInvariant = false;
2150 break;
2151 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002152 if (AllInvariant) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002153 // Ok, both add recurrences are valid after the transformation.
Andrew Trick3228cc22011-03-14 16:50:06 +00002154 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002155 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2156 // the outer recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002157 SCEV::NoWrapFlags InnerFlags =
2158 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick3228cc22011-03-14 16:50:06 +00002159 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2160 }
Dan Gohman9a80b452009-06-26 22:36:20 +00002161 }
2162 // Reset Operands to its original state.
2163 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002164 }
2165 }
2166
Dan Gohman67847532010-01-19 22:27:22 +00002167 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2168 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002169 FoldingSetNodeID ID;
2170 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002171 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2172 ID.AddPointer(Operands[i]);
2173 ID.AddPointer(L);
2174 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002175 SCEVAddRecExpr *S =
2176 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2177 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002178 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2179 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002180 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2181 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002182 UniqueSCEVs.InsertNode(S, IP);
2183 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002184 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002185 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002186}
2187
Dan Gohman9311ef62009-06-24 14:49:00 +00002188const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2189 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002190 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002191 Ops.push_back(LHS);
2192 Ops.push_back(RHS);
2193 return getSMaxExpr(Ops);
2194}
2195
Dan Gohman0bba49c2009-07-07 17:06:11 +00002196const SCEV *
2197ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002198 assert(!Ops.empty() && "Cannot get empty smax!");
2199 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002200#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002201 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002202 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002203 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002204 "SCEVSMaxExpr operand types don't match!");
2205#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002206
2207 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002208 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002209
2210 // If there are any constants, fold them together.
2211 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002212 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002213 ++Idx;
2214 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002215 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002216 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002217 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002218 APIntOps::smax(LHSC->getValue()->getValue(),
2219 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002220 Ops[0] = getConstant(Fold);
2221 Ops.erase(Ops.begin()+1); // Erase the folded element
2222 if (Ops.size() == 1) return Ops[0];
2223 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002224 }
2225
Dan Gohmane5aceed2009-06-24 14:46:22 +00002226 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002227 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2228 Ops.erase(Ops.begin());
2229 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002230 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2231 // If we have an smax with a constant maximum-int, it will always be
2232 // maximum-int.
2233 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002234 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002235
Dan Gohman3ab13122010-04-13 16:49:23 +00002236 if (Ops.size() == 1) return Ops[0];
2237 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002238
2239 // Find the first SMax
2240 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2241 ++Idx;
2242
2243 // Check to see if one of the operands is an SMax. If so, expand its operands
2244 // onto our operand list, and recurse to simplify.
2245 if (Idx < Ops.size()) {
2246 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002247 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002248 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002249 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002250 DeletedSMax = true;
2251 }
2252
2253 if (DeletedSMax)
2254 return getSMaxExpr(Ops);
2255 }
2256
2257 // Okay, check to see if the same value occurs in the operand list twice. If
2258 // so, delete one. Since we sorted the list, these values are required to
2259 // be adjacent.
2260 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002261 // X smax Y smax Y --> X smax Y
2262 // X smax Y --> X, if X is always greater than Y
2263 if (Ops[i] == Ops[i+1] ||
2264 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2265 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2266 --i; --e;
2267 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002268 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2269 --i; --e;
2270 }
2271
2272 if (Ops.size() == 1) return Ops[0];
2273
2274 assert(!Ops.empty() && "Reduced smax down to nothing!");
2275
Nick Lewycky3e630762008-02-20 06:48:22 +00002276 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002277 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002278 FoldingSetNodeID ID;
2279 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002280 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2281 ID.AddPointer(Ops[i]);
2282 void *IP = 0;
2283 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002284 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2285 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002286 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2287 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002288 UniqueSCEVs.InsertNode(S, IP);
2289 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002290}
2291
Dan Gohman9311ef62009-06-24 14:49:00 +00002292const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2293 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002294 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002295 Ops.push_back(LHS);
2296 Ops.push_back(RHS);
2297 return getUMaxExpr(Ops);
2298}
2299
Dan Gohman0bba49c2009-07-07 17:06:11 +00002300const SCEV *
2301ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002302 assert(!Ops.empty() && "Cannot get empty umax!");
2303 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002304#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002305 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002306 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002307 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002308 "SCEVUMaxExpr operand types don't match!");
2309#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002310
2311 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002312 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002313
2314 // If there are any constants, fold them together.
2315 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002316 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002317 ++Idx;
2318 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002319 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002320 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002321 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002322 APIntOps::umax(LHSC->getValue()->getValue(),
2323 RHSC->getValue()->getValue()));
2324 Ops[0] = getConstant(Fold);
2325 Ops.erase(Ops.begin()+1); // Erase the folded element
2326 if (Ops.size() == 1) return Ops[0];
2327 LHSC = cast<SCEVConstant>(Ops[0]);
2328 }
2329
Dan Gohmane5aceed2009-06-24 14:46:22 +00002330 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002331 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2332 Ops.erase(Ops.begin());
2333 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002334 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2335 // If we have an umax with a constant maximum-int, it will always be
2336 // maximum-int.
2337 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002338 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002339
Dan Gohman3ab13122010-04-13 16:49:23 +00002340 if (Ops.size() == 1) return Ops[0];
2341 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002342
2343 // Find the first UMax
2344 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2345 ++Idx;
2346
2347 // Check to see if one of the operands is a UMax. If so, expand its operands
2348 // onto our operand list, and recurse to simplify.
2349 if (Idx < Ops.size()) {
2350 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002351 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002352 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002353 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002354 DeletedUMax = true;
2355 }
2356
2357 if (DeletedUMax)
2358 return getUMaxExpr(Ops);
2359 }
2360
2361 // Okay, check to see if the same value occurs in the operand list twice. If
2362 // so, delete one. Since we sorted the list, these values are required to
2363 // be adjacent.
2364 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002365 // X umax Y umax Y --> X umax Y
2366 // X umax Y --> X, if X is always greater than Y
2367 if (Ops[i] == Ops[i+1] ||
2368 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2369 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2370 --i; --e;
2371 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002372 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2373 --i; --e;
2374 }
2375
2376 if (Ops.size() == 1) return Ops[0];
2377
2378 assert(!Ops.empty() && "Reduced umax down to nothing!");
2379
2380 // Okay, it looks like we really DO need a umax expr. Check to see if we
2381 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002382 FoldingSetNodeID ID;
2383 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002384 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2385 ID.AddPointer(Ops[i]);
2386 void *IP = 0;
2387 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002388 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2389 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002390 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2391 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002392 UniqueSCEVs.InsertNode(S, IP);
2393 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002394}
2395
Dan Gohman9311ef62009-06-24 14:49:00 +00002396const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2397 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002398 // ~smax(~x, ~y) == smin(x, y).
2399 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2400}
2401
Dan Gohman9311ef62009-06-24 14:49:00 +00002402const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2403 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002404 // ~umax(~x, ~y) == umin(x, y)
2405 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2406}
2407
Dan Gohman4f8eea82010-02-01 18:27:38 +00002408const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002409 // If we have TargetData, we can bypass creating a target-independent
2410 // constant expression and then folding it back into a ConstantInt.
2411 // This is just a compile-time optimization.
2412 if (TD)
2413 return getConstant(TD->getIntPtrType(getContext()),
2414 TD->getTypeAllocSize(AllocTy));
2415
Dan Gohman4f8eea82010-02-01 18:27:38 +00002416 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002418 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2419 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002420 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2421 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2422}
2423
2424const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2425 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2426 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002427 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2428 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002429 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2430 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2431}
2432
2433const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2434 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002435 // If we have TargetData, we can bypass creating a target-independent
2436 // constant expression and then folding it back into a ConstantInt.
2437 // This is just a compile-time optimization.
2438 if (TD)
2439 return getConstant(TD->getIntPtrType(getContext()),
2440 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2441
Dan Gohman0f5efe52010-01-28 02:15:55 +00002442 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002444 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2445 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002446 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002447 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002448}
2449
Dan Gohman4f8eea82010-02-01 18:27:38 +00002450const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2451 Constant *FieldNo) {
2452 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002454 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2455 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002456 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002457 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002458}
2459
Dan Gohman0bba49c2009-07-07 17:06:11 +00002460const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002461 // Don't attempt to do anything other than create a SCEVUnknown object
2462 // here. createSCEV only calls getUnknown after checking for all other
2463 // interesting possibilities, and any other code that calls getUnknown
2464 // is doing so in order to hide a value from SCEV canonicalization.
2465
Dan Gohman1c343752009-06-27 21:21:31 +00002466 FoldingSetNodeID ID;
2467 ID.AddInteger(scUnknown);
2468 ID.AddPointer(V);
2469 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002470 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2471 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2472 "Stale SCEVUnknown in uniquing map!");
2473 return S;
2474 }
2475 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2476 FirstUnknown);
2477 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002478 UniqueSCEVs.InsertNode(S, IP);
2479 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002480}
2481
Chris Lattner53e677a2004-04-02 20:23:17 +00002482//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002483// Basic SCEV Analysis and PHI Idiom Recognition Code
2484//
2485
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002486/// isSCEVable - Test if values of the given type are analyzable within
2487/// the SCEV framework. This primarily includes integer types, and it
2488/// can optionally include pointer types if the ScalarEvolution class
2489/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002490bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002491 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002492 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002493}
2494
2495/// getTypeSizeInBits - Return the size in bits of the specified type,
2496/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002497uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002498 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2499
2500 // If we have a TargetData, use it!
2501 if (TD)
2502 return TD->getTypeSizeInBits(Ty);
2503
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002504 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002505 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002506 return Ty->getPrimitiveSizeInBits();
2507
2508 // The only other support type is pointer. Without TargetData, conservatively
2509 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002510 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002511 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002512}
2513
2514/// getEffectiveSCEVType - Return a type with the same bitwidth as
2515/// the given type and which represents how SCEV will treat the given
2516/// type, for which isSCEVable must return true. For pointer types,
2517/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002518const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002519 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2520
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002521 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002522 return Ty;
2523
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002524 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002525 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002526 if (TD) return TD->getIntPtrType(getContext());
2527
2528 // Without TargetData, conservatively assume pointers are 64-bit.
2529 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002530}
Chris Lattner53e677a2004-04-02 20:23:17 +00002531
Dan Gohman0bba49c2009-07-07 17:06:11 +00002532const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002533 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002534}
2535
Chris Lattner53e677a2004-04-02 20:23:17 +00002536/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2537/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002538const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002539 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002540
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002541 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2542 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002543 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002544
2545 // The process of creating a SCEV for V may have caused other SCEVs
2546 // to have been created, so it's necessary to insert the new entry
2547 // from scratch, rather than trying to remember the insert position
2548 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002549 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002550 return S;
2551}
2552
Dan Gohman2d1be872009-04-16 03:18:22 +00002553/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2554///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002555const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002556 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002557 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002558 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002559
2560 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002561 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002562 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002563 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002564}
2565
2566/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002567const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002568 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002569 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002570 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002571
2572 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002573 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002574 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002575 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002576 return getMinusSCEV(AllOnes, V);
2577}
2578
Andrew Trick3228cc22011-03-14 16:50:06 +00002579/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2580///
2581/// FIXME: prohibit FlagNUW here, as soon as getMinusSCEVForExitTest goes.
Chris Lattner992efb02011-01-09 22:26:35 +00002582const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00002583 SCEV::NoWrapFlags Flags) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002584 // Fast path: X - X --> 0.
2585 if (LHS == RHS)
2586 return getConstant(LHS->getType(), 0);
2587
Dan Gohman2d1be872009-04-16 03:18:22 +00002588 // X - Y --> X + -Y
Andrew Trick3228cc22011-03-14 16:50:06 +00002589 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman2d1be872009-04-16 03:18:22 +00002590}
2591
2592/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2593/// input value to the specified type. If the type must be extended, it is zero
2594/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002595const SCEV *
Chris Lattner992efb02011-01-09 22:26:35 +00002596ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002597 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002598 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2599 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002600 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002601 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002602 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002603 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002604 return getTruncateExpr(V, Ty);
2605 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002606}
2607
2608/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2609/// input value to the specified type. If the type must be extended, it is sign
2610/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002611const SCEV *
2612ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002613 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002614 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002615 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2616 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002617 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002618 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002619 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002620 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002621 return getTruncateExpr(V, Ty);
2622 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002623}
2624
Dan Gohman467c4302009-05-13 03:46:30 +00002625/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2626/// input value to the specified type. If the type must be extended, it is zero
2627/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002628const SCEV *
2629ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002630 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002631 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2632 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002633 "Cannot noop or zero extend with non-integer arguments!");
2634 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2635 "getNoopOrZeroExtend cannot truncate!");
2636 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2637 return V; // No conversion
2638 return getZeroExtendExpr(V, Ty);
2639}
2640
2641/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2642/// input value to the specified type. If the type must be extended, it is sign
2643/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002644const SCEV *
2645ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002646 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002647 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2648 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002649 "Cannot noop or sign extend with non-integer arguments!");
2650 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2651 "getNoopOrSignExtend cannot truncate!");
2652 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2653 return V; // No conversion
2654 return getSignExtendExpr(V, Ty);
2655}
2656
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002657/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2658/// the input value to the specified type. If the type must be extended,
2659/// it is extended with unspecified bits. The conversion must not be
2660/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002661const SCEV *
2662ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002663 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002664 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2665 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002666 "Cannot noop or any extend with non-integer arguments!");
2667 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2668 "getNoopOrAnyExtend cannot truncate!");
2669 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2670 return V; // No conversion
2671 return getAnyExtendExpr(V, Ty);
2672}
2673
Dan Gohman467c4302009-05-13 03:46:30 +00002674/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2675/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002676const SCEV *
2677ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002678 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002679 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2680 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002681 "Cannot truncate or noop with non-integer arguments!");
2682 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2683 "getTruncateOrNoop cannot extend!");
2684 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2685 return V; // No conversion
2686 return getTruncateExpr(V, Ty);
2687}
2688
Dan Gohmana334aa72009-06-22 00:31:57 +00002689/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2690/// the types using zero-extension, and then perform a umax operation
2691/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002692const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2693 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002694 const SCEV *PromotedLHS = LHS;
2695 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002696
2697 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2698 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2699 else
2700 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2701
2702 return getUMaxExpr(PromotedLHS, PromotedRHS);
2703}
2704
Dan Gohmanc9759e82009-06-22 15:03:27 +00002705/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2706/// the types using zero-extension, and then perform a umin operation
2707/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002708const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2709 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002710 const SCEV *PromotedLHS = LHS;
2711 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002712
2713 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2714 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2715 else
2716 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2717
2718 return getUMinExpr(PromotedLHS, PromotedRHS);
2719}
2720
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002721/// PushDefUseChildren - Push users of the given Instruction
2722/// onto the given Worklist.
2723static void
2724PushDefUseChildren(Instruction *I,
2725 SmallVectorImpl<Instruction *> &Worklist) {
2726 // Push the def-use children onto the Worklist stack.
2727 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2728 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002729 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002730}
2731
2732/// ForgetSymbolicValue - This looks up computed SCEV values for all
2733/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002734/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002735/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002736void
Dan Gohman85669632010-02-25 06:57:05 +00002737ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002738 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002739 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002740
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002741 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002742 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002743 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002744 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002745 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002746
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002747 ValueExprMapType::iterator It =
2748 ValueExprMap.find(static_cast<Value *>(I));
2749 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002750 const SCEV *Old = It->second;
2751
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002752 // Short-circuit the def-use traversal if the symbolic name
2753 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002754 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002755 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002756
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002757 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002758 // structure, it's a PHI that's in the progress of being computed
2759 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2760 // additional loop trip count information isn't going to change anything.
2761 // In the second case, createNodeForPHI will perform the necessary
2762 // updates on its own when it gets to that point. In the third, we do
2763 // want to forget the SCEVUnknown.
2764 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002765 !isa<SCEVUnknown>(Old) ||
2766 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002767 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002768 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002769 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002770 }
2771
2772 PushDefUseChildren(I, Worklist);
2773 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002774}
Chris Lattner53e677a2004-04-02 20:23:17 +00002775
2776/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2777/// a loop header, making it a potential recurrence, or it doesn't.
2778///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002779const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002780 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2781 if (L->getHeader() == PN->getParent()) {
2782 // The loop may have multiple entrances or multiple exits; we can analyze
2783 // this phi as an addrec if it has a unique entry value and a unique
2784 // backedge value.
2785 Value *BEValueV = 0, *StartValueV = 0;
2786 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2787 Value *V = PN->getIncomingValue(i);
2788 if (L->contains(PN->getIncomingBlock(i))) {
2789 if (!BEValueV) {
2790 BEValueV = V;
2791 } else if (BEValueV != V) {
2792 BEValueV = 0;
2793 break;
2794 }
2795 } else if (!StartValueV) {
2796 StartValueV = V;
2797 } else if (StartValueV != V) {
2798 StartValueV = 0;
2799 break;
2800 }
2801 }
2802 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002803 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002804 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002805 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002806 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002807 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002808
2809 // Using this symbolic name for the PHI, analyze the value coming around
2810 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002811 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002812
2813 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2814 // has a special value for the first iteration of the loop.
2815
2816 // If the value coming around the backedge is an add with the symbolic
2817 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002818 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002819 // If there is a single occurrence of the symbolic value, replace it
2820 // with a recurrence.
2821 unsigned FoundIndex = Add->getNumOperands();
2822 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2823 if (Add->getOperand(i) == SymbolicName)
2824 if (FoundIndex == e) {
2825 FoundIndex = i;
2826 break;
2827 }
2828
2829 if (FoundIndex != Add->getNumOperands()) {
2830 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002831 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002832 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2833 if (i != FoundIndex)
2834 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002835 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002836
2837 // This is not a valid addrec if the step amount is varying each
2838 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002839 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002840 (isa<SCEVAddRecExpr>(Accum) &&
2841 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002842 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohmana10756e2010-01-21 02:09:26 +00002843
2844 // If the increment doesn't overflow, then neither the addrec nor
2845 // the post-increment will overflow.
2846 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2847 if (OBO->hasNoUnsignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002848 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002849 if (OBO->hasNoSignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00002850 Flags = setFlags(Flags, SCEV::FlagNSW);
Andrew Trick635f7182011-03-09 17:23:39 +00002851 } else if (const GEPOperator *GEP =
Andrew Trick3228cc22011-03-14 16:50:06 +00002852 dyn_cast<GEPOperator>(BEValueV)) {
2853 // If the increment is an inbounds GEP, then we know the address
2854 // space cannot be wrapped around. We cannot make any guarantee
2855 // about signed or unsigned overflow because pointers are
2856 // unsigned but we may have a negative index from the base
2857 // pointer.
2858 if (GEP->isInBounds())
Andrew Trickc343c1e2011-03-15 00:37:00 +00002859 Flags = setFlags(Flags, SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00002860 }
2861
Dan Gohman27dead42010-04-12 07:49:36 +00002862 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick3228cc22011-03-14 16:50:06 +00002863 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002864
Dan Gohmana10756e2010-01-21 02:09:26 +00002865 // Since the no-wrap flags are on the increment, they apply to the
2866 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002867 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002868 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick3228cc22011-03-14 16:50:06 +00002869 Accum, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002870
2871 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002872 // to be symbolic. We now need to go back and purge all of the
2873 // entries for the scalars that use the symbolic expression.
2874 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002875 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002876 return PHISCEV;
2877 }
2878 }
Dan Gohman622ed672009-05-04 22:02:23 +00002879 } else if (const SCEVAddRecExpr *AddRec =
2880 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002881 // Otherwise, this could be a loop like this:
2882 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2883 // In this case, j = {1,+,1} and BEValue is j.
2884 // Because the other in-value of i (0) fits the evolution of BEValue
2885 // i really is an addrec evolution.
2886 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002887 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002888
2889 // If StartVal = j.start - j.stride, we can use StartVal as the
2890 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002891 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002892 AddRec->getOperand(1))) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002893 // FIXME: For constant StartVal, we should be able to infer
2894 // no-wrap flags.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002895 const SCEV *PHISCEV =
Andrew Trick3228cc22011-03-14 16:50:06 +00002896 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
2897 SCEV::FlagAnyWrap);
Chris Lattner97156e72006-04-26 18:34:07 +00002898
2899 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002900 // to be symbolic. We now need to go back and purge all of the
2901 // entries for the scalars that use the symbolic expression.
2902 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002903 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002904 return PHISCEV;
2905 }
2906 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002907 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002908 }
Dan Gohman27dead42010-04-12 07:49:36 +00002909 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002910
Dan Gohman85669632010-02-25 06:57:05 +00002911 // If the PHI has a single incoming value, follow that value, unless the
2912 // PHI's incoming blocks are in a different loop, in which case doing so
2913 // risks breaking LCSSA form. Instcombine would normally zap these, but
2914 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00002915 if (Value *V = SimplifyInstruction(PN, TD, DT))
2916 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohman85669632010-02-25 06:57:05 +00002917 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002918
Chris Lattner53e677a2004-04-02 20:23:17 +00002919 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002920 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002921}
2922
Dan Gohman26466c02009-05-08 20:26:55 +00002923/// createNodeForGEP - Expand GEP instructions into add and multiply
2924/// operations. This allows them to be analyzed by regular SCEV code.
2925///
Dan Gohmand281ed22009-12-18 02:09:29 +00002926const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002927
Dan Gohmanb9f96512010-06-30 07:16:37 +00002928 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2929 // Add expression, because the Instruction may be guarded by control flow
2930 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002931 // context.
Chris Lattner8ebaf902011-02-13 03:14:49 +00002932 bool isInBounds = GEP->isInBounds();
Dan Gohman7a642572010-06-29 01:41:41 +00002933
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002934 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002935 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002936 // Don't attempt to analyze GEPs over unsized objects.
2937 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2938 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002939 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002940 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002941 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002942 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002943 I != E; ++I) {
2944 Value *Index = *I;
2945 // Compute the (potentially symbolic) offset in bytes for this index.
2946 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2947 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002948 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002949 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2950
Dan Gohmanb9f96512010-06-30 07:16:37 +00002951 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002952 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002953 } else {
2954 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002955 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2956 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002957 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002958 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2959
Dan Gohmanb9f96512010-06-30 07:16:37 +00002960 // Multiply the index by the element size to compute the element offset.
Andrew Trick3228cc22011-03-14 16:50:06 +00002961 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
2962 isInBounds ? SCEV::FlagNSW :
2963 SCEV::FlagAnyWrap);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002964
2965 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002966 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002967 }
2968 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002969
2970 // Get the SCEV for the GEP base.
2971 const SCEV *BaseS = getSCEV(Base);
2972
Dan Gohmanb9f96512010-06-30 07:16:37 +00002973 // Add the total offset from all the GEP indices to the base.
Andrew Trick3228cc22011-03-14 16:50:06 +00002974 return getAddExpr(BaseS, TotalOffset,
2975 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
Dan Gohman26466c02009-05-08 20:26:55 +00002976}
2977
Nick Lewycky83bb0052007-11-22 07:59:40 +00002978/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2979/// guaranteed to end in (at every loop iteration). It is, at the same time,
2980/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2981/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002982uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002983ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002984 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002985 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002986
Dan Gohman622ed672009-05-04 22:02:23 +00002987 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002988 return std::min(GetMinTrailingZeros(T->getOperand()),
2989 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002990
Dan Gohman622ed672009-05-04 22:02:23 +00002991 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002992 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2993 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2994 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002995 }
2996
Dan Gohman622ed672009-05-04 22:02:23 +00002997 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002998 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2999 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3000 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00003001 }
3002
Dan Gohman622ed672009-05-04 22:02:23 +00003003 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003004 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003005 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003006 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003007 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003008 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003009 }
3010
Dan Gohman622ed672009-05-04 22:02:23 +00003011 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003012 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003013 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3014 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00003015 for (unsigned i = 1, e = M->getNumOperands();
3016 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003017 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00003018 BitWidth);
3019 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003020 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003021
Dan Gohman622ed672009-05-04 22:02:23 +00003022 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003023 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003024 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003025 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003026 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003027 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003028 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003029
Dan Gohman622ed672009-05-04 22:02:23 +00003030 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003031 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003032 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003033 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003034 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003035 return MinOpRes;
3036 }
3037
Dan Gohman622ed672009-05-04 22:02:23 +00003038 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00003039 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003040 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00003041 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003042 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00003043 return MinOpRes;
3044 }
3045
Dan Gohman2c364ad2009-06-19 23:29:04 +00003046 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3047 // For a SCEVUnknown, ask ValueTracking.
3048 unsigned BitWidth = getTypeSizeInBits(U->getType());
3049 APInt Mask = APInt::getAllOnesValue(BitWidth);
3050 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3051 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3052 return Zeros.countTrailingOnes();
3053 }
3054
3055 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00003056 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00003057}
Chris Lattner53e677a2004-04-02 20:23:17 +00003058
Dan Gohman85b05a22009-07-13 21:35:55 +00003059/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3060///
3061ConstantRange
3062ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003063 // See if we've computed this range already.
3064 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3065 if (I != UnsignedRanges.end())
3066 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003067
3068 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003069 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003070
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003071 unsigned BitWidth = getTypeSizeInBits(S->getType());
3072 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3073
3074 // If the value has known zeros, the maximum unsigned value will have those
3075 // known zeros as well.
3076 uint32_t TZ = GetMinTrailingZeros(S);
3077 if (TZ != 0)
3078 ConservativeResult =
3079 ConstantRange(APInt::getMinValue(BitWidth),
3080 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3081
Dan Gohman85b05a22009-07-13 21:35:55 +00003082 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3083 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3084 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3085 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003086 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003087 }
3088
3089 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3090 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3091 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3092 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003093 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003094 }
3095
3096 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3097 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3098 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3099 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003100 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003101 }
3102
3103 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3104 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3105 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3106 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003107 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003108 }
3109
3110 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3111 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3112 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003113 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003114 }
3115
3116 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3117 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003118 return setUnsignedRange(ZExt,
3119 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003120 }
3121
3122 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3123 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003124 return setUnsignedRange(SExt,
3125 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003126 }
3127
3128 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3129 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003130 return setUnsignedRange(Trunc,
3131 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003132 }
3133
Dan Gohman85b05a22009-07-13 21:35:55 +00003134 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003135 // If there's no unsigned wrap, the value will never be less than its
3136 // initial value.
Andrew Trick3228cc22011-03-14 16:50:06 +00003137 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmana10756e2010-01-21 02:09:26 +00003138 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003139 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003140 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003141 ConservativeResult.intersectWith(
3142 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003143
3144 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003145 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003146 const Type *Ty = AddRec->getType();
3147 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003148 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3149 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003150 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3151
3152 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003153 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003154
3155 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003156 ConstantRange StepRange = getSignedRange(Step);
3157 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3158 ConstantRange EndRange =
3159 StartRange.add(MaxBECountRange.multiply(StepRange));
3160
3161 // Check for overflow. This must be done with ConstantRange arithmetic
3162 // because we could be called from within the ScalarEvolution overflow
3163 // checking code.
3164 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3165 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3166 ConstantRange ExtMaxBECountRange =
3167 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3168 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3169 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3170 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003171 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003172
Dan Gohman85b05a22009-07-13 21:35:55 +00003173 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3174 EndRange.getUnsignedMin());
3175 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3176 EndRange.getUnsignedMax());
3177 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003178 return setUnsignedRange(AddRec, ConservativeResult);
3179 return setUnsignedRange(AddRec,
3180 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003181 }
3182 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003183
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003184 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003185 }
3186
3187 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3188 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003189 APInt Mask = APInt::getAllOnesValue(BitWidth);
3190 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3191 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003192 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003193 return setUnsignedRange(U, ConservativeResult);
3194 return setUnsignedRange(U,
3195 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003196 }
3197
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003198 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003199}
3200
Dan Gohman85b05a22009-07-13 21:35:55 +00003201/// getSignedRange - Determine the signed range for a particular SCEV.
3202///
3203ConstantRange
3204ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohmana3bbf242011-01-24 17:54:18 +00003205 // See if we've computed this range already.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003206 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3207 if (I != SignedRanges.end())
3208 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003209
Dan Gohman85b05a22009-07-13 21:35:55 +00003210 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003211 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003212
Dan Gohman52fddd32010-01-26 04:40:18 +00003213 unsigned BitWidth = getTypeSizeInBits(S->getType());
3214 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3215
3216 // If the value has known zeros, the maximum signed value will have those
3217 // known zeros as well.
3218 uint32_t TZ = GetMinTrailingZeros(S);
3219 if (TZ != 0)
3220 ConservativeResult =
3221 ConstantRange(APInt::getSignedMinValue(BitWidth),
3222 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3223
Dan Gohman85b05a22009-07-13 21:35:55 +00003224 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3225 ConstantRange X = getSignedRange(Add->getOperand(0));
3226 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3227 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003228 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003229 }
3230
Dan Gohman85b05a22009-07-13 21:35:55 +00003231 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3232 ConstantRange X = getSignedRange(Mul->getOperand(0));
3233 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3234 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003235 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003236 }
3237
Dan Gohman85b05a22009-07-13 21:35:55 +00003238 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3239 ConstantRange X = getSignedRange(SMax->getOperand(0));
3240 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3241 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003242 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003243 }
Dan Gohman62849c02009-06-24 01:05:09 +00003244
Dan Gohman85b05a22009-07-13 21:35:55 +00003245 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3246 ConstantRange X = getSignedRange(UMax->getOperand(0));
3247 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3248 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003249 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003250 }
Dan Gohman62849c02009-06-24 01:05:09 +00003251
Dan Gohman85b05a22009-07-13 21:35:55 +00003252 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3253 ConstantRange X = getSignedRange(UDiv->getLHS());
3254 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003255 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003256 }
Dan Gohman62849c02009-06-24 01:05:09 +00003257
Dan Gohman85b05a22009-07-13 21:35:55 +00003258 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3259 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003260 return setSignedRange(ZExt,
3261 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003262 }
3263
3264 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3265 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003266 return setSignedRange(SExt,
3267 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003268 }
3269
3270 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3271 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003272 return setSignedRange(Trunc,
3273 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003274 }
3275
Dan Gohman85b05a22009-07-13 21:35:55 +00003276 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003277 // If there's no signed wrap, and all the operands have the same sign or
3278 // zero, the value won't ever change sign.
Andrew Trick3228cc22011-03-14 16:50:06 +00003279 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003280 bool AllNonNeg = true;
3281 bool AllNonPos = true;
3282 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3283 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3284 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3285 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003286 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003287 ConservativeResult = ConservativeResult.intersectWith(
3288 ConstantRange(APInt(BitWidth, 0),
3289 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003290 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003291 ConservativeResult = ConservativeResult.intersectWith(
3292 ConstantRange(APInt::getSignedMinValue(BitWidth),
3293 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003294 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003295
3296 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003297 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003298 const Type *Ty = AddRec->getType();
3299 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003300 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3301 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003302 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3303
3304 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003305 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003306
3307 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003308 ConstantRange StepRange = getSignedRange(Step);
3309 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3310 ConstantRange EndRange =
3311 StartRange.add(MaxBECountRange.multiply(StepRange));
3312
3313 // Check for overflow. This must be done with ConstantRange arithmetic
3314 // because we could be called from within the ScalarEvolution overflow
3315 // checking code.
3316 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3317 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3318 ConstantRange ExtMaxBECountRange =
3319 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3320 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3321 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3322 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003323 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003324
Dan Gohman85b05a22009-07-13 21:35:55 +00003325 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3326 EndRange.getSignedMin());
3327 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3328 EndRange.getSignedMax());
3329 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003330 return setSignedRange(AddRec, ConservativeResult);
3331 return setSignedRange(AddRec,
3332 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003333 }
Dan Gohman62849c02009-06-24 01:05:09 +00003334 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003335
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003336 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003337 }
3338
Dan Gohman2c364ad2009-06-19 23:29:04 +00003339 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3340 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003341 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003342 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003343 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3344 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003345 return setSignedRange(U, ConservativeResult);
3346 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003347 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003348 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003349 }
3350
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003351 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003352}
3353
Chris Lattner53e677a2004-04-02 20:23:17 +00003354/// createSCEV - We know that there is no SCEV for the specified value.
3355/// Analyze the expression.
3356///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003357const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003358 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003359 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003360
Dan Gohman6c459a22008-06-22 19:56:46 +00003361 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003362 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003363 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003364
3365 // Don't attempt to analyze instructions in blocks that aren't
3366 // reachable. Such instructions don't matter, and they aren't required
3367 // to obey basic rules for definitions dominating uses which this
3368 // analysis depends on.
3369 if (!DT->isReachableFromEntry(I->getParent()))
3370 return getUnknown(V);
3371 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003372 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003373 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3374 return getConstant(CI);
3375 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003376 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003377 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3378 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003379 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003380 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003381
Dan Gohmanca178902009-07-17 20:47:02 +00003382 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003383 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003384 case Instruction::Add: {
3385 // The simple thing to do would be to just call getSCEV on both operands
3386 // and call getAddExpr with the result. However if we're looking at a
3387 // bunch of things all added together, this can be quite inefficient,
3388 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3389 // Instead, gather up all the operands and make a single getAddExpr call.
3390 // LLVM IR canonical form means we need only traverse the left operands.
3391 SmallVector<const SCEV *, 4> AddOps;
3392 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003393 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3394 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3395 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3396 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003397 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003398 const SCEV *Op1 = getSCEV(U->getOperand(1));
3399 if (Opcode == Instruction::Sub)
3400 AddOps.push_back(getNegativeSCEV(Op1));
3401 else
3402 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003403 }
3404 AddOps.push_back(getSCEV(U->getOperand(0)));
3405 return getAddExpr(AddOps);
3406 }
3407 case Instruction::Mul: {
3408 // See the Add code above.
3409 SmallVector<const SCEV *, 4> MulOps;
3410 MulOps.push_back(getSCEV(U->getOperand(1)));
3411 for (Value *Op = U->getOperand(0);
Andrew Trick635f7182011-03-09 17:23:39 +00003412 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003413 Op = U->getOperand(0)) {
3414 U = cast<Operator>(Op);
3415 MulOps.push_back(getSCEV(U->getOperand(1)));
3416 }
3417 MulOps.push_back(getSCEV(U->getOperand(0)));
3418 return getMulExpr(MulOps);
3419 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003420 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003421 return getUDivExpr(getSCEV(U->getOperand(0)),
3422 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003423 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003424 return getMinusSCEV(getSCEV(U->getOperand(0)),
3425 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003426 case Instruction::And:
3427 // For an expression like x&255 that merely masks off the high bits,
3428 // use zext(trunc(x)) as the SCEV expression.
3429 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003430 if (CI->isNullValue())
3431 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003432 if (CI->isAllOnesValue())
3433 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003434 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003435
3436 // Instcombine's ShrinkDemandedConstant may strip bits out of
3437 // constants, obscuring what would otherwise be a low-bits mask.
3438 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3439 // knew about to reconstruct a low-bits mask value.
3440 unsigned LZ = A.countLeadingZeros();
3441 unsigned BitWidth = A.getBitWidth();
3442 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3443 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3444 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3445
3446 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3447
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003448 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003449 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003450 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003451 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003452 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003453 }
3454 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003455
Dan Gohman6c459a22008-06-22 19:56:46 +00003456 case Instruction::Or:
3457 // If the RHS of the Or is a constant, we may have something like:
3458 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3459 // optimizations will transparently handle this case.
3460 //
3461 // In order for this transformation to be safe, the LHS must be of the
3462 // form X*(2^n) and the Or constant must be less than 2^n.
3463 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003464 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003465 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003466 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003467 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3468 // Build a plain add SCEV.
3469 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3470 // If the LHS of the add was an addrec and it has no-wrap flags,
3471 // transfer the no-wrap flags, since an or won't introduce a wrap.
3472 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3473 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick3228cc22011-03-14 16:50:06 +00003474 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3475 OldAR->getNoWrapFlags());
Dan Gohman1f96e672009-09-17 18:05:20 +00003476 }
3477 return S;
3478 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003479 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003480 break;
3481 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003482 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003483 // If the RHS of the xor is a signbit, then this is just an add.
3484 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003485 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003486 return getAddExpr(getSCEV(U->getOperand(0)),
3487 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003488
3489 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003490 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003491 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003492
3493 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3494 // This is a variant of the check for xor with -1, and it handles
3495 // the case where instcombine has trimmed non-demanded bits out
3496 // of an xor with -1.
3497 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3498 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3499 if (BO->getOpcode() == Instruction::And &&
3500 LCI->getValue() == CI->getValue())
3501 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003502 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003503 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003504 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003505 const Type *Z0Ty = Z0->getType();
3506 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3507
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003508 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003509 // mask off the high bits. Complement the operand and
3510 // re-apply the zext.
3511 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3512 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3513
3514 // If C is a single bit, it may be in the sign-bit position
3515 // before the zero-extend. In this case, represent the xor
3516 // using an add, which is equivalent, and re-apply the zext.
Jay Foad40f8f622010-12-07 08:25:19 +00003517 APInt Trunc = CI->getValue().trunc(Z0TySize);
3518 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohman82052832009-06-18 00:00:20 +00003519 Trunc.isSignBit())
3520 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3521 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003522 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003523 }
3524 break;
3525
3526 case Instruction::Shl:
3527 // Turn shift left of a constant amount into a multiply.
3528 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003529 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003530
3531 // If the shift count is not less than the bitwidth, the result of
3532 // the shift is undefined. Don't try to analyze it, because the
3533 // resolution chosen here may differ from the resolution chosen in
3534 // other parts of the compiler.
3535 if (SA->getValue().uge(BitWidth))
3536 break;
3537
Owen Andersoneed707b2009-07-24 23:12:02 +00003538 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003539 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003540 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003541 }
3542 break;
3543
Nick Lewycky01eaf802008-07-07 06:15:49 +00003544 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003545 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003546 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003547 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003548
3549 // If the shift count is not less than the bitwidth, the result of
3550 // the shift is undefined. Don't try to analyze it, because the
3551 // resolution chosen here may differ from the resolution chosen in
3552 // other parts of the compiler.
3553 if (SA->getValue().uge(BitWidth))
3554 break;
3555
Owen Andersoneed707b2009-07-24 23:12:02 +00003556 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003557 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003558 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003559 }
3560 break;
3561
Dan Gohman4ee29af2009-04-21 02:26:00 +00003562 case Instruction::AShr:
3563 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3564 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003565 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003566 if (L->getOpcode() == Instruction::Shl &&
3567 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003568 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3569
3570 // If the shift count is not less than the bitwidth, the result of
3571 // the shift is undefined. Don't try to analyze it, because the
3572 // resolution chosen here may differ from the resolution chosen in
3573 // other parts of the compiler.
3574 if (CI->getValue().uge(BitWidth))
3575 break;
3576
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003577 uint64_t Amt = BitWidth - CI->getZExtValue();
3578 if (Amt == BitWidth)
3579 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003580 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003581 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003582 IntegerType::get(getContext(),
3583 Amt)),
3584 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003585 }
3586 break;
3587
Dan Gohman6c459a22008-06-22 19:56:46 +00003588 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003589 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003590
3591 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003592 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003593
3594 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003595 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003596
3597 case Instruction::BitCast:
3598 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003599 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003600 return getSCEV(U->getOperand(0));
3601 break;
3602
Dan Gohman4f8eea82010-02-01 18:27:38 +00003603 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3604 // lead to pointer expressions which cannot safely be expanded to GEPs,
3605 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3606 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003607
Dan Gohman26466c02009-05-08 20:26:55 +00003608 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003609 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003610
Dan Gohman6c459a22008-06-22 19:56:46 +00003611 case Instruction::PHI:
3612 return createNodeForPHI(cast<PHINode>(U));
3613
3614 case Instruction::Select:
3615 // This could be a smax or umax that was lowered earlier.
3616 // Try to recover it.
3617 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3618 Value *LHS = ICI->getOperand(0);
3619 Value *RHS = ICI->getOperand(1);
3620 switch (ICI->getPredicate()) {
3621 case ICmpInst::ICMP_SLT:
3622 case ICmpInst::ICMP_SLE:
3623 std::swap(LHS, RHS);
3624 // fall through
3625 case ICmpInst::ICMP_SGT:
3626 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003627 // a >s b ? a+x : b+x -> smax(a, b)+x
3628 // a >s b ? b+x : a+x -> smin(a, b)+x
3629 if (LHS->getType() == U->getType()) {
3630 const SCEV *LS = getSCEV(LHS);
3631 const SCEV *RS = getSCEV(RHS);
3632 const SCEV *LA = getSCEV(U->getOperand(1));
3633 const SCEV *RA = getSCEV(U->getOperand(2));
3634 const SCEV *LDiff = getMinusSCEV(LA, LS);
3635 const SCEV *RDiff = getMinusSCEV(RA, RS);
3636 if (LDiff == RDiff)
3637 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3638 LDiff = getMinusSCEV(LA, RS);
3639 RDiff = getMinusSCEV(RA, LS);
3640 if (LDiff == RDiff)
3641 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3642 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003643 break;
3644 case ICmpInst::ICMP_ULT:
3645 case ICmpInst::ICMP_ULE:
3646 std::swap(LHS, RHS);
3647 // fall through
3648 case ICmpInst::ICMP_UGT:
3649 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003650 // a >u b ? a+x : b+x -> umax(a, b)+x
3651 // a >u b ? b+x : a+x -> umin(a, b)+x
3652 if (LHS->getType() == U->getType()) {
3653 const SCEV *LS = getSCEV(LHS);
3654 const SCEV *RS = getSCEV(RHS);
3655 const SCEV *LA = getSCEV(U->getOperand(1));
3656 const SCEV *RA = getSCEV(U->getOperand(2));
3657 const SCEV *LDiff = getMinusSCEV(LA, LS);
3658 const SCEV *RDiff = getMinusSCEV(RA, RS);
3659 if (LDiff == RDiff)
3660 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3661 LDiff = getMinusSCEV(LA, RS);
3662 RDiff = getMinusSCEV(RA, LS);
3663 if (LDiff == RDiff)
3664 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3665 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003666 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003667 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003668 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3669 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003670 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003671 cast<ConstantInt>(RHS)->isZero()) {
3672 const SCEV *One = getConstant(LHS->getType(), 1);
3673 const SCEV *LS = getSCEV(LHS);
3674 const SCEV *LA = getSCEV(U->getOperand(1));
3675 const SCEV *RA = getSCEV(U->getOperand(2));
3676 const SCEV *LDiff = getMinusSCEV(LA, LS);
3677 const SCEV *RDiff = getMinusSCEV(RA, One);
3678 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003679 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003680 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003681 break;
3682 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003683 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3684 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003685 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003686 cast<ConstantInt>(RHS)->isZero()) {
3687 const SCEV *One = getConstant(LHS->getType(), 1);
3688 const SCEV *LS = getSCEV(LHS);
3689 const SCEV *LA = getSCEV(U->getOperand(1));
3690 const SCEV *RA = getSCEV(U->getOperand(2));
3691 const SCEV *LDiff = getMinusSCEV(LA, One);
3692 const SCEV *RDiff = getMinusSCEV(RA, LS);
3693 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003694 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003695 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003696 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003697 default:
3698 break;
3699 }
3700 }
3701
3702 default: // We cannot analyze this expression.
3703 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003704 }
3705
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003706 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003707}
3708
3709
3710
3711//===----------------------------------------------------------------------===//
3712// Iteration Count Computation Code
3713//
3714
Dan Gohman46bdfb02009-02-24 18:55:53 +00003715/// getBackedgeTakenCount - If the specified loop has a predictable
3716/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3717/// object. The backedge-taken count is the number of times the loop header
3718/// will be branched to from within the loop. This is one less than the
3719/// trip count of the loop, since it doesn't count the first iteration,
3720/// when the header is branched to from outside the loop.
3721///
3722/// Note that it is not valid to call this method on a loop without a
3723/// loop-invariant backedge-taken count (see
3724/// hasLoopInvariantBackedgeTakenCount).
3725///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003726const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003727 return getBackedgeTakenInfo(L).Exact;
3728}
3729
3730/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3731/// return the least SCEV value that is known never to be less than the
3732/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003733const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003734 return getBackedgeTakenInfo(L).Max;
3735}
3736
Dan Gohman59ae6b92009-07-08 19:23:34 +00003737/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3738/// onto the given Worklist.
3739static void
3740PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3741 BasicBlock *Header = L->getHeader();
3742
3743 // Push all Loop-header PHIs onto the Worklist stack.
3744 for (BasicBlock::iterator I = Header->begin();
3745 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3746 Worklist.push_back(PN);
3747}
3748
Dan Gohmana1af7572009-04-30 20:47:05 +00003749const ScalarEvolution::BackedgeTakenInfo &
3750ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003751 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003752 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003753 // update the value. The temporary CouldNotCompute value tells SCEV
3754 // code elsewhere that it shouldn't attempt to request a new
3755 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003756 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003757 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
Chris Lattnerf1859892011-01-09 02:16:18 +00003758 if (!Pair.second)
3759 return Pair.first->second;
Dan Gohman01ecca22009-04-27 20:16:15 +00003760
Chris Lattnerf1859892011-01-09 02:16:18 +00003761 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3762 if (BECount.Exact != getCouldNotCompute()) {
3763 assert(isLoopInvariant(BECount.Exact, L) &&
3764 isLoopInvariant(BECount.Max, L) &&
3765 "Computed backedge-taken count isn't loop invariant for loop!");
3766 ++NumTripCountsComputed;
3767
3768 // Update the value in the map.
3769 Pair.first->second = BECount;
3770 } else {
3771 if (BECount.Max != getCouldNotCompute())
Dan Gohman01ecca22009-04-27 20:16:15 +00003772 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003773 Pair.first->second = BECount;
Chris Lattnerf1859892011-01-09 02:16:18 +00003774 if (isa<PHINode>(L->getHeader()->begin()))
3775 // Only count loops that have phi nodes as not being computable.
3776 ++NumTripCountsNotComputed;
3777 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003778
Chris Lattnerf1859892011-01-09 02:16:18 +00003779 // Now that we know more about the trip count for this loop, forget any
3780 // existing SCEV values for PHI nodes in this loop since they are only
3781 // conservative estimates made without the benefit of trip count
3782 // information. This is similar to the code in forgetLoop, except that
3783 // it handles SCEVUnknown PHI nodes specially.
3784 if (BECount.hasAnyInfo()) {
3785 SmallVector<Instruction *, 16> Worklist;
3786 PushLoopPHIs(L, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003787
Chris Lattnerf1859892011-01-09 02:16:18 +00003788 SmallPtrSet<Instruction *, 8> Visited;
3789 while (!Worklist.empty()) {
3790 Instruction *I = Worklist.pop_back_val();
3791 if (!Visited.insert(I)) continue;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003792
Chris Lattnerf1859892011-01-09 02:16:18 +00003793 ValueExprMapType::iterator It =
3794 ValueExprMap.find(static_cast<Value *>(I));
3795 if (It != ValueExprMap.end()) {
3796 const SCEV *Old = It->second;
Dan Gohman6678e7b2010-11-17 02:44:44 +00003797
Chris Lattnerf1859892011-01-09 02:16:18 +00003798 // SCEVUnknown for a PHI either means that it has an unrecognized
3799 // structure, or it's a PHI that's in the progress of being computed
3800 // by createNodeForPHI. In the former case, additional loop trip
3801 // count information isn't going to change anything. In the later
3802 // case, createNodeForPHI will perform the necessary updates on its
3803 // own when it gets to that point.
3804 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3805 forgetMemoizedResults(Old);
3806 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003807 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003808 if (PHINode *PN = dyn_cast<PHINode>(I))
3809 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003810 }
Chris Lattnerf1859892011-01-09 02:16:18 +00003811
3812 PushDefUseChildren(I, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003813 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003814 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003815 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003816}
3817
Dan Gohman4c7279a2009-10-31 15:04:55 +00003818/// forgetLoop - This method should be called by the client when it has
3819/// changed a loop in a way that may effect ScalarEvolution's ability to
3820/// compute a trip count, or if the loop is deleted.
3821void ScalarEvolution::forgetLoop(const Loop *L) {
3822 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003823 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003824
Dan Gohman4c7279a2009-10-31 15:04:55 +00003825 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003826 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003827 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003828
Dan Gohman59ae6b92009-07-08 19:23:34 +00003829 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003830 while (!Worklist.empty()) {
3831 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003832 if (!Visited.insert(I)) continue;
3833
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003834 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3835 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003836 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003837 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003838 if (PHINode *PN = dyn_cast<PHINode>(I))
3839 ConstantEvolutionLoopExitValue.erase(PN);
3840 }
3841
3842 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003843 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003844
3845 // Forget all contained loops too, to avoid dangling entries in the
3846 // ValuesAtScopes map.
3847 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3848 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003849}
3850
Eric Christophere6cbfa62010-07-29 01:25:38 +00003851/// forgetValue - This method should be called by the client when it has
3852/// changed a value in a way that may effect its value, or which may
3853/// disconnect it from a def-use chain linking it to a loop.
3854void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003855 Instruction *I = dyn_cast<Instruction>(V);
3856 if (!I) return;
3857
3858 // Drop information about expressions based on loop-header PHIs.
3859 SmallVector<Instruction *, 16> Worklist;
3860 Worklist.push_back(I);
3861
3862 SmallPtrSet<Instruction *, 8> Visited;
3863 while (!Worklist.empty()) {
3864 I = Worklist.pop_back_val();
3865 if (!Visited.insert(I)) continue;
3866
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003867 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3868 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00003869 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003870 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003871 if (PHINode *PN = dyn_cast<PHINode>(I))
3872 ConstantEvolutionLoopExitValue.erase(PN);
3873 }
3874
3875 PushDefUseChildren(I, Worklist);
3876 }
3877}
3878
Dan Gohman46bdfb02009-02-24 18:55:53 +00003879/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3880/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003881ScalarEvolution::BackedgeTakenInfo
3882ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003883 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003884 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003885
Dan Gohmana334aa72009-06-22 00:31:57 +00003886 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003887 const SCEV *BECount = getCouldNotCompute();
3888 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003889 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003890 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3891 BackedgeTakenInfo NewBTI =
3892 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003893
Dan Gohman1c343752009-06-27 21:21:31 +00003894 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003895 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003896 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003897 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003898 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003899 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003900 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003901 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003902 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003903 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003904 }
Dan Gohman1c343752009-06-27 21:21:31 +00003905 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003906 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003907 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003908 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003909 }
3910
3911 return BackedgeTakenInfo(BECount, MaxBECount);
3912}
3913
3914/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3915/// of the specified loop will execute if it exits via the specified block.
3916ScalarEvolution::BackedgeTakenInfo
3917ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3918 BasicBlock *ExitingBlock) {
3919
3920 // Okay, we've chosen an exiting block. See what condition causes us to
3921 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003922 //
3923 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003924 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003925 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003926 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003927
Chris Lattner8b0e3602007-01-07 02:24:26 +00003928 // At this point, we know we have a conditional branch that determines whether
3929 // the loop is exited. However, we don't know if the branch is executed each
3930 // time through the loop. If not, then the execution count of the branch will
3931 // not be equal to the trip count of the loop.
3932 //
3933 // Currently we check for this by checking to see if the Exit branch goes to
3934 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003935 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003936 // loop header. This is common for un-rotated loops.
3937 //
3938 // If both of those tests fail, walk up the unique predecessor chain to the
3939 // header, stopping if there is an edge that doesn't exit the loop. If the
3940 // header is reached, the execution count of the branch will be equal to the
3941 // trip count of the loop.
3942 //
3943 // More extensive analysis could be done to handle more cases here.
3944 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003945 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003946 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003947 ExitBr->getParent() != L->getHeader()) {
3948 // The simple checks failed, try climbing the unique predecessor chain
3949 // up to the header.
3950 bool Ok = false;
3951 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3952 BasicBlock *Pred = BB->getUniquePredecessor();
3953 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003954 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003955 TerminatorInst *PredTerm = Pred->getTerminator();
3956 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3957 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3958 if (PredSucc == BB)
3959 continue;
3960 // If the predecessor has a successor that isn't BB and isn't
3961 // outside the loop, assume the worst.
3962 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003963 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003964 }
3965 if (Pred == L->getHeader()) {
3966 Ok = true;
3967 break;
3968 }
3969 BB = Pred;
3970 }
3971 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003972 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003973 }
3974
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003975 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003976 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3977 ExitBr->getSuccessor(0),
3978 ExitBr->getSuccessor(1));
3979}
3980
3981/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3982/// backedge of the specified loop will execute if its exit condition
3983/// were a conditional branch of ExitCond, TBB, and FBB.
3984ScalarEvolution::BackedgeTakenInfo
3985ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3986 Value *ExitCond,
3987 BasicBlock *TBB,
3988 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003989 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3991 if (BO->getOpcode() == Instruction::And) {
3992 // Recurse on the operands of the and.
3993 BackedgeTakenInfo BTI0 =
3994 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3995 BackedgeTakenInfo BTI1 =
3996 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003997 const SCEV *BECount = getCouldNotCompute();
3998 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003999 if (L->contains(TBB)) {
4000 // Both conditions must be true for the loop to continue executing.
4001 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00004002 if (BTI0.Exact == getCouldNotCompute() ||
4003 BTI1.Exact == getCouldNotCompute())
4004 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004005 else
4006 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00004007 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004008 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00004009 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004010 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004011 else
4012 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004013 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004014 // Both conditions must be true at the same time for the loop to exit.
4015 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004016 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00004017 if (BTI0.Max == BTI1.Max)
4018 MaxBECount = BTI0.Max;
4019 if (BTI0.Exact == BTI1.Exact)
4020 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004021 }
4022
4023 return BackedgeTakenInfo(BECount, MaxBECount);
4024 }
4025 if (BO->getOpcode() == Instruction::Or) {
4026 // Recurse on the operands of the or.
4027 BackedgeTakenInfo BTI0 =
4028 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
4029 BackedgeTakenInfo BTI1 =
4030 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004031 const SCEV *BECount = getCouldNotCompute();
4032 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004033 if (L->contains(FBB)) {
4034 // Both conditions must be false for the loop to continue executing.
4035 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00004036 if (BTI0.Exact == getCouldNotCompute() ||
4037 BTI1.Exact == getCouldNotCompute())
4038 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004039 else
4040 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00004041 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004042 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00004043 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004044 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004045 else
4046 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004047 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004048 // Both conditions must be false at the same time for the loop to exit.
4049 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004050 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00004051 if (BTI0.Max == BTI1.Max)
4052 MaxBECount = BTI0.Max;
4053 if (BTI0.Exact == BTI1.Exact)
4054 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004055 }
4056
4057 return BackedgeTakenInfo(BECount, MaxBECount);
4058 }
4059 }
4060
4061 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004062 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00004063 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4064 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004065
Dan Gohman00cb5b72010-02-19 18:12:07 +00004066 // Check for a constant condition. These are normally stripped out by
4067 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4068 // preserve the CFG and is temporarily leaving constant conditions
4069 // in place.
4070 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4071 if (L->contains(FBB) == !CI->getZExtValue())
4072 // The backedge is always taken.
4073 return getCouldNotCompute();
4074 else
4075 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00004076 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00004077 }
4078
Eli Friedman361e54d2009-05-09 12:32:42 +00004079 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00004080 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4081}
4082
Chris Lattner992efb02011-01-09 22:26:35 +00004083static const SCEVAddRecExpr *
4084isSimpleUnwrappingAddRec(const SCEV *S, const Loop *L) {
4085 const SCEVAddRecExpr *SA = dyn_cast<SCEVAddRecExpr>(S);
Andrew Trick635f7182011-03-09 17:23:39 +00004086
Chris Lattner992efb02011-01-09 22:26:35 +00004087 // The SCEV must be an addrec of this loop.
4088 if (!SA || SA->getLoop() != L || !SA->isAffine())
4089 return 0;
Andrew Trick635f7182011-03-09 17:23:39 +00004090
Chris Lattner992efb02011-01-09 22:26:35 +00004091 // The SCEV must be known to not wrap in some way to be interesting.
Andrew Trick3228cc22011-03-14 16:50:06 +00004092 if (!SA->getNoWrapFlags(SCEV::FlagNW))
Chris Lattner992efb02011-01-09 22:26:35 +00004093 return 0;
4094
4095 // The stride must be a constant so that we know if it is striding up or down.
4096 if (!isa<SCEVConstant>(SA->getOperand(1)))
4097 return 0;
4098 return SA;
4099}
4100
4101/// getMinusSCEVForExitTest - When considering an exit test for a loop with a
4102/// "x != y" exit test, we turn this into a computation that evaluates x-y != 0,
4103/// and this function returns the expression to use for x-y. We know and take
4104/// advantage of the fact that this subtraction is only being used in a
4105/// comparison by zero context.
4106///
Andrew Trick3228cc22011-03-14 16:50:06 +00004107/// FIXME: this can be completely removed once AddRec FlagNWs are propagated.
Chris Lattner992efb02011-01-09 22:26:35 +00004108static const SCEV *getMinusSCEVForExitTest(const SCEV *LHS, const SCEV *RHS,
4109 const Loop *L, ScalarEvolution &SE) {
4110 // If either LHS or RHS is an AddRec SCEV (of this loop) that is known to not
Andrew Trick3228cc22011-03-14 16:50:06 +00004111 // self-wrap, then we know that the value will either become the other one
4112 // (and thus the loop terminates), that the loop will terminate through some
4113 // other exit condition first, or that the loop has undefined behavior. This
4114 // information is useful when the addrec has a stride that is != 1 or -1,
4115 // because it means we can't "miss" the exit value.
Chris Lattner992efb02011-01-09 22:26:35 +00004116 //
4117 // In any of these three cases, it is safe to turn the exit condition into a
4118 // "counting down" AddRec (to zero) by subtracting the two inputs as normal,
4119 // but since we know that the "end cannot be missed" we can force the
4120 // resulting AddRec to be a NUW addrec. Since it is counting down, this means
4121 // that the AddRec *cannot* pass zero.
4122
4123 // See if LHS and RHS are addrec's we can handle.
4124 const SCEVAddRecExpr *LHSA = isSimpleUnwrappingAddRec(LHS, L);
4125 const SCEVAddRecExpr *RHSA = isSimpleUnwrappingAddRec(RHS, L);
Andrew Trick635f7182011-03-09 17:23:39 +00004126
Chris Lattner992efb02011-01-09 22:26:35 +00004127 // If neither addrec is interesting, just return a minus.
4128 if (RHSA == 0 && LHSA == 0)
4129 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004130
Chris Lattner992efb02011-01-09 22:26:35 +00004131 // If only one of LHS and RHS are an AddRec of this loop, make sure it is LHS.
4132 if (RHSA && LHSA == 0) {
4133 // Safe because a-b === b-a for comparisons against zero.
4134 std::swap(LHS, RHS);
4135 std::swap(LHSA, RHSA);
4136 }
Andrew Trick635f7182011-03-09 17:23:39 +00004137
Chris Lattner992efb02011-01-09 22:26:35 +00004138 // Handle the case when only one is advancing in a non-overflowing way.
4139 if (RHSA == 0) {
4140 // If RHS is loop varying, then we can't predict when LHS will cross it.
4141 if (!SE.isLoopInvariant(RHS, L))
4142 return SE.getMinusSCEV(LHS, RHS);
Andrew Trick635f7182011-03-09 17:23:39 +00004143
Chris Lattner992efb02011-01-09 22:26:35 +00004144 // If LHS has a positive stride, then we compute RHS-LHS, because the loop
4145 // is counting up until it crosses RHS (which must be larger than LHS). If
4146 // it is negative, we compute LHS-RHS because we're counting down to RHS.
4147 const ConstantInt *Stride =
4148 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4149 if (Stride->getValue().isNegative())
4150 std::swap(LHS, RHS);
4151
Andrew Trick3228cc22011-03-14 16:50:06 +00004152 return SE.getMinusSCEV(RHS, LHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004153 }
Andrew Trick635f7182011-03-09 17:23:39 +00004154
Chris Lattner992efb02011-01-09 22:26:35 +00004155 // If both LHS and RHS are interesting, we have something like:
4156 // a+i*4 != b+i*8.
4157 const ConstantInt *LHSStride =
4158 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4159 const ConstantInt *RHSStride =
4160 cast<SCEVConstant>(RHSA->getOperand(1))->getValue();
Andrew Trick635f7182011-03-09 17:23:39 +00004161
Chris Lattner992efb02011-01-09 22:26:35 +00004162 // If the strides are equal, then this is just a (complex) loop invariant
Chris Lattner6038a632011-01-11 17:11:59 +00004163 // comparison of a and b.
Chris Lattner992efb02011-01-09 22:26:35 +00004164 if (LHSStride == RHSStride)
4165 return SE.getMinusSCEV(LHSA->getStart(), RHSA->getStart());
Andrew Trick635f7182011-03-09 17:23:39 +00004166
Chris Lattner992efb02011-01-09 22:26:35 +00004167 // If the signs of the strides differ, then the negative stride is counting
4168 // down to the positive stride.
4169 if (LHSStride->getValue().isNegative() != RHSStride->getValue().isNegative()){
4170 if (RHSStride->getValue().isNegative())
4171 std::swap(LHS, RHS);
4172 } else {
4173 // If LHS's stride is smaller than RHS's stride, then "b" must be less than
4174 // "a" and "b" is RHS is counting up (catching up) to LHS. This is true
4175 // whether the strides are positive or negative.
4176 if (RHSStride->getValue().slt(LHSStride->getValue()))
4177 std::swap(LHS, RHS);
4178 }
Andrew Trick635f7182011-03-09 17:23:39 +00004179
Andrew Trick3228cc22011-03-14 16:50:06 +00004180 return SE.getMinusSCEV(LHS, RHS, SCEV::FlagNUW);
Chris Lattner992efb02011-01-09 22:26:35 +00004181}
4182
Dan Gohmana334aa72009-06-22 00:31:57 +00004183/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
4184/// backedge of the specified loop will execute if its exit condition
4185/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4186ScalarEvolution::BackedgeTakenInfo
4187ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
4188 ICmpInst *ExitCond,
4189 BasicBlock *TBB,
4190 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004191
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 // If the condition was exit on true, convert the condition to exit on false
4193 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00004194 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004196 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004197 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004198
4199 // Handle common loops like: for (X = "string"; *X; ++X)
4200 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4201 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004202 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004203 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004204 if (ItCnt.hasAnyInfo())
4205 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00004206 }
4207
Dan Gohman0bba49c2009-07-07 17:06:11 +00004208 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4209 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00004210
4211 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004212 LHS = getSCEVAtScope(LHS, L);
4213 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004214
Dan Gohman64a845e2009-06-24 04:48:43 +00004215 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004216 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004217 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004218 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004219 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004220 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004221 }
4222
Dan Gohman03557dc2010-05-03 16:35:17 +00004223 // Simplify the operands before analyzing them.
4224 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4225
Chris Lattner53e677a2004-04-02 20:23:17 +00004226 // If we have a comparison of a chrec against a constant, try to use value
4227 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004228 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4229 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004230 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004231 // Form the constant range.
4232 ConstantRange CompRange(
4233 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004234
Dan Gohman0bba49c2009-07-07 17:06:11 +00004235 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004236 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004237 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004238
Chris Lattner53e677a2004-04-02 20:23:17 +00004239 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004240 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004241 // Convert to: while (X-Y != 0)
Andrew Trick3228cc22011-03-14 16:50:06 +00004242 // FIXME: Once AddRec FlagNW are propagated, should be:
4243 // BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Chris Lattner992efb02011-01-09 22:26:35 +00004244 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEVForExitTest(LHS, RHS, L,
4245 *this), L);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004246 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004247 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004248 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004249 case ICmpInst::ICMP_EQ: { // while (X == Y)
4250 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004251 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4252 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004253 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004254 }
4255 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004256 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4257 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004258 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 }
4260 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004261 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4262 getNotSCEV(RHS), L, true);
4263 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004264 break;
4265 }
4266 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004267 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4268 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004269 break;
4270 }
4271 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004272 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4273 getNotSCEV(RHS), L, false);
4274 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004275 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004276 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004277 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004278#if 0
David Greene25e0e872009-12-23 22:18:14 +00004279 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004280 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004281 dbgs() << "[unsigned] ";
4282 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004283 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004284 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004285#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004286 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004287 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004288 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004289 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004290}
4291
Chris Lattner673e02b2004-10-12 01:49:27 +00004292static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004293EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4294 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004295 const SCEV *InVal = SE.getConstant(C);
4296 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004297 assert(isa<SCEVConstant>(Val) &&
4298 "Evaluation of SCEV at constant didn't fold correctly?");
4299 return cast<SCEVConstant>(Val)->getValue();
4300}
4301
4302/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4303/// and a GEP expression (missing the pointer index) indexing into it, return
4304/// the addressed element of the initializer or null if the index expression is
4305/// invalid.
4306static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004307GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004308 const std::vector<ConstantInt*> &Indices) {
4309 Constant *Init = GV->getInitializer();
4310 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004311 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004312 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4313 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4314 Init = cast<Constant>(CS->getOperand(Idx));
4315 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4316 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4317 Init = cast<Constant>(CA->getOperand(Idx));
4318 } else if (isa<ConstantAggregateZero>(Init)) {
4319 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4320 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004321 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004322 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4323 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004324 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004325 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004326 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004327 }
4328 return 0;
4329 } else {
4330 return 0; // Unknown initializer type
4331 }
4332 }
4333 return Init;
4334}
4335
Dan Gohman46bdfb02009-02-24 18:55:53 +00004336/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4337/// 'icmp op load X, cst', try to see if we can compute the backedge
4338/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004339ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004340ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4341 LoadInst *LI,
4342 Constant *RHS,
4343 const Loop *L,
4344 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004345 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004346
4347 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004348 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004349 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004350 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004351
4352 // Make sure that it is really a constant global we are gepping, with an
4353 // initializer, and make sure the first IDX is really 0.
4354 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004355 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004356 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4357 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004358 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004359
4360 // Okay, we allow one non-constant index into the GEP instruction.
4361 Value *VarIdx = 0;
4362 std::vector<ConstantInt*> Indexes;
4363 unsigned VarIdxNum = 0;
4364 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4365 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4366 Indexes.push_back(CI);
4367 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004368 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004369 VarIdx = GEP->getOperand(i);
4370 VarIdxNum = i-2;
4371 Indexes.push_back(0);
4372 }
4373
4374 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4375 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004376 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004377 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004378
4379 // We can only recognize very limited forms of loop index expressions, in
4380 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004381 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004382 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004383 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4384 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004385 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004386
4387 unsigned MaxSteps = MaxBruteForceIterations;
4388 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004389 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004390 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004391 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004392
4393 // Form the GEP offset.
4394 Indexes[VarIdxNum] = Val;
4395
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004396 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004397 if (Result == 0) break; // Cannot compute!
4398
4399 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004400 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004401 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004402 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004403#if 0
David Greene25e0e872009-12-23 22:18:14 +00004404 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004405 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4406 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004407#endif
4408 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004409 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004410 }
4411 }
Dan Gohman1c343752009-06-27 21:21:31 +00004412 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004413}
4414
4415
Chris Lattner3221ad02004-04-17 22:58:41 +00004416/// CanConstantFold - Return true if we can constant fold an instruction of the
4417/// specified type, assuming that all operands were constants.
4418static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004419 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004420 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4421 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004422
Chris Lattner3221ad02004-04-17 22:58:41 +00004423 if (const CallInst *CI = dyn_cast<CallInst>(I))
4424 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004425 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004426 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004427}
4428
Chris Lattner3221ad02004-04-17 22:58:41 +00004429/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4430/// in the loop that V is derived from. We allow arbitrary operations along the
4431/// way, but the operands of an operation must either be constants or a value
4432/// derived from a constant PHI. If this expression does not fit with these
4433/// constraints, return null.
4434static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4435 // If this is not an instruction, or if this is an instruction outside of the
4436 // loop, it can't be derived from a loop PHI.
4437 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004438 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004439
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004440 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004441 if (L->getHeader() == I->getParent())
4442 return PN;
4443 else
4444 // We don't currently keep track of the control flow needed to evaluate
4445 // PHIs, so we cannot handle PHIs inside of loops.
4446 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004447 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004448
4449 // If we won't be able to constant fold this expression even if the operands
4450 // are constants, return early.
4451 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004452
Chris Lattner3221ad02004-04-17 22:58:41 +00004453 // Otherwise, we can evaluate this instruction if all of its operands are
4454 // constant or derived from a PHI node themselves.
4455 PHINode *PHI = 0;
4456 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004457 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004458 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4459 if (P == 0) return 0; // Not evolving from PHI
4460 if (PHI == 0)
4461 PHI = P;
4462 else if (PHI != P)
4463 return 0; // Evolving from multiple different PHIs.
4464 }
4465
4466 // This is a expression evolving from a constant PHI!
4467 return PHI;
4468}
4469
4470/// EvaluateExpression - Given an expression that passes the
4471/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4472/// in the loop has the value PHIVal. If we can't fold this expression for some
4473/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004474static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4475 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004476 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004477 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004478 Instruction *I = cast<Instruction>(V);
4479
Dan Gohman9d4588f2010-06-22 13:15:46 +00004480 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004481
4482 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004483 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004484 if (Operands[i] == 0) return 0;
4485 }
4486
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004487 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004488 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004489 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004490 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004491 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004492}
4493
4494/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4495/// in the header of its containing loop, we know the loop executes a
4496/// constant number of times, and the PHI node is just a recurrence
4497/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004498Constant *
4499ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004500 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004501 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004502 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004503 ConstantEvolutionLoopExitValue.find(PN);
4504 if (I != ConstantEvolutionLoopExitValue.end())
4505 return I->second;
4506
Dan Gohmane0567812010-04-08 23:03:40 +00004507 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004508 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4509
4510 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4511
4512 // Since the loop is canonicalized, the PHI node must have two entries. One
4513 // entry must be a constant (coming in from outside of the loop), and the
4514 // second must be derived from the same PHI.
4515 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4516 Constant *StartCST =
4517 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4518 if (StartCST == 0)
4519 return RetVal = 0; // Must be a constant.
4520
4521 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004522 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4523 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004524 return RetVal = 0; // Not derived from same PHI.
4525
4526 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004527 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004528 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004529
Dan Gohman46bdfb02009-02-24 18:55:53 +00004530 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004531 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004532 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4533 if (IterationNum == NumIterations)
4534 return RetVal = PHIVal; // Got exit value!
4535
4536 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004537 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004538 if (NextPHI == PHIVal)
4539 return RetVal = NextPHI; // Stopped evolving!
4540 if (NextPHI == 0)
4541 return 0; // Couldn't evaluate!
4542 PHIVal = NextPHI;
4543 }
4544}
4545
Dan Gohman07ad19b2009-07-27 16:09:48 +00004546/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004547/// constant number of times (the condition evolves only from constants),
4548/// try to evaluate a few iterations of the loop until we get the exit
4549/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004550/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004551const SCEV *
4552ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4553 Value *Cond,
4554 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004555 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004556 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004557
Dan Gohmanb92654d2010-06-19 14:17:24 +00004558 // If the loop is canonicalized, the PHI will have exactly two entries.
4559 // That's the only form we support here.
4560 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4561
4562 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004563 // second must be derived from the same PHI.
4564 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4565 Constant *StartCST =
4566 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004567 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004568
4569 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004570 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4571 !isa<Constant>(BEValue))
4572 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004573
4574 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4575 // the loop symbolically to determine when the condition gets a value of
4576 // "ExitWhen".
4577 unsigned IterationNum = 0;
4578 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4579 for (Constant *PHIVal = StartCST;
4580 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004581 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004582 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004583
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004584 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004585 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004586
Reid Spencere8019bb2007-03-01 07:25:48 +00004587 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004588 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004589 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004590 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004591
Chris Lattner3221ad02004-04-17 22:58:41 +00004592 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004593 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004594 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004595 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004596 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004597 }
4598
4599 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004600 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004601}
4602
Dan Gohmane7125f42009-09-03 15:00:26 +00004603/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004604/// at the specified scope in the program. The L value specifies a loop
4605/// nest to evaluate the expression at, where null is the top-level or a
4606/// specified loop is immediately inside of the loop.
4607///
4608/// This method can be used to compute the exit value for a variable defined
4609/// in a loop by querying what the value will hold in the parent loop.
4610///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004611/// In the case that a relevant loop exit value cannot be computed, the
4612/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004613const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004614 // Check to see if we've folded this expression at this loop before.
4615 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4616 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4617 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4618 if (!Pair.second)
4619 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004620
Dan Gohman42214892009-08-31 21:15:23 +00004621 // Otherwise compute it.
4622 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004623 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004624 return C;
4625}
4626
4627const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004628 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004629
Nick Lewycky3e630762008-02-20 06:48:22 +00004630 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004631 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004632 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004633 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004634 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004635 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4636 if (PHINode *PN = dyn_cast<PHINode>(I))
4637 if (PN->getParent() == LI->getHeader()) {
4638 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004639 // to see if the loop that contains it has a known backedge-taken
4640 // count. If so, we may be able to force computation of the exit
4641 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004642 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004643 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004644 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004645 // Okay, we know how many times the containing loop executes. If
4646 // this is a constant evolving PHI node, get the final value at
4647 // the specified iteration number.
4648 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004649 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004650 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004651 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004652 }
4653 }
4654
Reid Spencer09906f32006-12-04 21:33:23 +00004655 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004656 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004657 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004658 // result. This is particularly useful for computing loop exit values.
4659 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004660 SmallVector<Constant *, 4> Operands;
4661 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004662 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4663 Value *Op = I->getOperand(i);
4664 if (Constant *C = dyn_cast<Constant>(Op)) {
4665 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004666 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004667 }
Dan Gohman11046452010-06-29 23:43:06 +00004668
4669 // If any of the operands is non-constant and if they are
4670 // non-integer and non-pointer, don't even try to analyze them
4671 // with scev techniques.
4672 if (!isSCEVable(Op->getType()))
4673 return V;
4674
4675 const SCEV *OrigV = getSCEV(Op);
4676 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4677 MadeImprovement |= OrigV != OpV;
4678
4679 Constant *C = 0;
4680 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4681 C = SC->getValue();
4682 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4683 C = dyn_cast<Constant>(SU->getValue());
4684 if (!C) return V;
4685 if (C->getType() != Op->getType())
4686 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4687 Op->getType(),
4688 false),
4689 C, Op->getType());
4690 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004691 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004692
Dan Gohman11046452010-06-29 23:43:06 +00004693 // Check to see if getSCEVAtScope actually made an improvement.
4694 if (MadeImprovement) {
4695 Constant *C = 0;
4696 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4697 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4698 Operands[0], Operands[1], TD);
4699 else
4700 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4701 &Operands[0], Operands.size(), TD);
4702 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004703 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004704 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004705 }
4706 }
4707
4708 // This is some other type of SCEVUnknown, just return it.
4709 return V;
4710 }
4711
Dan Gohman622ed672009-05-04 22:02:23 +00004712 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004713 // Avoid performing the look-up in the common case where the specified
4714 // expression has no loop-variant portions.
4715 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004716 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004717 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004718 // Okay, at least one of these operands is loop variant but might be
4719 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004720 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4721 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004722 NewOps.push_back(OpAtScope);
4723
4724 for (++i; i != e; ++i) {
4725 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004726 NewOps.push_back(OpAtScope);
4727 }
4728 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004729 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004730 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004731 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004732 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004733 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004734 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004735 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004736 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004737 }
4738 }
4739 // If we got here, all operands are loop invariant.
4740 return Comm;
4741 }
4742
Dan Gohman622ed672009-05-04 22:02:23 +00004743 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004744 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4745 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004746 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4747 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004748 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004749 }
4750
4751 // If this is a loop recurrence for a loop that does not contain L, then we
4752 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004753 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004754 // First, attempt to evaluate each operand.
4755 // Avoid performing the look-up in the common case where the specified
4756 // expression has no loop-variant portions.
4757 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4758 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4759 if (OpAtScope == AddRec->getOperand(i))
4760 continue;
4761
4762 // Okay, at least one of these operands is loop variant but might be
4763 // foldable. Build a new instance of the folded commutative expression.
4764 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4765 AddRec->op_begin()+i);
4766 NewOps.push_back(OpAtScope);
4767 for (++i; i != e; ++i)
4768 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4769
Andrew Trick3228cc22011-03-14 16:50:06 +00004770 AddRec = cast<SCEVAddRecExpr>(
4771 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00004772 AddRec->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman11046452010-06-29 23:43:06 +00004773 break;
4774 }
4775
4776 // If the scope is outside the addrec's loop, evaluate it by using the
4777 // loop exit value of the addrec.
4778 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004779 // To evaluate this recurrence, we need to know how many times the AddRec
4780 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004781 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004782 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004783
Eli Friedmanb42a6262008-08-04 23:49:06 +00004784 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004785 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004786 }
Dan Gohman11046452010-06-29 23:43:06 +00004787
Dan Gohmand594e6f2009-05-24 23:25:42 +00004788 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004789 }
4790
Dan Gohman622ed672009-05-04 22:02:23 +00004791 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004792 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004793 if (Op == Cast->getOperand())
4794 return Cast; // must be loop invariant
4795 return getZeroExtendExpr(Op, Cast->getType());
4796 }
4797
Dan Gohman622ed672009-05-04 22:02:23 +00004798 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004799 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004800 if (Op == Cast->getOperand())
4801 return Cast; // must be loop invariant
4802 return getSignExtendExpr(Op, Cast->getType());
4803 }
4804
Dan Gohman622ed672009-05-04 22:02:23 +00004805 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004806 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004807 if (Op == Cast->getOperand())
4808 return Cast; // must be loop invariant
4809 return getTruncateExpr(Op, Cast->getType());
4810 }
4811
Torok Edwinc23197a2009-07-14 16:55:14 +00004812 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004813 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004814}
4815
Dan Gohman66a7e852009-05-08 20:38:54 +00004816/// getSCEVAtScope - This is a convenience function which does
4817/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004818const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004819 return getSCEVAtScope(getSCEV(V), L);
4820}
4821
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004822/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4823/// following equation:
4824///
4825/// A * X = B (mod N)
4826///
4827/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4828/// A and B isn't important.
4829///
4830/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004831static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004832 ScalarEvolution &SE) {
4833 uint32_t BW = A.getBitWidth();
4834 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4835 assert(A != 0 && "A must be non-zero.");
4836
4837 // 1. D = gcd(A, N)
4838 //
4839 // The gcd of A and N may have only one prime factor: 2. The number of
4840 // trailing zeros in A is its multiplicity
4841 uint32_t Mult2 = A.countTrailingZeros();
4842 // D = 2^Mult2
4843
4844 // 2. Check if B is divisible by D.
4845 //
4846 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4847 // is not less than multiplicity of this prime factor for D.
4848 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004849 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004850
4851 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4852 // modulo (N / D).
4853 //
4854 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4855 // bit width during computations.
4856 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4857 APInt Mod(BW + 1, 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00004858 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004859 APInt I = AD.multiplicativeInverse(Mod);
4860
4861 // 4. Compute the minimum unsigned root of the equation:
4862 // I * (B / D) mod (N / D)
4863 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4864
4865 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4866 // bits.
4867 return SE.getConstant(Result.trunc(BW));
4868}
Chris Lattner53e677a2004-04-02 20:23:17 +00004869
4870/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4871/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4872/// might be the same) or two SCEVCouldNotCompute objects.
4873///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004874static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004875SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004876 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004877 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4878 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4879 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004880
Chris Lattner53e677a2004-04-02 20:23:17 +00004881 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004882 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004883 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004884 return std::make_pair(CNC, CNC);
4885 }
4886
Reid Spencere8019bb2007-03-01 07:25:48 +00004887 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004888 const APInt &L = LC->getValue()->getValue();
4889 const APInt &M = MC->getValue()->getValue();
4890 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004891 APInt Two(BitWidth, 2);
4892 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004893
Dan Gohman64a845e2009-06-24 04:48:43 +00004894 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004895 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004896 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004897 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4898 // The B coefficient is M-N/2
4899 APInt B(M);
4900 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004901
Reid Spencere8019bb2007-03-01 07:25:48 +00004902 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004903 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004904
Reid Spencere8019bb2007-03-01 07:25:48 +00004905 // Compute the B^2-4ac term.
4906 APInt SqrtTerm(B);
4907 SqrtTerm *= B;
4908 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004909
Reid Spencere8019bb2007-03-01 07:25:48 +00004910 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4911 // integer value or else APInt::sqrt() will assert.
4912 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004913
Dan Gohman64a845e2009-06-24 04:48:43 +00004914 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004915 // The divisions must be performed as signed divisions.
4916 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004917 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004918 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004919 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004920 return std::make_pair(CNC, CNC);
4921 }
4922
Owen Andersone922c022009-07-22 00:24:57 +00004923 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004924
4925 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004926 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004927 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004928 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004929
Dan Gohman64a845e2009-06-24 04:48:43 +00004930 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004931 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004932 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004933}
4934
4935/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004936/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick3228cc22011-03-14 16:50:06 +00004937///
4938/// This is only used for loops with a "x != y" exit test. The exit condition is
4939/// now expressed as a single expression, V = x-y. So the exit test is
4940/// effectively V != 0. We know and take advantage of the fact that this
4941/// expression only being used in a comparison by zero context.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004942ScalarEvolution::BackedgeTakenInfo
4943ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004944 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004945 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004946 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004947 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004948 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004949 }
4950
Dan Gohman35738ac2009-05-04 22:30:44 +00004951 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004952 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004953 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004954
Chris Lattner7975e3e2011-01-09 22:39:48 +00004955 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4956 // the quadratic equation to solve it.
4957 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4958 std::pair<const SCEV *,const SCEV *> Roots =
4959 SolveQuadraticEquation(AddRec, *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004960 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4961 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner7975e3e2011-01-09 22:39:48 +00004962 if (R1 && R2) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004963#if 0
David Greene25e0e872009-12-23 22:18:14 +00004964 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004965 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004966#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004967 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004968 if (ConstantInt *CB =
Chris Lattner53e1d452011-01-09 22:58:47 +00004969 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
4970 R1->getValue(),
4971 R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004972 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004973 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick635f7182011-03-09 17:23:39 +00004974
Chris Lattner53e677a2004-04-02 20:23:17 +00004975 // We can only use this value if the chrec ends up with an exact zero
4976 // value at this index. When solving for "X*X != 5", for example, we
4977 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004978 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004979 if (Val->isZero())
4980 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004981 }
4982 }
Chris Lattner7975e3e2011-01-09 22:39:48 +00004983 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004984 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004985
Chris Lattner7975e3e2011-01-09 22:39:48 +00004986 // Otherwise we can only handle this if it is affine.
4987 if (!AddRec->isAffine())
4988 return getCouldNotCompute();
4989
4990 // If this is an affine expression, the execution count of this branch is
4991 // the minimum unsigned root of the following equation:
4992 //
4993 // Start + Step*N = 0 (mod 2^BW)
4994 //
4995 // equivalent to:
4996 //
4997 // Step*N = -Start (mod 2^BW)
4998 //
4999 // where BW is the common bit width of Start and Step.
5000
5001 // Get the initial value for the loop.
5002 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5003 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5004
5005 // For now we handle only constant steps.
Andrew Trick3228cc22011-03-14 16:50:06 +00005006 //
5007 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5008 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5009 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5010 // We have not yet seen any such cases.
Chris Lattner7975e3e2011-01-09 22:39:48 +00005011 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5012 if (StepC == 0)
5013 return getCouldNotCompute();
5014
Andrew Trick3228cc22011-03-14 16:50:06 +00005015 // For positive steps (counting up until unsigned overflow):
5016 // N = -Start/Step (as unsigned)
5017 // For negative steps (counting down to zero):
5018 // N = Start/-Step
5019 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005020 bool CountDown = StepC->getValue()->getValue().isNegative();
5021 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick3228cc22011-03-14 16:50:06 +00005022
5023 // Handle unitary steps, which cannot wraparound.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005024 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5025 // N = Distance (as unsigned)
5026 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue())
5027 return Distance;
Andrew Trick635f7182011-03-09 17:23:39 +00005028
Andrew Trickdcfd4042011-03-14 17:28:02 +00005029 // If the recurrence is known not to wraparound, unsigned divide computes the
5030 // back edge count. We know that the value will either become zero (and thus
5031 // the loop terminates), that the loop will terminate through some other exit
5032 // condition first, or that the loop has undefined behavior. This means
5033 // we can't "miss" the exit value, even with nonunit stride.
5034 //
5035 // FIXME: Prove that loops always exhibits *acceptable* undefined
5036 // behavior. Loops must exhibit defined behavior until a wrapped value is
5037 // actually used. So the trip count computed by udiv could be smaller than the
5038 // number of well-defined iterations.
5039 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5040 // FIXME: We really want an "isexact" bit for udiv.
5041 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005042
5043 // Then, try to solve the above equation provided that Start is constant.
5044 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5045 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5046 -StartC->getValue()->getValue(),
5047 *this);
Dan Gohman1c343752009-06-27 21:21:31 +00005048 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005049}
5050
5051/// HowFarToNonZero - Return the number of times a backedge checking the
5052/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005053/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005054ScalarEvolution::BackedgeTakenInfo
5055ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005056 // Loops that look like: while (X == 0) are very strange indeed. We don't
5057 // handle them yet except for the trivial case. This could be expanded in the
5058 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005059
Chris Lattner53e677a2004-04-02 20:23:17 +00005060 // If the value is a constant, check to see if it is known to be non-zero
5061 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00005062 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00005063 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00005064 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00005065 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005066 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005067
Chris Lattner53e677a2004-04-02 20:23:17 +00005068 // We could implement others, but I really doubt anyone writes loops like
5069 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00005070 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005071}
5072
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005073/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5074/// (which may not be an immediate predecessor) which has exactly one
5075/// successor from which BB is reachable, or null if no such block is
5076/// found.
5077///
Dan Gohman005752b2010-04-15 16:19:08 +00005078std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005079ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00005080 // If the block has a unique predecessor, then there is no path from the
5081 // predecessor to the block that does not go through the direct edge
5082 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005083 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00005084 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005085
5086 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00005087 // If the header has a unique predecessor outside the loop, it must be
5088 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005089 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00005090 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005091
Dan Gohman005752b2010-04-15 16:19:08 +00005092 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005093}
5094
Dan Gohman763bad12009-06-20 00:35:32 +00005095/// HasSameValue - SCEV structural equivalence is usually sufficient for
5096/// testing whether two expressions are equal, however for the purposes of
5097/// looking for a condition guarding a loop, it can be useful to be a little
5098/// more general, since a front-end may have replicated the controlling
5099/// expression.
5100///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005101static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00005102 // Quick check to see if they are the same SCEV.
5103 if (A == B) return true;
5104
5105 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5106 // two different instructions with the same value. Check for this case.
5107 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5108 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5109 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5110 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00005111 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00005112 return true;
5113
5114 // Otherwise assume they may have a different value.
5115 return false;
5116}
5117
Dan Gohmane9796502010-04-24 01:28:42 +00005118/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5119/// predicate Pred. Return true iff any changes were made.
5120///
5121bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5122 const SCEV *&LHS, const SCEV *&RHS) {
5123 bool Changed = false;
5124
5125 // Canonicalize a constant to the right side.
5126 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5127 // Check for both operands constant.
5128 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5129 if (ConstantExpr::getICmp(Pred,
5130 LHSC->getValue(),
5131 RHSC->getValue())->isNullValue())
5132 goto trivially_false;
5133 else
5134 goto trivially_true;
5135 }
5136 // Otherwise swap the operands to put the constant on the right.
5137 std::swap(LHS, RHS);
5138 Pred = ICmpInst::getSwappedPredicate(Pred);
5139 Changed = true;
5140 }
5141
5142 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00005143 // addrec's loop, put the addrec on the left. Also make a dominance check,
5144 // as both operands could be addrecs loop-invariant in each other's loop.
5145 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5146 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005147 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00005148 std::swap(LHS, RHS);
5149 Pred = ICmpInst::getSwappedPredicate(Pred);
5150 Changed = true;
5151 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00005152 }
Dan Gohmane9796502010-04-24 01:28:42 +00005153
5154 // If there's a constant operand, canonicalize comparisons with boundary
5155 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5156 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5157 const APInt &RA = RC->getValue()->getValue();
5158 switch (Pred) {
5159 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5160 case ICmpInst::ICMP_EQ:
5161 case ICmpInst::ICMP_NE:
5162 break;
5163 case ICmpInst::ICMP_UGE:
5164 if ((RA - 1).isMinValue()) {
5165 Pred = ICmpInst::ICMP_NE;
5166 RHS = getConstant(RA - 1);
5167 Changed = true;
5168 break;
5169 }
5170 if (RA.isMaxValue()) {
5171 Pred = ICmpInst::ICMP_EQ;
5172 Changed = true;
5173 break;
5174 }
5175 if (RA.isMinValue()) goto trivially_true;
5176
5177 Pred = ICmpInst::ICMP_UGT;
5178 RHS = getConstant(RA - 1);
5179 Changed = true;
5180 break;
5181 case ICmpInst::ICMP_ULE:
5182 if ((RA + 1).isMaxValue()) {
5183 Pred = ICmpInst::ICMP_NE;
5184 RHS = getConstant(RA + 1);
5185 Changed = true;
5186 break;
5187 }
5188 if (RA.isMinValue()) {
5189 Pred = ICmpInst::ICMP_EQ;
5190 Changed = true;
5191 break;
5192 }
5193 if (RA.isMaxValue()) goto trivially_true;
5194
5195 Pred = ICmpInst::ICMP_ULT;
5196 RHS = getConstant(RA + 1);
5197 Changed = true;
5198 break;
5199 case ICmpInst::ICMP_SGE:
5200 if ((RA - 1).isMinSignedValue()) {
5201 Pred = ICmpInst::ICMP_NE;
5202 RHS = getConstant(RA - 1);
5203 Changed = true;
5204 break;
5205 }
5206 if (RA.isMaxSignedValue()) {
5207 Pred = ICmpInst::ICMP_EQ;
5208 Changed = true;
5209 break;
5210 }
5211 if (RA.isMinSignedValue()) goto trivially_true;
5212
5213 Pred = ICmpInst::ICMP_SGT;
5214 RHS = getConstant(RA - 1);
5215 Changed = true;
5216 break;
5217 case ICmpInst::ICMP_SLE:
5218 if ((RA + 1).isMaxSignedValue()) {
5219 Pred = ICmpInst::ICMP_NE;
5220 RHS = getConstant(RA + 1);
5221 Changed = true;
5222 break;
5223 }
5224 if (RA.isMinSignedValue()) {
5225 Pred = ICmpInst::ICMP_EQ;
5226 Changed = true;
5227 break;
5228 }
5229 if (RA.isMaxSignedValue()) goto trivially_true;
5230
5231 Pred = ICmpInst::ICMP_SLT;
5232 RHS = getConstant(RA + 1);
5233 Changed = true;
5234 break;
5235 case ICmpInst::ICMP_UGT:
5236 if (RA.isMinValue()) {
5237 Pred = ICmpInst::ICMP_NE;
5238 Changed = true;
5239 break;
5240 }
5241 if ((RA + 1).isMaxValue()) {
5242 Pred = ICmpInst::ICMP_EQ;
5243 RHS = getConstant(RA + 1);
5244 Changed = true;
5245 break;
5246 }
5247 if (RA.isMaxValue()) goto trivially_false;
5248 break;
5249 case ICmpInst::ICMP_ULT:
5250 if (RA.isMaxValue()) {
5251 Pred = ICmpInst::ICMP_NE;
5252 Changed = true;
5253 break;
5254 }
5255 if ((RA - 1).isMinValue()) {
5256 Pred = ICmpInst::ICMP_EQ;
5257 RHS = getConstant(RA - 1);
5258 Changed = true;
5259 break;
5260 }
5261 if (RA.isMinValue()) goto trivially_false;
5262 break;
5263 case ICmpInst::ICMP_SGT:
5264 if (RA.isMinSignedValue()) {
5265 Pred = ICmpInst::ICMP_NE;
5266 Changed = true;
5267 break;
5268 }
5269 if ((RA + 1).isMaxSignedValue()) {
5270 Pred = ICmpInst::ICMP_EQ;
5271 RHS = getConstant(RA + 1);
5272 Changed = true;
5273 break;
5274 }
5275 if (RA.isMaxSignedValue()) goto trivially_false;
5276 break;
5277 case ICmpInst::ICMP_SLT:
5278 if (RA.isMaxSignedValue()) {
5279 Pred = ICmpInst::ICMP_NE;
5280 Changed = true;
5281 break;
5282 }
5283 if ((RA - 1).isMinSignedValue()) {
5284 Pred = ICmpInst::ICMP_EQ;
5285 RHS = getConstant(RA - 1);
5286 Changed = true;
5287 break;
5288 }
5289 if (RA.isMinSignedValue()) goto trivially_false;
5290 break;
5291 }
5292 }
5293
5294 // Check for obvious equality.
5295 if (HasSameValue(LHS, RHS)) {
5296 if (ICmpInst::isTrueWhenEqual(Pred))
5297 goto trivially_true;
5298 if (ICmpInst::isFalseWhenEqual(Pred))
5299 goto trivially_false;
5300 }
5301
Dan Gohman03557dc2010-05-03 16:35:17 +00005302 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5303 // adding or subtracting 1 from one of the operands.
5304 switch (Pred) {
5305 case ICmpInst::ICMP_SLE:
5306 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5307 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005308 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005309 Pred = ICmpInst::ICMP_SLT;
5310 Changed = true;
5311 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005312 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005313 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005314 Pred = ICmpInst::ICMP_SLT;
5315 Changed = true;
5316 }
5317 break;
5318 case ICmpInst::ICMP_SGE:
5319 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005320 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005321 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005322 Pred = ICmpInst::ICMP_SGT;
5323 Changed = true;
5324 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5325 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005326 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005327 Pred = ICmpInst::ICMP_SGT;
5328 Changed = true;
5329 }
5330 break;
5331 case ICmpInst::ICMP_ULE:
5332 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005333 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005334 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005335 Pred = ICmpInst::ICMP_ULT;
5336 Changed = true;
5337 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005338 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005339 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005340 Pred = ICmpInst::ICMP_ULT;
5341 Changed = true;
5342 }
5343 break;
5344 case ICmpInst::ICMP_UGE:
5345 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005346 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005347 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005348 Pred = ICmpInst::ICMP_UGT;
5349 Changed = true;
5350 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005351 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005352 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005353 Pred = ICmpInst::ICMP_UGT;
5354 Changed = true;
5355 }
5356 break;
5357 default:
5358 break;
5359 }
5360
Dan Gohmane9796502010-04-24 01:28:42 +00005361 // TODO: More simplifications are possible here.
5362
5363 return Changed;
5364
5365trivially_true:
5366 // Return 0 == 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005367 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005368 Pred = ICmpInst::ICMP_EQ;
5369 return true;
5370
5371trivially_false:
5372 // Return 0 != 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005373 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005374 Pred = ICmpInst::ICMP_NE;
5375 return true;
5376}
5377
Dan Gohman85b05a22009-07-13 21:35:55 +00005378bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5379 return getSignedRange(S).getSignedMax().isNegative();
5380}
5381
5382bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5383 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5384}
5385
5386bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5387 return !getSignedRange(S).getSignedMin().isNegative();
5388}
5389
5390bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5391 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5392}
5393
5394bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5395 return isKnownNegative(S) || isKnownPositive(S);
5396}
5397
5398bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5399 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005400 // Canonicalize the inputs first.
5401 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5402
Dan Gohman53c66ea2010-04-11 22:16:48 +00005403 // If LHS or RHS is an addrec, check to see if the condition is true in
5404 // every iteration of the loop.
5405 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5406 if (isLoopEntryGuardedByCond(
5407 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5408 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005409 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005410 return true;
5411 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5412 if (isLoopEntryGuardedByCond(
5413 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5414 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005415 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005416 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005417
Dan Gohman53c66ea2010-04-11 22:16:48 +00005418 // Otherwise see what can be done with known constant ranges.
5419 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5420}
5421
5422bool
5423ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5424 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005425 if (HasSameValue(LHS, RHS))
5426 return ICmpInst::isTrueWhenEqual(Pred);
5427
Dan Gohman53c66ea2010-04-11 22:16:48 +00005428 // This code is split out from isKnownPredicate because it is called from
5429 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005430 switch (Pred) {
5431 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005432 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005433 break;
5434 case ICmpInst::ICMP_SGT:
5435 Pred = ICmpInst::ICMP_SLT;
5436 std::swap(LHS, RHS);
5437 case ICmpInst::ICMP_SLT: {
5438 ConstantRange LHSRange = getSignedRange(LHS);
5439 ConstantRange RHSRange = getSignedRange(RHS);
5440 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5441 return true;
5442 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5443 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005444 break;
5445 }
5446 case ICmpInst::ICMP_SGE:
5447 Pred = ICmpInst::ICMP_SLE;
5448 std::swap(LHS, RHS);
5449 case ICmpInst::ICMP_SLE: {
5450 ConstantRange LHSRange = getSignedRange(LHS);
5451 ConstantRange RHSRange = getSignedRange(RHS);
5452 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5453 return true;
5454 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5455 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005456 break;
5457 }
5458 case ICmpInst::ICMP_UGT:
5459 Pred = ICmpInst::ICMP_ULT;
5460 std::swap(LHS, RHS);
5461 case ICmpInst::ICMP_ULT: {
5462 ConstantRange LHSRange = getUnsignedRange(LHS);
5463 ConstantRange RHSRange = getUnsignedRange(RHS);
5464 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5465 return true;
5466 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5467 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005468 break;
5469 }
5470 case ICmpInst::ICMP_UGE:
5471 Pred = ICmpInst::ICMP_ULE;
5472 std::swap(LHS, RHS);
5473 case ICmpInst::ICMP_ULE: {
5474 ConstantRange LHSRange = getUnsignedRange(LHS);
5475 ConstantRange RHSRange = getUnsignedRange(RHS);
5476 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5477 return true;
5478 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5479 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005480 break;
5481 }
5482 case ICmpInst::ICMP_NE: {
5483 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5484 return true;
5485 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5486 return true;
5487
5488 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5489 if (isKnownNonZero(Diff))
5490 return true;
5491 break;
5492 }
5493 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005494 // The check at the top of the function catches the case where
5495 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005496 break;
5497 }
5498 return false;
5499}
5500
5501/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5502/// protected by a conditional between LHS and RHS. This is used to
5503/// to eliminate casts.
5504bool
5505ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5506 ICmpInst::Predicate Pred,
5507 const SCEV *LHS, const SCEV *RHS) {
5508 // Interpret a null as meaning no loop, where there is obviously no guard
5509 // (interprocedural conditions notwithstanding).
5510 if (!L) return true;
5511
5512 BasicBlock *Latch = L->getLoopLatch();
5513 if (!Latch)
5514 return false;
5515
5516 BranchInst *LoopContinuePredicate =
5517 dyn_cast<BranchInst>(Latch->getTerminator());
5518 if (!LoopContinuePredicate ||
5519 LoopContinuePredicate->isUnconditional())
5520 return false;
5521
Dan Gohmanaf08a362010-08-10 23:46:30 +00005522 return isImpliedCond(Pred, LHS, RHS,
5523 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005524 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005525}
5526
Dan Gohman3948d0b2010-04-11 19:27:13 +00005527/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005528/// by a conditional between LHS and RHS. This is used to help avoid max
5529/// expressions in loop trip counts, and to eliminate casts.
5530bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005531ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5532 ICmpInst::Predicate Pred,
5533 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005534 // Interpret a null as meaning no loop, where there is obviously no guard
5535 // (interprocedural conditions notwithstanding).
5536 if (!L) return false;
5537
Dan Gohman859b4822009-05-18 15:36:09 +00005538 // Starting at the loop predecessor, climb up the predecessor chain, as long
5539 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005540 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005541 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005542 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005543 Pair.first;
5544 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005545
5546 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005547 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005548 if (!LoopEntryPredicate ||
5549 LoopEntryPredicate->isUnconditional())
5550 continue;
5551
Dan Gohmanaf08a362010-08-10 23:46:30 +00005552 if (isImpliedCond(Pred, LHS, RHS,
5553 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005554 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005555 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005556 }
5557
Dan Gohman38372182008-08-12 20:17:31 +00005558 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005559}
5560
Dan Gohman0f4b2852009-07-21 23:03:19 +00005561/// isImpliedCond - Test whether the condition described by Pred, LHS,
5562/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005563bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005564 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005565 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005566 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005567 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005568 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005569 if (BO->getOpcode() == Instruction::And) {
5570 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005571 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5572 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005573 } else if (BO->getOpcode() == Instruction::Or) {
5574 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005575 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5576 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005577 }
5578 }
5579
Dan Gohmanaf08a362010-08-10 23:46:30 +00005580 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005581 if (!ICI) return false;
5582
Dan Gohman85b05a22009-07-13 21:35:55 +00005583 // Bail if the ICmp's operands' types are wider than the needed type
5584 // before attempting to call getSCEV on them. This avoids infinite
5585 // recursion, since the analysis of widening casts can require loop
5586 // exit condition information for overflow checking, which would
5587 // lead back here.
5588 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005589 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005590 return false;
5591
Dan Gohman0f4b2852009-07-21 23:03:19 +00005592 // Now that we found a conditional branch that dominates the loop, check to
5593 // see if it is the comparison we are looking for.
5594 ICmpInst::Predicate FoundPred;
5595 if (Inverse)
5596 FoundPred = ICI->getInversePredicate();
5597 else
5598 FoundPred = ICI->getPredicate();
5599
5600 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5601 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005602
5603 // Balance the types. The case where FoundLHS' type is wider than
5604 // LHS' type is checked for above.
5605 if (getTypeSizeInBits(LHS->getType()) >
5606 getTypeSizeInBits(FoundLHS->getType())) {
5607 if (CmpInst::isSigned(Pred)) {
5608 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5609 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5610 } else {
5611 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5612 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5613 }
5614 }
5615
Dan Gohman0f4b2852009-07-21 23:03:19 +00005616 // Canonicalize the query to match the way instcombine will have
5617 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005618 if (SimplifyICmpOperands(Pred, LHS, RHS))
5619 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005620 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005621 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5622 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005623 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005624
5625 // Check to see if we can make the LHS or RHS match.
5626 if (LHS == FoundRHS || RHS == FoundLHS) {
5627 if (isa<SCEVConstant>(RHS)) {
5628 std::swap(FoundLHS, FoundRHS);
5629 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5630 } else {
5631 std::swap(LHS, RHS);
5632 Pred = ICmpInst::getSwappedPredicate(Pred);
5633 }
5634 }
5635
5636 // Check whether the found predicate is the same as the desired predicate.
5637 if (FoundPred == Pred)
5638 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5639
5640 // Check whether swapping the found predicate makes it the same as the
5641 // desired predicate.
5642 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5643 if (isa<SCEVConstant>(RHS))
5644 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5645 else
5646 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5647 RHS, LHS, FoundLHS, FoundRHS);
5648 }
5649
5650 // Check whether the actual condition is beyond sufficient.
5651 if (FoundPred == ICmpInst::ICMP_EQ)
5652 if (ICmpInst::isTrueWhenEqual(Pred))
5653 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5654 return true;
5655 if (Pred == ICmpInst::ICMP_NE)
5656 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5657 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5658 return true;
5659
5660 // Otherwise assume the worst.
5661 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005662}
5663
Dan Gohman0f4b2852009-07-21 23:03:19 +00005664/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005665/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005666/// and FoundRHS is true.
5667bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5668 const SCEV *LHS, const SCEV *RHS,
5669 const SCEV *FoundLHS,
5670 const SCEV *FoundRHS) {
5671 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5672 FoundLHS, FoundRHS) ||
5673 // ~x < ~y --> x > y
5674 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5675 getNotSCEV(FoundRHS),
5676 getNotSCEV(FoundLHS));
5677}
5678
5679/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005680/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005681/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005682bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005683ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5684 const SCEV *LHS, const SCEV *RHS,
5685 const SCEV *FoundLHS,
5686 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005687 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005688 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5689 case ICmpInst::ICMP_EQ:
5690 case ICmpInst::ICMP_NE:
5691 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5692 return true;
5693 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005694 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005695 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005696 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5697 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005698 return true;
5699 break;
5700 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005701 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005702 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5703 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005704 return true;
5705 break;
5706 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005707 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005708 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5709 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005710 return true;
5711 break;
5712 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005713 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005714 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5715 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005716 return true;
5717 break;
5718 }
5719
5720 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005721}
5722
Dan Gohman51f53b72009-06-21 23:46:38 +00005723/// getBECount - Subtract the end and start values and divide by the step,
5724/// rounding up, to get the number of times the backedge is executed. Return
5725/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005726const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005727 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005728 const SCEV *Step,
5729 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005730 assert(!isKnownNegative(Step) &&
5731 "This code doesn't handle negative strides yet!");
5732
Dan Gohman51f53b72009-06-21 23:46:38 +00005733 const Type *Ty = Start->getType();
Andrew Tricke62289b2011-03-09 17:29:58 +00005734
5735 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5736 // here because SCEV may not be able to determine that the unsigned division
5737 // after rounding is zero.
5738 if (Start == End)
5739 return getConstant(Ty, 0);
5740
Dan Gohmandeff6212010-05-03 22:09:21 +00005741 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005742 const SCEV *Diff = getMinusSCEV(End, Start);
5743 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005744
5745 // Add an adjustment to the difference between End and Start so that
5746 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005747 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005748
Dan Gohman1f96e672009-09-17 18:05:20 +00005749 if (!NoWrap) {
5750 // Check Add for unsigned overflow.
5751 // TODO: More sophisticated things could be done here.
5752 const Type *WideTy = IntegerType::get(getContext(),
5753 getTypeSizeInBits(Ty) + 1);
5754 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5755 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5756 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5757 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5758 return getCouldNotCompute();
5759 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005760
5761 return getUDivExpr(Add, Step);
5762}
5763
Chris Lattnerdb25de42005-08-15 23:33:51 +00005764/// HowManyLessThans - Return the number of times a backedge containing the
5765/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005766/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005767ScalarEvolution::BackedgeTakenInfo
5768ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5769 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005770 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005771 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005772
Dan Gohman35738ac2009-05-04 22:30:44 +00005773 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005774 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005775 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005776
Dan Gohman1f96e672009-09-17 18:05:20 +00005777 // Check to see if we have a flag which makes analysis easy.
Andrew Trick3228cc22011-03-14 16:50:06 +00005778 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5779 AddRec->getNoWrapFlags(SCEV::FlagNUW);
Dan Gohman1f96e672009-09-17 18:05:20 +00005780
Chris Lattnerdb25de42005-08-15 23:33:51 +00005781 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005782 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005783 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005784
Dan Gohman52fddd32010-01-26 04:40:18 +00005785 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005786 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005787 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005788 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005789 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005790 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005791 // value and past the maximum value for its type in a single step.
5792 // Note that it's not sufficient to check NoWrap here, because even
5793 // though the value after a wrap is undefined, it's not undefined
5794 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005795 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005796 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005797 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005798 if (isSigned) {
5799 APInt Max = APInt::getSignedMaxValue(BitWidth);
5800 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5801 .slt(getSignedRange(RHS).getSignedMax()))
5802 return getCouldNotCompute();
5803 } else {
5804 APInt Max = APInt::getMaxValue(BitWidth);
5805 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5806 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5807 return getCouldNotCompute();
5808 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005809 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005810 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005811 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005812
Dan Gohmana1af7572009-04-30 20:47:05 +00005813 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5814 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5815 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005816 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005817
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005818 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005819 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005820
Dan Gohmana1af7572009-04-30 20:47:05 +00005821 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005822 const SCEV *MinStart = getConstant(isSigned ?
5823 getSignedRange(Start).getSignedMin() :
5824 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005825
Dan Gohmana1af7572009-04-30 20:47:05 +00005826 // If we know that the condition is true in order to enter the loop,
5827 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005828 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5829 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005830 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005831 if (!isLoopEntryGuardedByCond(L,
5832 isSigned ? ICmpInst::ICMP_SLT :
5833 ICmpInst::ICMP_ULT,
5834 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005835 End = isSigned ? getSMaxExpr(RHS, Start)
5836 : getUMaxExpr(RHS, Start);
5837
5838 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005839 const SCEV *MaxEnd = getConstant(isSigned ?
5840 getSignedRange(End).getSignedMax() :
5841 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005842
Dan Gohman52fddd32010-01-26 04:40:18 +00005843 // If MaxEnd is within a step of the maximum integer value in its type,
5844 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005845 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005846 // compute the correct value.
5847 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005848 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005849 MaxEnd = isSigned ?
5850 getSMinExpr(MaxEnd,
5851 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5852 StepMinusOne)) :
5853 getUMinExpr(MaxEnd,
5854 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5855 StepMinusOne));
5856
Dan Gohmana1af7572009-04-30 20:47:05 +00005857 // Finally, we subtract these two values and divide, rounding up, to get
5858 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005859 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005860
5861 // The maximum backedge count is similar, except using the minimum start
5862 // value and the maximum end value.
Andrew Tricke62289b2011-03-09 17:29:58 +00005863 // If we already have an exact constant BECount, use it instead.
5864 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
5865 : getBECount(MinStart, MaxEnd, Step, NoWrap);
5866
5867 // If the stride is nonconstant, and NoWrap == true, then
5868 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
5869 // exact BECount and invalid MaxBECount, which should be avoided to catch
5870 // more optimization opportunities.
5871 if (isa<SCEVCouldNotCompute>(MaxBECount))
5872 MaxBECount = BECount;
Dan Gohmana1af7572009-04-30 20:47:05 +00005873
5874 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005875 }
5876
Dan Gohman1c343752009-06-27 21:21:31 +00005877 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005878}
5879
Chris Lattner53e677a2004-04-02 20:23:17 +00005880/// getNumIterationsInRange - Return the number of iterations of this loop that
5881/// produce values in the specified constant range. Another way of looking at
5882/// this is that it returns the first iteration number where the value is not in
5883/// the condition, thus computing the exit count. If the iteration count can't
5884/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005885const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005886 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005887 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005888 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005889
5890 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005891 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005892 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005893 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005894 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00005895 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00005896 getNoWrapFlags(FlagNW));
Dan Gohman622ed672009-05-04 22:02:23 +00005897 if (const SCEVAddRecExpr *ShiftedAddRec =
5898 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005899 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005900 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005901 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005902 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005903 }
5904
5905 // The only time we can solve this is when we have all constant indices.
5906 // Otherwise, we cannot determine the overflow conditions.
5907 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5908 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005909 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005910
5911
5912 // Okay at this point we know that all elements of the chrec are constants and
5913 // that the start element is zero.
5914
5915 // First check to see if the range contains zero. If not, the first
5916 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005917 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005918 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005919 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005920
Chris Lattner53e677a2004-04-02 20:23:17 +00005921 if (isAffine()) {
5922 // If this is an affine expression then we have this situation:
5923 // Solve {0,+,A} in Range === Ax in Range
5924
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005925 // We know that zero is in the range. If A is positive then we know that
5926 // the upper value of the range must be the first possible exit value.
5927 // If A is negative then the lower of the range is the last possible loop
5928 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005929 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005930 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5931 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005932
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005933 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005934 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005935 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005936
5937 // Evaluate at the exit value. If we really did fall out of the valid
5938 // range, then we computed our trip count, otherwise wrap around or other
5939 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005940 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005941 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005942 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005943
5944 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005945 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005946 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005947 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005948 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005949 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005950 } else if (isQuadratic()) {
5951 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5952 // quadratic equation to solve it. To do this, we must frame our problem in
5953 // terms of figuring out when zero is crossed, instead of when
5954 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005955 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005956 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick3228cc22011-03-14 16:50:06 +00005957 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
5958 // getNoWrapFlags(FlagNW)
5959 FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00005960
5961 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005962 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005963 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005964 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5965 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005966 if (R1) {
5967 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005968 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005969 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005970 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005971 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005972 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005973
Chris Lattner53e677a2004-04-02 20:23:17 +00005974 // Make sure the root is not off by one. The returned iteration should
5975 // not be in the range, but the previous one should be. When solving
5976 // for "X*X < 5", for example, we should not return a root of 2.
5977 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005978 R1->getValue(),
5979 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005980 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005981 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005982 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005983 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005984
Dan Gohman246b2562007-10-22 18:31:58 +00005985 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005986 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005987 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005988 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005989 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005990
Chris Lattner53e677a2004-04-02 20:23:17 +00005991 // If R1 was not in the range, then it is a good return value. Make
5992 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005993 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005994 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005995 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005996 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005997 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005998 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005999 }
6000 }
6001 }
6002
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006003 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006004}
6005
6006
6007
6008//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00006009// SCEVCallbackVH Class Implementation
6010//===----------------------------------------------------------------------===//
6011
Dan Gohman1959b752009-05-19 19:22:47 +00006012void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006013 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00006014 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6015 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006016 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00006017 // this now dangles!
6018}
6019
Dan Gohman81f91212010-07-28 01:09:07 +00006020void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006021 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00006022
Dan Gohman35738ac2009-05-04 22:30:44 +00006023 // Forget all the expressions associated with users of the old value,
6024 // so that future queries will recompute the expressions using the new
6025 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00006026 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00006027 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00006028 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00006029 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6030 UI != UE; ++UI)
6031 Worklist.push_back(*UI);
6032 while (!Worklist.empty()) {
6033 User *U = Worklist.pop_back_val();
6034 // Deleting the Old value will cause this to dangle. Postpone
6035 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00006036 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00006037 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00006038 if (!Visited.insert(U))
6039 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00006040 if (PHINode *PN = dyn_cast<PHINode>(U))
6041 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006042 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00006043 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6044 UI != UE; ++UI)
6045 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00006046 }
Dan Gohman59846ac2010-07-28 00:28:25 +00006047 // Delete the Old value.
6048 if (PHINode *PN = dyn_cast<PHINode>(Old))
6049 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006050 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00006051 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00006052}
6053
Dan Gohman1959b752009-05-19 19:22:47 +00006054ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00006055 : CallbackVH(V), SE(se) {}
6056
6057//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00006058// ScalarEvolution Class Implementation
6059//===----------------------------------------------------------------------===//
6060
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006061ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00006062 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00006063 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006064}
6065
Chris Lattner53e677a2004-04-02 20:23:17 +00006066bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006067 this->F = &F;
6068 LI = &getAnalysis<LoopInfo>();
6069 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00006070 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00006071 return false;
6072}
6073
6074void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00006075 // Iterate through all the SCEVUnknown instances and call their
6076 // destructors, so that they release their references to their values.
6077 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6078 U->~SCEVUnknown();
6079 FirstUnknown = 0;
6080
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006081 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006082 BackedgeTakenCounts.clear();
6083 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00006084 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00006085 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006086 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00006087 UnsignedRanges.clear();
6088 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00006089 UniqueSCEVs.clear();
6090 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00006091}
6092
6093void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6094 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00006095 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00006096 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00006097}
6098
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006099bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006100 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00006101}
6102
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006103static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00006104 const Loop *L) {
6105 // Print all inner loops first
6106 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6107 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006108
Dan Gohman30733292010-01-09 18:17:45 +00006109 OS << "Loop ";
6110 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6111 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006112
Dan Gohman5d984912009-12-18 01:14:11 +00006113 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006114 L->getExitBlocks(ExitBlocks);
6115 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00006116 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006117
Dan Gohman46bdfb02009-02-24 18:55:53 +00006118 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6119 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00006120 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006121 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006122 }
6123
Dan Gohman30733292010-01-09 18:17:45 +00006124 OS << "\n"
6125 "Loop ";
6126 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6127 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00006128
6129 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6130 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6131 } else {
6132 OS << "Unpredictable max backedge-taken count. ";
6133 }
6134
6135 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006136}
6137
Dan Gohman5d984912009-12-18 01:14:11 +00006138void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006139 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006140 // out SCEV values of all instructions that are interesting. Doing
6141 // this potentially causes it to create new SCEV objects though,
6142 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00006143 // observable from outside the class though, so casting away the
6144 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00006145 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00006146
Dan Gohman30733292010-01-09 18:17:45 +00006147 OS << "Classifying expressions for: ";
6148 WriteAsOperand(OS, F, /*PrintType=*/false);
6149 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006150 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00006151 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00006152 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00006153 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006154 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006155 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006156
Dan Gohman0c689c52009-06-19 17:49:54 +00006157 const Loop *L = LI->getLoopFor((*I).getParent());
6158
Dan Gohman0bba49c2009-07-07 17:06:11 +00006159 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00006160 if (AtUse != SV) {
6161 OS << " --> ";
6162 AtUse->print(OS);
6163 }
6164
6165 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00006166 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006167 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00006168 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006169 OS << "<<Unknown>>";
6170 } else {
6171 OS << *ExitValue;
6172 }
6173 }
6174
Chris Lattner53e677a2004-04-02 20:23:17 +00006175 OS << "\n";
6176 }
6177
Dan Gohman30733292010-01-09 18:17:45 +00006178 OS << "Determining loop execution counts for: ";
6179 WriteAsOperand(OS, F, /*PrintType=*/false);
6180 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006181 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6182 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006183}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00006184
Dan Gohman714b5292010-11-17 23:21:44 +00006185ScalarEvolution::LoopDisposition
6186ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6187 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6188 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6189 Values.insert(std::make_pair(L, LoopVariant));
6190 if (!Pair.second)
6191 return Pair.first->second;
6192
6193 LoopDisposition D = computeLoopDisposition(S, L);
6194 return LoopDispositions[S][L] = D;
6195}
6196
6197ScalarEvolution::LoopDisposition
6198ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00006199 switch (S->getSCEVType()) {
6200 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00006201 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006202 case scTruncate:
6203 case scZeroExtend:
6204 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00006205 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006206 case scAddRecExpr: {
6207 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6208
Dan Gohman714b5292010-11-17 23:21:44 +00006209 // If L is the addrec's loop, it's computable.
6210 if (AR->getLoop() == L)
6211 return LoopComputable;
6212
Dan Gohman17ead4f2010-11-17 21:23:15 +00006213 // Add recurrences are never invariant in the function-body (null loop).
6214 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00006215 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006216
6217 // This recurrence is variant w.r.t. L if L contains AR's loop.
6218 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00006219 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006220
6221 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6222 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00006223 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006224
6225 // This recurrence is variant w.r.t. L if any of its operands
6226 // are variant.
6227 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6228 I != E; ++I)
6229 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00006230 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006231
6232 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00006233 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006234 }
6235 case scAddExpr:
6236 case scMulExpr:
6237 case scUMaxExpr:
6238 case scSMaxExpr: {
6239 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006240 bool HasVarying = false;
6241 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6242 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00006243 LoopDisposition D = getLoopDisposition(*I, L);
6244 if (D == LoopVariant)
6245 return LoopVariant;
6246 if (D == LoopComputable)
6247 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006248 }
Dan Gohman714b5292010-11-17 23:21:44 +00006249 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006250 }
6251 case scUDivExpr: {
6252 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00006253 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6254 if (LD == LoopVariant)
6255 return LoopVariant;
6256 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6257 if (RD == LoopVariant)
6258 return LoopVariant;
6259 return (LD == LoopInvariant && RD == LoopInvariant) ?
6260 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006261 }
6262 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00006263 // All non-instruction values are loop invariant. All instructions are loop
6264 // invariant if they are not contained in the specified loop.
6265 // Instructions are never considered invariant in the function body
6266 // (null loop) because they are defined within the "loop".
6267 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6268 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6269 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006270 case scCouldNotCompute:
6271 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00006272 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006273 default: break;
6274 }
6275 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006276 return LoopVariant;
6277}
6278
6279bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6280 return getLoopDisposition(S, L) == LoopInvariant;
6281}
6282
6283bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6284 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006285}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006286
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006287ScalarEvolution::BlockDisposition
6288ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6289 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6290 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6291 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6292 if (!Pair.second)
6293 return Pair.first->second;
6294
6295 BlockDisposition D = computeBlockDisposition(S, BB);
6296 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006297}
6298
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006299ScalarEvolution::BlockDisposition
6300ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006301 switch (S->getSCEVType()) {
6302 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006303 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006304 case scTruncate:
6305 case scZeroExtend:
6306 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006307 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006308 case scAddRecExpr: {
6309 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006310 // to test for proper dominance too, because the instruction which
6311 // produces the addrec's value is a PHI, and a PHI effectively properly
6312 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006313 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6314 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006315 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006316 }
6317 // FALL THROUGH into SCEVNAryExpr handling.
6318 case scAddExpr:
6319 case scMulExpr:
6320 case scUMaxExpr:
6321 case scSMaxExpr: {
6322 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006323 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006324 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006325 I != E; ++I) {
6326 BlockDisposition D = getBlockDisposition(*I, BB);
6327 if (D == DoesNotDominateBlock)
6328 return DoesNotDominateBlock;
6329 if (D == DominatesBlock)
6330 Proper = false;
6331 }
6332 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006333 }
6334 case scUDivExpr: {
6335 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006336 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6337 BlockDisposition LD = getBlockDisposition(LHS, BB);
6338 if (LD == DoesNotDominateBlock)
6339 return DoesNotDominateBlock;
6340 BlockDisposition RD = getBlockDisposition(RHS, BB);
6341 if (RD == DoesNotDominateBlock)
6342 return DoesNotDominateBlock;
6343 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6344 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006345 }
6346 case scUnknown:
6347 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006348 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6349 if (I->getParent() == BB)
6350 return DominatesBlock;
6351 if (DT->properlyDominates(I->getParent(), BB))
6352 return ProperlyDominatesBlock;
6353 return DoesNotDominateBlock;
6354 }
6355 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006356 case scCouldNotCompute:
6357 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006358 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006359 default: break;
6360 }
6361 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006362 return DoesNotDominateBlock;
6363}
6364
6365bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6366 return getBlockDisposition(S, BB) >= DominatesBlock;
6367}
6368
6369bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6370 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006371}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006372
6373bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6374 switch (S->getSCEVType()) {
6375 case scConstant:
6376 return false;
6377 case scTruncate:
6378 case scZeroExtend:
6379 case scSignExtend: {
6380 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6381 const SCEV *CastOp = Cast->getOperand();
6382 return Op == CastOp || hasOperand(CastOp, Op);
6383 }
6384 case scAddRecExpr:
6385 case scAddExpr:
6386 case scMulExpr:
6387 case scUMaxExpr:
6388 case scSMaxExpr: {
6389 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6390 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6391 I != E; ++I) {
6392 const SCEV *NAryOp = *I;
6393 if (NAryOp == Op || hasOperand(NAryOp, Op))
6394 return true;
6395 }
6396 return false;
6397 }
6398 case scUDivExpr: {
6399 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6400 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6401 return LHS == Op || hasOperand(LHS, Op) ||
6402 RHS == Op || hasOperand(RHS, Op);
6403 }
6404 case scUnknown:
6405 return false;
6406 case scCouldNotCompute:
6407 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6408 return false;
6409 default: break;
6410 }
6411 llvm_unreachable("Unknown SCEV kind!");
6412 return false;
6413}
Dan Gohman56a75682010-11-17 23:28:48 +00006414
6415void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6416 ValuesAtScopes.erase(S);
6417 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006418 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006419 UnsignedRanges.erase(S);
6420 SignedRanges.erase(S);
6421}