blob: ac00259c5bb5eb7524fa90464872cf5b5ef2ed70 [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);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000200 Type *AllocTy;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000201 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000210 Type *CTy;
Dan Gohman4ce32db2010-11-17 22:27:42 +0000211 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000231Type *SCEV::getType() const {
Dan Gohman4ce32db2010-11-17 22:27:42 +0000232 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 *
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000300ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
301 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana560fd22010-04-21 16:04:04 +0000302 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000306 unsigned SCEVTy, const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000310 const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000318 const SCEV *op, 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 const SCEV *op, 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000357bool SCEVUnknown::isSizeOf(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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000374bool SCEVUnknown::isAlignOf(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()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000380 Type *Ty =
Dan Gohman8db08df2010-02-02 01:38:49 +0000381 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000382 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman8db08df2010-02-02 01:38:49 +0000383 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000399bool SCEVUnknown::isOffsetOf(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()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman4f8eea82010-02-01 18:27:38 +0000408 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,
Nick Lewycky8cfb2f82011-09-06 06:39:54 +0000655 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
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000746 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000793 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,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000880 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) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000957 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
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001038// Get the limit of a recurrence such that incrementing by Step cannot cause
1039// signed overflow as long as the value of the recurrence within the loop does
1040// not exceed this limit before incrementing.
1041static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1042 ICmpInst::Predicate *Pred,
1043 ScalarEvolution *SE) {
1044 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1045 if (SE->isKnownPositive(Step)) {
1046 *Pred = ICmpInst::ICMP_SLT;
1047 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1048 SE->getSignedRange(Step).getSignedMax());
1049 }
1050 if (SE->isKnownNegative(Step)) {
1051 *Pred = ICmpInst::ICMP_SGT;
1052 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1053 SE->getSignedRange(Step).getSignedMin());
1054 }
1055 return 0;
1056}
1057
1058// The recurrence AR has been shown to have no signed wrap. Typically, if we can
1059// prove NSW for AR, then we can just as easily prove NSW for its preincrement
1060// or postincrement sibling. This allows normalizing a sign extended AddRec as
1061// such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1062// result, the expression "Step + sext(PreIncAR)" is congruent with
1063// "sext(PostIncAR)"
1064static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001065 Type *Ty,
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001066 ScalarEvolution *SE) {
1067 const Loop *L = AR->getLoop();
1068 const SCEV *Start = AR->getStart();
1069 const SCEV *Step = AR->getStepRecurrence(*SE);
1070
1071 // Check for a simple looking step prior to loop entry.
1072 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
Andrew Trickf63ae212011-09-28 17:02:54 +00001073 if (!SA)
1074 return 0;
1075
1076 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1077 // subtraction is expensive. For this purpose, perform a quick and dirty
1078 // difference, by checking for Step in the operand list.
1079 SmallVector<const SCEV *, 4> DiffOps;
1080 for (SCEVAddExpr::op_iterator I = SA->op_begin(), E = SA->op_end();
1081 I != E; ++I) {
1082 if (*I != Step)
1083 DiffOps.push_back(*I);
1084 }
1085 if (DiffOps.size() == SA->getNumOperands())
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001086 return 0;
1087
1088 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1089 // same three conditions that getSignExtendedExpr checks.
1090
1091 // 1. NSW flags on the step increment.
Andrew Trickf63ae212011-09-28 17:02:54 +00001092 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001093 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1094 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1095
Andrew Trickcf31f912011-06-01 19:14:56 +00001096 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001097 return PreStart;
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001098
1099 // 2. Direct overflow check on the step operation's expression.
1100 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001101 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001102 const SCEV *OperandExtendedStart =
1103 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1104 SE->getSignExtendExpr(Step, WideTy));
1105 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1106 // Cache knowledge of PreAR NSW.
1107 if (PreAR)
1108 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1109 // FIXME: this optimization needs a unit test
1110 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1111 return PreStart;
1112 }
1113
1114 // 3. Loop precondition.
1115 ICmpInst::Predicate Pred;
1116 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1117
Andrew Trickcf31f912011-06-01 19:14:56 +00001118 if (OverflowLimit &&
1119 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001120 return PreStart;
1121 }
1122 return 0;
1123}
1124
1125// Get the normalized sign-extended expression for this AddRec's Start.
1126static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001127 Type *Ty,
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001128 ScalarEvolution *SE) {
1129 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1130 if (!PreStart)
1131 return SE->getSignExtendExpr(AR->getStart(), Ty);
1132
1133 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1134 SE->getSignExtendExpr(PreStart, Ty));
1135}
1136
Dan Gohman0bba49c2009-07-07 17:06:11 +00001137const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001138 Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001139 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001140 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001141 assert(isSCEVable(Ty) &&
1142 "This is not a conversion to a SCEVable type!");
1143 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001144
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001145 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001146 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1147 return getConstant(
1148 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1149 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001150
Dan Gohman20900ca2009-04-22 16:20:48 +00001151 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001152 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001153 return getSignExtendExpr(SS->getOperand(), Ty);
1154
Nick Lewycky73f565e2011-01-19 15:56:12 +00001155 // sext(zext(x)) --> zext(x)
1156 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1157 return getZeroExtendExpr(SZ->getOperand(), Ty);
1158
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001159 // Before doing any expensive analysis, check to see if we've already
1160 // computed a SCEV for this Op and Ty.
1161 FoldingSetNodeID ID;
1162 ID.AddInteger(scSignExtend);
1163 ID.AddPointer(Op);
1164 ID.AddPointer(Ty);
1165 void *IP = 0;
1166 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1167
Nick Lewycky9b8d2c22011-01-22 22:06:21 +00001168 // If the input value is provably positive, build a zext instead.
1169 if (isKnownNonNegative(Op))
1170 return getZeroExtendExpr(Op, Ty);
1171
Nick Lewycky630d85a2011-01-23 06:20:19 +00001172 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1173 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1174 // It's possible the bits taken off by the truncate were all sign bits. If
1175 // so, we should be able to simplify this further.
1176 const SCEV *X = ST->getOperand();
1177 ConstantRange CR = getSignedRange(X);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001178 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1179 unsigned NewBits = getTypeSizeInBits(Ty);
1180 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewycky76167af2011-01-23 20:06:05 +00001181 CR.sextOrTrunc(NewBits)))
1182 return getTruncateOrSignExtend(X, Ty);
Nick Lewycky630d85a2011-01-23 06:20:19 +00001183 }
1184
Dan Gohman01ecca22009-04-27 20:16:15 +00001185 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001186 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001187 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001188 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001189 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001190 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001191 const SCEV *Start = AR->getStart();
1192 const SCEV *Step = AR->getStepRecurrence(*this);
1193 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1194 const Loop *L = AR->getLoop();
1195
Dan Gohmaneb490a72009-07-25 01:22:26 +00001196 // If we have special knowledge that this addrec won't overflow,
1197 // we don't need to do any further analysis.
Andrew Trick3228cc22011-03-14 16:50:06 +00001198 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001199 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohmaneb490a72009-07-25 01:22:26 +00001200 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001201 L, SCEV::FlagNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00001202
Dan Gohman01ecca22009-04-27 20:16:15 +00001203 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1204 // Note that this serves two purposes: It filters out loops that are
1205 // simply not analyzable, and it covers the case where this code is
1206 // being called from within backedge-taken count analysis, such that
1207 // attempting to ask for the backedge-taken count would likely result
1208 // in infinite recursion. In the later case, the analysis code will
1209 // cope with a conservative value, and it will take care to purge
1210 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001211 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001212 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001213 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001214 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001215
1216 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001217 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001218 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001219 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001220 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001221 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1222 if (MaxBECount == RecastedMaxBECount) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001223 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001224 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001225 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001226 const SCEV *Add = getAddExpr(Start, SMul);
1227 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001228 getAddExpr(getSignExtendExpr(Start, WideTy),
1229 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1230 getSignExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001231 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1232 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1233 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohmanac70cea2009-04-29 22:28:28 +00001234 // Return the expression with the addrec on the outside.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001235 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohmanac70cea2009-04-29 22:28:28 +00001236 getSignExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001237 L, AR->getNoWrapFlags());
1238 }
Dan Gohman850f7912009-07-16 17:34:36 +00001239 // Similar to above, only this time treat the step value as unsigned.
1240 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001241 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001242 Add = getAddExpr(Start, UMul);
1243 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001244 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001245 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1246 getZeroExtendExpr(Step, WideTy)));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001247 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1248 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1249 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman850f7912009-07-16 17:34:36 +00001250 // Return the expression with the addrec on the outside.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001251 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman850f7912009-07-16 17:34:36 +00001252 getZeroExtendExpr(Step, Ty),
Andrew Trickc343c1e2011-03-15 00:37:00 +00001253 L, AR->getNoWrapFlags());
1254 }
Dan Gohman85b05a22009-07-13 21:35:55 +00001255 }
1256
1257 // If the backedge is guarded by a comparison with the pre-inc value
1258 // the addrec is safe. Also, if the entry is guarded by a comparison
1259 // with the start value and the backedge is guarded by a comparison
1260 // with the post-inc value, the addrec is safe.
Andrew Trickb1ce4c02011-05-31 21:17:47 +00001261 ICmpInst::Predicate Pred;
1262 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1263 if (OverflowLimit &&
1264 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1265 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1266 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1267 OverflowLimit)))) {
1268 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1269 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1270 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1271 getSignExtendExpr(Step, Ty),
1272 L, AR->getNoWrapFlags());
Dan Gohman01ecca22009-04-27 20:16:15 +00001273 }
1274 }
1275 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001276
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001277 // The cast wasn't folded; create an explicit cast node.
1278 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001279 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001280 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1281 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001282 UniqueSCEVs.InsertNode(S, IP);
1283 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001284}
1285
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001286/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1287/// unspecified bits out to the given type.
1288///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001289const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001290 Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001291 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1292 "This is not an extending conversion!");
1293 assert(isSCEVable(Ty) &&
1294 "This is not a conversion to a SCEVable type!");
1295 Ty = getEffectiveSCEVType(Ty);
1296
1297 // Sign-extend negative constants.
1298 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1299 if (SC->getValue()->getValue().isNegative())
1300 return getSignExtendExpr(Op, Ty);
1301
1302 // Peel off a truncate cast.
1303 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001304 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001305 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1306 return getAnyExtendExpr(NewOp, Ty);
1307 return getTruncateOrNoop(NewOp, Ty);
1308 }
1309
1310 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001311 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001312 if (!isa<SCEVZeroExtendExpr>(ZExt))
1313 return ZExt;
1314
1315 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001316 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001317 if (!isa<SCEVSignExtendExpr>(SExt))
1318 return SExt;
1319
Dan Gohmana10756e2010-01-21 02:09:26 +00001320 // Force the cast to be folded into the operands of an addrec.
1321 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1322 SmallVector<const SCEV *, 4> Ops;
1323 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1324 I != E; ++I)
1325 Ops.push_back(getAnyExtendExpr(*I, Ty));
Andrew Trickc343c1e2011-03-15 00:37:00 +00001326 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00001327 }
1328
Dan Gohmanf53462d2010-07-15 20:02:11 +00001329 // As a special case, fold anyext(undef) to undef. We don't want to
1330 // know too much about SCEVUnknowns, but this special case is handy
1331 // and harmless.
1332 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1333 if (isa<UndefValue>(U->getValue()))
1334 return getSCEV(UndefValue::get(Ty));
1335
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001336 // If the expression is obviously signed, use the sext cast value.
1337 if (isa<SCEVSMaxExpr>(Op))
1338 return SExt;
1339
1340 // Absent any other information, use the zext cast value.
1341 return ZExt;
1342}
1343
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001344/// CollectAddOperandsWithScales - Process the given Ops list, which is
1345/// a list of operands to be added under the given scale, update the given
1346/// map. This is a helper function for getAddRecExpr. As an example of
1347/// what it does, given a sequence of operands that would form an add
1348/// expression like this:
1349///
1350/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1351///
1352/// where A and B are constants, update the map with these values:
1353///
1354/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1355///
1356/// and add 13 + A*B*29 to AccumulatedConstant.
1357/// This will allow getAddRecExpr to produce this:
1358///
1359/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1360///
1361/// This form often exposes folding opportunities that are hidden in
1362/// the original operand list.
1363///
1364/// Return true iff it appears that any interesting folding opportunities
1365/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1366/// the common case where no interesting opportunities are present, and
1367/// is also used as a check to avoid infinite recursion.
1368///
1369static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001370CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1371 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001372 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001373 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001374 const APInt &Scale,
1375 ScalarEvolution &SE) {
1376 bool Interesting = false;
1377
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001378 // Iterate over the add operands. They are sorted, with constants first.
1379 unsigned i = 0;
1380 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1381 ++i;
1382 // Pull a buried constant out to the outside.
1383 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1384 Interesting = true;
1385 AccumulatedConstant += Scale * C->getValue()->getValue();
1386 }
1387
1388 // Next comes everything else. We're especially interested in multiplies
1389 // here, but they're in the middle, so just visit the rest with one loop.
1390 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001391 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1392 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1393 APInt NewScale =
1394 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1395 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1396 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001397 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001398 Interesting |=
1399 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001400 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001401 NewScale, SE);
1402 } else {
1403 // A multiplication of a constant with some other value. Update
1404 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001405 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1406 const SCEV *Key = SE.getMulExpr(MulOps);
1407 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001408 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001409 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001410 NewOps.push_back(Pair.first->first);
1411 } else {
1412 Pair.first->second += NewScale;
1413 // The map already had an entry for this value, which may indicate
1414 // a folding opportunity.
1415 Interesting = true;
1416 }
1417 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001418 } else {
1419 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001420 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001421 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001422 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001423 NewOps.push_back(Pair.first->first);
1424 } else {
1425 Pair.first->second += Scale;
1426 // The map already had an entry for this value, which may indicate
1427 // a folding opportunity.
1428 Interesting = true;
1429 }
1430 }
1431 }
1432
1433 return Interesting;
1434}
1435
1436namespace {
1437 struct APIntCompare {
1438 bool operator()(const APInt &LHS, const APInt &RHS) const {
1439 return LHS.ult(RHS);
1440 }
1441 };
1442}
1443
Dan Gohman6c0866c2009-05-24 23:45:28 +00001444/// getAddExpr - Get a canonical add expression, or something simpler if
1445/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001446const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001447 SCEV::NoWrapFlags Flags) {
1448 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1449 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001450 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001451 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001452#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001453 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001454 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001455 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001456 "SCEVAddExpr operand types don't match!");
1457#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001458
Andrew Trick3228cc22011-03-14 16:50:06 +00001459 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001460 // And vice-versa.
1461 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1462 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1463 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001464 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001465 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1466 E = Ops.end(); I != E; ++I)
1467 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001468 All = false;
1469 break;
1470 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001471 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001472 }
1473
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001475 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476
1477 // If there are any constants, fold them together.
1478 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001479 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001481 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001482 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001483 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001484 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1485 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001486 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001487 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001488 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 }
1490
1491 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001492 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 Ops.erase(Ops.begin());
1494 --Idx;
1495 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001496
Dan Gohmanbca091d2010-04-12 23:08:18 +00001497 if (Ops.size() == 1) return Ops[0];
1498 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001499
Dan Gohman68ff7762010-08-27 21:39:59 +00001500 // Okay, check to see if the same value occurs in the operand list more than
1501 // once. If so, merge them together into an multiply expression. Since we
1502 // sorted the list, these values are required to be adjacent.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001503 Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001504 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001505 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001506 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001507 // Scan ahead to count how many equal operands there are.
1508 unsigned Count = 2;
1509 while (i+Count != e && Ops[i+Count] == Ops[i])
1510 ++Count;
1511 // Merge the values into a multiply.
1512 const SCEV *Scale = getConstant(Ty, Count);
1513 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1514 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001516 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001517 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001518 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001519 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001521 if (FoundMatch)
Andrew Trick3228cc22011-03-14 16:50:06 +00001522 return getAddExpr(Ops, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523
Dan Gohman728c7f32009-05-08 21:03:19 +00001524 // Check for truncates. If all the operands are truncated from the same
1525 // type, see if factoring out the truncate would permit the result to be
1526 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1527 // if the contents of the resulting outer trunc fold to something simple.
1528 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1529 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001530 Type *DstType = Trunc->getType();
1531 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001532 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001533 bool Ok = true;
1534 // Check all the operands to see if they can be represented in the
1535 // source type of the truncate.
1536 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1537 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1538 if (T->getOperand()->getType() != SrcType) {
1539 Ok = false;
1540 break;
1541 }
1542 LargeOps.push_back(T->getOperand());
1543 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001544 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001545 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001546 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001547 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1548 if (const SCEVTruncateExpr *T =
1549 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1550 if (T->getOperand()->getType() != SrcType) {
1551 Ok = false;
1552 break;
1553 }
1554 LargeMulOps.push_back(T->getOperand());
1555 } else if (const SCEVConstant *C =
1556 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001557 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001558 } else {
1559 Ok = false;
1560 break;
1561 }
1562 }
1563 if (Ok)
1564 LargeOps.push_back(getMulExpr(LargeMulOps));
1565 } else {
1566 Ok = false;
1567 break;
1568 }
1569 }
1570 if (Ok) {
1571 // Evaluate the expression in the larger type.
Andrew Trick3228cc22011-03-14 16:50:06 +00001572 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman728c7f32009-05-08 21:03:19 +00001573 // If it folds to something simple, use it. Otherwise, don't.
1574 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1575 return getTruncateExpr(Fold, DstType);
1576 }
1577 }
1578
1579 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001580 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1581 ++Idx;
1582
1583 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001584 if (Idx < Ops.size()) {
1585 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001586 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 // If we have an add, expand the add operands onto the end of the operands
1588 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001590 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001591 DeletedAdd = true;
1592 }
1593
1594 // If we deleted at least one add, we added operands to the end of the list,
1595 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001596 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001598 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001599 }
1600
1601 // Skip over the add expression until we get to a multiply.
1602 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1603 ++Idx;
1604
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001605 // Check to see if there are any folding opportunities present with
1606 // operands multiplied by constant values.
1607 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1608 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001609 DenseMap<const SCEV *, APInt> M;
1610 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001611 APInt AccumulatedConstant(BitWidth, 0);
1612 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001613 Ops.data(), Ops.size(),
1614 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001615 // Some interesting folding opportunity is present, so its worthwhile to
1616 // re-generate the operands list. Group the operands by constant scale,
1617 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001618 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001619 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001620 E = NewOps.end(); I != E; ++I)
1621 MulOpLists[M.find(*I)->second].push_back(*I);
1622 // Re-generate the operands list.
1623 Ops.clear();
1624 if (AccumulatedConstant != 0)
1625 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001626 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1627 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001628 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001629 Ops.push_back(getMulExpr(getConstant(I->first),
1630 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001631 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001632 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001633 if (Ops.size() == 1)
1634 return Ops[0];
1635 return getAddExpr(Ops);
1636 }
1637 }
1638
Chris Lattner53e677a2004-04-02 20:23:17 +00001639 // If we are adding something to a multiply expression, make sure the
1640 // something is not already an operand of the multiply. If so, merge it into
1641 // the multiply.
1642 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001643 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001644 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001645 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001646 if (isa<SCEVConstant>(MulOpSCEV))
1647 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001648 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001649 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001651 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001652 if (Mul->getNumOperands() != 2) {
1653 // If the multiply has more than two operands, we must get the
1654 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001655 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1656 Mul->op_begin()+MulOp);
1657 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001658 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001659 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001660 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001661 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001662 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001663 if (Ops.size() == 2) return OuterMul;
1664 if (AddOp < Idx) {
1665 Ops.erase(Ops.begin()+AddOp);
1666 Ops.erase(Ops.begin()+Idx-1);
1667 } else {
1668 Ops.erase(Ops.begin()+Idx);
1669 Ops.erase(Ops.begin()+AddOp-1);
1670 }
1671 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001672 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001674
Chris Lattner53e677a2004-04-02 20:23:17 +00001675 // Check this multiply against other multiplies being added together.
1676 for (unsigned OtherMulIdx = Idx+1;
1677 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1678 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001679 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 // If MulOp occurs in OtherMul, we can fold the two multiplies
1681 // together.
1682 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1683 OMulOp != e; ++OMulOp)
1684 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1685 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001686 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001688 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001689 Mul->op_begin()+MulOp);
1690 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001691 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001692 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001693 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001694 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001695 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001696 OtherMul->op_begin()+OMulOp);
1697 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001698 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001699 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001700 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1701 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001702 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001703 Ops.erase(Ops.begin()+Idx);
1704 Ops.erase(Ops.begin()+OtherMulIdx-1);
1705 Ops.push_back(OuterMul);
1706 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 }
1708 }
1709 }
1710 }
1711
1712 // If there are any add recurrences in the operands list, see if any other
1713 // added values are loop invariant. If so, we can fold them into the
1714 // recurrence.
1715 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1716 ++Idx;
1717
1718 // Scan over all recurrences, trying to fold loop invariants into them.
1719 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1720 // Scan all of the other operands to this add and add them to the vector if
1721 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001722 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001723 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001724 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001725 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001726 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001727 LIOps.push_back(Ops[i]);
1728 Ops.erase(Ops.begin()+i);
1729 --i; --e;
1730 }
1731
1732 // If we found some loop invariants, fold them into the recurrence.
1733 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001734 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001735 LIOps.push_back(AddRec->getStart());
1736
Dan Gohman0bba49c2009-07-07 17:06:11 +00001737 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001738 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001739 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001740
Dan Gohmanb9f96512010-06-30 07:16:37 +00001741 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher87376832011-01-11 09:02:09 +00001742 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001743 // Always propagate NW.
1744 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick3228cc22011-03-14 16:50:06 +00001745 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman59de33e2009-12-18 18:45:31 +00001746
Chris Lattner53e677a2004-04-02 20:23:17 +00001747 // If all of the other operands were loop invariant, we are done.
1748 if (Ops.size() == 1) return NewRec;
1749
Nick Lewycky980e9f32011-09-06 05:08:09 +00001750 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 for (unsigned i = 0;; ++i)
1752 if (Ops[i] == AddRec) {
1753 Ops[i] = NewRec;
1754 break;
1755 }
Dan Gohman246b2562007-10-22 18:31:58 +00001756 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001757 }
1758
1759 // Okay, if there weren't any loop invariants to be folded, check to see if
1760 // there are multiple AddRec's with the same loop induction variable being
1761 // added together. If so, we can fold them.
1762 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001763 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1764 ++OtherIdx)
1765 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1766 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1767 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1768 AddRec->op_end());
1769 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1770 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001771 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001772 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001773 if (OtherAddRec->getLoop() == AddRecLoop) {
1774 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1775 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001776 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001777 AddRecOps.append(OtherAddRec->op_begin()+i,
1778 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001779 break;
1780 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001781 AddRecOps[i] = getAddExpr(AddRecOps[i],
1782 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001783 }
1784 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001785 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001786 // Step size has changed, so we cannot guarantee no self-wraparound.
1787 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohman32527152010-08-27 20:45:56 +00001788 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001789 }
1790
1791 // Otherwise couldn't fold anything into this recurrence. Move onto the
1792 // next one.
1793 }
1794
1795 // Okay, it looks like we really DO need an add expr. Check to see if we
1796 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001797 FoldingSetNodeID ID;
1798 ID.AddInteger(scAddExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001799 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1800 ID.AddPointer(Ops[i]);
1801 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001802 SCEVAddExpr *S =
1803 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1804 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001805 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1806 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001807 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1808 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001809 UniqueSCEVs.InsertNode(S, IP);
1810 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001811 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00001812 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001813}
1814
Nick Lewyckye97728e2011-10-04 06:51:26 +00001815static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
1816 uint64_t k = i*j;
1817 if (j > 1 && k / j != i) Overflow = true;
1818 return k;
1819}
1820
1821/// Compute the result of "n choose k", the binomial coefficient. If an
1822/// intermediate computation overflows, Overflow will be set and the return will
1823/// be garbage. Overflow is not cleared on absense of overflow.
1824static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
1825 // We use the multiplicative formula:
1826 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
1827 // At each iteration, we take the n-th term of the numeral and divide by the
1828 // (k-n)th term of the denominator. This division will always produce an
1829 // integral result, and helps reduce the chance of overflow in the
1830 // intermediate computations. However, we can still overflow even when the
1831 // final result would fit.
1832
1833 if (n == 0 || n == k) return 1;
1834 if (k > n) return 0;
1835
1836 if (k > n/2)
1837 k = n-k;
1838
1839 uint64_t r = 1;
1840 for (uint64_t i = 1; i <= k; ++i) {
1841 r = umul_ov(r, n-(i-1), Overflow);
1842 r /= i;
1843 }
1844 return r;
1845}
1846
Dan Gohman6c0866c2009-05-24 23:45:28 +00001847/// getMulExpr - Get a canonical multiply expression, or something simpler if
1848/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001849const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick3228cc22011-03-14 16:50:06 +00001850 SCEV::NoWrapFlags Flags) {
1851 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1852 "only nuw or nsw allowed");
Chris Lattner53e677a2004-04-02 20:23:17 +00001853 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001854 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001855#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001856 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001857 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001858 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001859 "SCEVMulExpr operand types don't match!");
1860#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001861
Andrew Trick3228cc22011-03-14 16:50:06 +00001862 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00001863 // And vice-versa.
1864 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1865 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1866 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001867 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001868 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1869 E = Ops.end(); I != E; ++I)
1870 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001871 All = false;
1872 break;
1873 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00001874 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00001875 }
1876
Chris Lattner53e677a2004-04-02 20:23:17 +00001877 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001878 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001879
1880 // If there are any constants, fold them together.
1881 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001882 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001883
1884 // C1*(C2+V) -> C1*C2 + C1*V
1885 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001886 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001887 if (Add->getNumOperands() == 2 &&
1888 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001889 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1890 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001891
Chris Lattner53e677a2004-04-02 20:23:17 +00001892 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001893 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001894 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001895 ConstantInt *Fold = ConstantInt::get(getContext(),
1896 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001897 RHSC->getValue()->getValue());
1898 Ops[0] = getConstant(Fold);
1899 Ops.erase(Ops.begin()+1); // Erase the folded element
1900 if (Ops.size() == 1) return Ops[0];
1901 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001902 }
1903
1904 // If we are left with a constant one being multiplied, strip it off.
1905 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1906 Ops.erase(Ops.begin());
1907 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001908 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001909 // If we have a multiply of zero, it will always be zero.
1910 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001911 } else if (Ops[0]->isAllOnesValue()) {
1912 // If we have a mul by -1 of an add, try distributing the -1 among the
1913 // add operands.
Andrew Trick3228cc22011-03-14 16:50:06 +00001914 if (Ops.size() == 2) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001915 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1916 SmallVector<const SCEV *, 4> NewOps;
1917 bool AnyFolded = false;
Andrew Trick3228cc22011-03-14 16:50:06 +00001918 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1919 E = Add->op_end(); I != E; ++I) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001920 const SCEV *Mul = getMulExpr(Ops[0], *I);
1921 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1922 NewOps.push_back(Mul);
1923 }
1924 if (AnyFolded)
1925 return getAddExpr(NewOps);
1926 }
Andrew Tricka053b212011-03-14 17:38:54 +00001927 else if (const SCEVAddRecExpr *
1928 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1929 // Negation preserves a recurrence's no self-wrap property.
1930 SmallVector<const SCEV *, 4> Operands;
1931 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1932 E = AddRec->op_end(); I != E; ++I) {
1933 Operands.push_back(getMulExpr(Ops[0], *I));
1934 }
1935 return getAddRecExpr(Operands, AddRec->getLoop(),
1936 AddRec->getNoWrapFlags(SCEV::FlagNW));
1937 }
Andrew Trick3228cc22011-03-14 16:50:06 +00001938 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001939 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001940
1941 if (Ops.size() == 1)
1942 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001943 }
1944
1945 // Skip over the add expression until we get to a multiply.
1946 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1947 ++Idx;
1948
Chris Lattner53e677a2004-04-02 20:23:17 +00001949 // If there are mul operands inline them all into this expression.
1950 if (Idx < Ops.size()) {
1951 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001952 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001953 // If we have an mul, expand the mul operands onto the end of the operands
1954 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001956 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001957 DeletedMul = true;
1958 }
1959
1960 // If we deleted at least one mul, we added operands to the end of the list,
1961 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001962 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001963 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001964 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001965 }
1966
1967 // If there are any add recurrences in the operands list, see if any other
1968 // added values are loop invariant. If so, we can fold them into the
1969 // recurrence.
1970 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1971 ++Idx;
1972
1973 // Scan over all recurrences, trying to fold loop invariants into them.
1974 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1975 // Scan all of the other operands to this mul and add them to the vector if
1976 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001977 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001978 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001979 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001980 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001981 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001982 LIOps.push_back(Ops[i]);
1983 Ops.erase(Ops.begin()+i);
1984 --i; --e;
1985 }
1986
1987 // If we found some loop invariants, fold them into the recurrence.
1988 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001989 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001990 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001991 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001992 const SCEV *Scale = getMulExpr(LIOps);
1993 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1994 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001995
Dan Gohmanb9f96512010-06-30 07:16:37 +00001996 // Build the new addrec. Propagate the NUW and NSW flags if both the
1997 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick3228cc22011-03-14 16:50:06 +00001998 //
1999 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner7a2bdde2011-04-15 05:18:47 +00002000 // will be inferred if either NUW or NSW is true.
Andrew Trick3228cc22011-03-14 16:50:06 +00002001 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2002 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002003
2004 // If all of the other operands were loop invariant, we are done.
2005 if (Ops.size() == 1) return NewRec;
2006
Nick Lewycky980e9f32011-09-06 05:08:09 +00002007 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattner53e677a2004-04-02 20:23:17 +00002008 for (unsigned i = 0;; ++i)
2009 if (Ops[i] == AddRec) {
2010 Ops[i] = NewRec;
2011 break;
2012 }
Dan Gohman246b2562007-10-22 18:31:58 +00002013 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002014 }
2015
2016 // Okay, if there weren't any loop invariants to be folded, check to see if
2017 // there are multiple AddRec's with the same loop induction variable being
2018 // multiplied together. If so, we can fold them.
2019 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00002020 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckyc103a082011-09-06 21:42:18 +00002021 ++OtherIdx) {
Dan Gohman6a0c1252010-08-31 22:52:12 +00002022 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
Nick Lewyckye97728e2011-10-04 06:51:26 +00002023 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2024 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2025 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2026 // ]]],+,...up to x=2n}.
2027 // Note that the arguments to choose() are always integers with values
2028 // known at compile time, never SCEV objects.
Nick Lewycky28682ae2011-09-06 05:33:18 +00002029 //
Nick Lewyckye97728e2011-10-04 06:51:26 +00002030 // The implementation avoids pointless extra computations when the two
2031 // addrec's are of different length (mathematically, it's equivalent to
2032 // an infinite stream of zeros on the right).
2033 bool OpsModified = false;
Dan Gohman6a0c1252010-08-31 22:52:12 +00002034 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2035 ++OtherIdx)
2036 if (const SCEVAddRecExpr *OtherAddRec =
2037 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2038 if (OtherAddRec->getLoop() == AddRecLoop) {
Nick Lewyckye97728e2011-10-04 06:51:26 +00002039 bool Overflow = false;
2040 Type *Ty = AddRec->getType();
2041 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2042 SmallVector<const SCEV*, 7> AddRecOps;
2043 for (int x = 0, xe = AddRec->getNumOperands() +
2044 OtherAddRec->getNumOperands() - 1;
2045 x != xe && !Overflow; ++x) {
2046 const SCEV *Term = getConstant(Ty, 0);
2047 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2048 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2049 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2050 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2051 z < ze && !Overflow; ++z) {
2052 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2053 uint64_t Coeff;
2054 if (LargerThan64Bits)
2055 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2056 else
2057 Coeff = Coeff1*Coeff2;
2058 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2059 const SCEV *Term1 = AddRec->getOperand(y-z);
2060 const SCEV *Term2 = OtherAddRec->getOperand(z);
2061 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2062 }
2063 }
2064 AddRecOps.push_back(Term);
2065 }
2066 if (!Overflow) {
Nick Lewyckyc103a082011-09-06 21:42:18 +00002067 const SCEV *NewAddRec = getAddRecExpr(AddRecOps,
2068 AddRec->getLoop(),
2069 SCEV::FlagAnyWrap);
2070 if (Ops.size() == 2) return NewAddRec;
2071 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
2072 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Nick Lewyckye97728e2011-10-04 06:51:26 +00002073 OpsModified = true;
Nick Lewyckyc103a082011-09-06 21:42:18 +00002074 }
Dan Gohman6a0c1252010-08-31 22:52:12 +00002075 }
Nick Lewyckye97728e2011-10-04 06:51:26 +00002076 if (OpsModified)
Nick Lewyckyc103a082011-09-06 21:42:18 +00002077 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 }
Nick Lewyckyc103a082011-09-06 21:42:18 +00002079 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002080
2081 // Otherwise couldn't fold anything into this recurrence. Move onto the
2082 // next one.
2083 }
2084
2085 // Okay, it looks like we really DO need an mul expr. Check to see if we
2086 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002087 FoldingSetNodeID ID;
2088 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002089 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2090 ID.AddPointer(Ops[i]);
2091 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002092 SCEVMulExpr *S =
2093 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2094 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002095 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2096 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002097 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2098 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00002099 UniqueSCEVs.InsertNode(S, IP);
2100 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002101 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002102 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002103}
2104
Andreas Bolka8a11c982009-08-07 22:55:26 +00002105/// getUDivExpr - Get a canonical unsigned division expression, or something
2106/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00002107const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2108 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00002109 assert(getEffectiveSCEVType(LHS->getType()) ==
2110 getEffectiveSCEVType(RHS->getType()) &&
2111 "SCEVUDivExpr operand types don't match!");
2112
Dan Gohman622ed672009-05-04 22:02:23 +00002113 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002114 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00002115 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002116 // If the denominator is zero, the result of the udiv is undefined. Don't
2117 // try to analyze it, because the resolution chosen here may differ from
2118 // the resolution chosen in other parts of the compiler.
2119 if (!RHSC->getValue()->isZero()) {
2120 // Determine if the division can be folded into the operands of
2121 // its operands.
2122 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002123 Type *Ty = LHS->getType();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002124 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00002125 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002126 // For non-power-of-two values, effectively round the value up to the
2127 // nearest power of two.
2128 if (!RHSC->getValue()->getValue().isPowerOf2())
2129 ++MaxShiftAmt;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002130 IntegerType *ExtTy =
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002131 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002132 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2133 if (const SCEVConstant *Step =
Andrew Trick06988bc2011-08-06 07:00:37 +00002134 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2135 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2136 const APInt &StepInt = Step->getValue()->getValue();
2137 const APInt &DivInt = RHSC->getValue()->getValue();
2138 if (!StepInt.urem(DivInt) &&
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002139 getZeroExtendExpr(AR, ExtTy) ==
2140 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2141 getZeroExtendExpr(Step, ExtTy),
Andrew Trick3228cc22011-03-14 16:50:06 +00002142 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002143 SmallVector<const SCEV *, 4> Operands;
2144 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2145 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick3228cc22011-03-14 16:50:06 +00002146 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00002147 SCEV::FlagNW);
Dan Gohman185cf032009-05-08 20:18:49 +00002148 }
Andrew Trick06988bc2011-08-06 07:00:37 +00002149 /// Get a canonical UDivExpr for a recurrence.
2150 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2151 // We can currently only fold X%N if X is constant.
2152 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2153 if (StartC && !DivInt.urem(StepInt) &&
2154 getZeroExtendExpr(AR, ExtTy) ==
2155 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2156 getZeroExtendExpr(Step, ExtTy),
2157 AR->getLoop(), SCEV::FlagAnyWrap)) {
2158 const APInt &StartInt = StartC->getValue()->getValue();
2159 const APInt &StartRem = StartInt.urem(StepInt);
2160 if (StartRem != 0)
2161 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2162 AR->getLoop(), SCEV::FlagNW);
2163 }
2164 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002165 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2166 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2167 SmallVector<const SCEV *, 4> Operands;
2168 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2169 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2170 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2171 // Find an operand that's safely divisible.
2172 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2173 const SCEV *Op = M->getOperand(i);
2174 const SCEV *Div = getUDivExpr(Op, RHSC);
2175 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2176 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2177 M->op_end());
2178 Operands[i] = Div;
2179 return getMulExpr(Operands);
2180 }
2181 }
Dan Gohman185cf032009-05-08 20:18:49 +00002182 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002183 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Andrew Tricka2a16202011-04-27 18:17:36 +00002184 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002185 SmallVector<const SCEV *, 4> Operands;
2186 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2187 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2188 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2189 Operands.clear();
2190 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2191 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2192 if (isa<SCEVUDivExpr>(Op) ||
2193 getMulExpr(Op, RHS) != A->getOperand(i))
2194 break;
2195 Operands.push_back(Op);
2196 }
2197 if (Operands.size() == A->getNumOperands())
2198 return getAddExpr(Operands);
2199 }
2200 }
Dan Gohman185cf032009-05-08 20:18:49 +00002201
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00002202 // Fold if both operands are constant.
2203 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2204 Constant *LHSCV = LHSC->getValue();
2205 Constant *RHSCV = RHSC->getValue();
2206 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2207 RHSCV)));
2208 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 }
2210 }
2211
Dan Gohman1c343752009-06-27 21:21:31 +00002212 FoldingSetNodeID ID;
2213 ID.AddInteger(scUDivExpr);
2214 ID.AddPointer(LHS);
2215 ID.AddPointer(RHS);
2216 void *IP = 0;
2217 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00002218 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2219 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00002220 UniqueSCEVs.InsertNode(S, IP);
2221 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002222}
2223
2224
Dan Gohman6c0866c2009-05-24 23:45:28 +00002225/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2226/// Simplify the expression as much as possible.
Andrew Trick3228cc22011-03-14 16:50:06 +00002227const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2228 const Loop *L,
2229 SCEV::NoWrapFlags Flags) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002230 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00002231 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00002232 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00002233 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002234 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickc343c1e2011-03-15 00:37:00 +00002235 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattner53e677a2004-04-02 20:23:17 +00002236 }
2237
2238 Operands.push_back(Step);
Andrew Trick3228cc22011-03-14 16:50:06 +00002239 return getAddRecExpr(Operands, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00002240}
2241
Dan Gohman6c0866c2009-05-24 23:45:28 +00002242/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2243/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002244const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002245ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick3228cc22011-03-14 16:50:06 +00002246 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002247 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002248#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002249 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002250 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002251 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002252 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00002253 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002254 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00002255 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00002256#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002257
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002258 if (Operands.back()->isZero()) {
2259 Operands.pop_back();
Andrew Trick3228cc22011-03-14 16:50:06 +00002260 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002261 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002262
Dan Gohmanbc028532010-02-19 18:49:22 +00002263 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2264 // use that information to infer NUW and NSW flags. However, computing a
2265 // BE count requires calling getAddRecExpr, so we may not yet have a
2266 // meaningful BE count at this point (and if we don't, we'd be stuck
2267 // with a SCEVCouldNotCompute as the cached BE count).
2268
Andrew Trick3228cc22011-03-14 16:50:06 +00002269 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002270 // And vice-versa.
2271 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2272 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2273 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002274 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00002275 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2276 E = Operands.end(); I != E; ++I)
2277 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002278 All = false;
2279 break;
2280 }
Andrew Trickc343c1e2011-03-15 00:37:00 +00002281 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohmana10756e2010-01-21 02:09:26 +00002282 }
2283
Dan Gohmand9cc7492008-08-08 18:33:12 +00002284 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002285 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002286 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00002287 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00002288 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00002289 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00002290 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002291 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002292 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002293 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002294 // AddRecs require their operands be loop-invariant with respect to their
2295 // loops. Don't perform this transformation if it would break this
2296 // requirement.
2297 bool AllInvariant = true;
2298 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002299 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002300 AllInvariant = false;
2301 break;
2302 }
2303 if (AllInvariant) {
Andrew Trick3228cc22011-03-14 16:50:06 +00002304 // Create a recurrence for the outer loop with the same step size.
2305 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002306 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2307 // inner recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002308 SCEV::NoWrapFlags OuterFlags =
2309 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick3228cc22011-03-14 16:50:06 +00002310
2311 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohman9a80b452009-06-26 22:36:20 +00002312 AllInvariant = true;
2313 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002314 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002315 AllInvariant = false;
2316 break;
2317 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002318 if (AllInvariant) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002319 // Ok, both add recurrences are valid after the transformation.
Andrew Trick3228cc22011-03-14 16:50:06 +00002320 //
Andrew Trick3228cc22011-03-14 16:50:06 +00002321 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2322 // the outer recurrence has the same property.
Andrew Trickc343c1e2011-03-15 00:37:00 +00002323 SCEV::NoWrapFlags InnerFlags =
2324 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick3228cc22011-03-14 16:50:06 +00002325 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2326 }
Dan Gohman9a80b452009-06-26 22:36:20 +00002327 }
2328 // Reset Operands to its original state.
2329 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002330 }
2331 }
2332
Dan Gohman67847532010-01-19 22:27:22 +00002333 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2334 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002335 FoldingSetNodeID ID;
2336 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002337 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2338 ID.AddPointer(Operands[i]);
2339 ID.AddPointer(L);
2340 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002341 SCEVAddRecExpr *S =
2342 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2343 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002344 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2345 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002346 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2347 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002348 UniqueSCEVs.InsertNode(S, IP);
2349 }
Andrew Trick3228cc22011-03-14 16:50:06 +00002350 S->setNoWrapFlags(Flags);
Dan Gohman1c343752009-06-27 21:21:31 +00002351 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002352}
2353
Dan Gohman9311ef62009-06-24 14:49:00 +00002354const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2355 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002356 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002357 Ops.push_back(LHS);
2358 Ops.push_back(RHS);
2359 return getSMaxExpr(Ops);
2360}
2361
Dan Gohman0bba49c2009-07-07 17:06:11 +00002362const SCEV *
2363ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002364 assert(!Ops.empty() && "Cannot get empty smax!");
2365 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002366#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002367 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002368 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002369 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002370 "SCEVSMaxExpr operand types don't match!");
2371#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002372
2373 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002374 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002375
2376 // If there are any constants, fold them together.
2377 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002378 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002379 ++Idx;
2380 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002381 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002382 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002383 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002384 APIntOps::smax(LHSC->getValue()->getValue(),
2385 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002386 Ops[0] = getConstant(Fold);
2387 Ops.erase(Ops.begin()+1); // Erase the folded element
2388 if (Ops.size() == 1) return Ops[0];
2389 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002390 }
2391
Dan Gohmane5aceed2009-06-24 14:46:22 +00002392 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002393 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2394 Ops.erase(Ops.begin());
2395 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002396 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2397 // If we have an smax with a constant maximum-int, it will always be
2398 // maximum-int.
2399 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002400 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002401
Dan Gohman3ab13122010-04-13 16:49:23 +00002402 if (Ops.size() == 1) return Ops[0];
2403 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002404
2405 // Find the first SMax
2406 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2407 ++Idx;
2408
2409 // Check to see if one of the operands is an SMax. If so, expand its operands
2410 // onto our operand list, and recurse to simplify.
2411 if (Idx < Ops.size()) {
2412 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002413 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002414 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002415 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002416 DeletedSMax = true;
2417 }
2418
2419 if (DeletedSMax)
2420 return getSMaxExpr(Ops);
2421 }
2422
2423 // Okay, check to see if the same value occurs in the operand list twice. If
2424 // so, delete one. Since we sorted the list, these values are required to
2425 // be adjacent.
2426 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002427 // X smax Y smax Y --> X smax Y
2428 // X smax Y --> X, if X is always greater than Y
2429 if (Ops[i] == Ops[i+1] ||
2430 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2431 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2432 --i; --e;
2433 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002434 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2435 --i; --e;
2436 }
2437
2438 if (Ops.size() == 1) return Ops[0];
2439
2440 assert(!Ops.empty() && "Reduced smax down to nothing!");
2441
Nick Lewycky3e630762008-02-20 06:48:22 +00002442 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002443 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002444 FoldingSetNodeID ID;
2445 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002446 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2447 ID.AddPointer(Ops[i]);
2448 void *IP = 0;
2449 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002450 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2451 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002452 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2453 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002454 UniqueSCEVs.InsertNode(S, IP);
2455 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002456}
2457
Dan Gohman9311ef62009-06-24 14:49:00 +00002458const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2459 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002460 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002461 Ops.push_back(LHS);
2462 Ops.push_back(RHS);
2463 return getUMaxExpr(Ops);
2464}
2465
Dan Gohman0bba49c2009-07-07 17:06:11 +00002466const SCEV *
2467ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002468 assert(!Ops.empty() && "Cannot get empty umax!");
2469 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002470#ifndef NDEBUG
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002471 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002472 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002473 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002474 "SCEVUMaxExpr operand types don't match!");
2475#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002476
2477 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002478 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002479
2480 // If there are any constants, fold them together.
2481 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002482 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002483 ++Idx;
2484 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002485 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002486 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002487 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002488 APIntOps::umax(LHSC->getValue()->getValue(),
2489 RHSC->getValue()->getValue()));
2490 Ops[0] = getConstant(Fold);
2491 Ops.erase(Ops.begin()+1); // Erase the folded element
2492 if (Ops.size() == 1) return Ops[0];
2493 LHSC = cast<SCEVConstant>(Ops[0]);
2494 }
2495
Dan Gohmane5aceed2009-06-24 14:46:22 +00002496 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002497 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2498 Ops.erase(Ops.begin());
2499 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002500 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2501 // If we have an umax with a constant maximum-int, it will always be
2502 // maximum-int.
2503 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002504 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002505
Dan Gohman3ab13122010-04-13 16:49:23 +00002506 if (Ops.size() == 1) return Ops[0];
2507 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002508
2509 // Find the first UMax
2510 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2511 ++Idx;
2512
2513 // Check to see if one of the operands is a UMax. If so, expand its operands
2514 // onto our operand list, and recurse to simplify.
2515 if (Idx < Ops.size()) {
2516 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002517 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002518 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002519 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002520 DeletedUMax = true;
2521 }
2522
2523 if (DeletedUMax)
2524 return getUMaxExpr(Ops);
2525 }
2526
2527 // Okay, check to see if the same value occurs in the operand list twice. If
2528 // so, delete one. Since we sorted the list, these values are required to
2529 // be adjacent.
2530 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002531 // X umax Y umax Y --> X umax Y
2532 // X umax Y --> X, if X is always greater than Y
2533 if (Ops[i] == Ops[i+1] ||
2534 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2535 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2536 --i; --e;
2537 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002538 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2539 --i; --e;
2540 }
2541
2542 if (Ops.size() == 1) return Ops[0];
2543
2544 assert(!Ops.empty() && "Reduced umax down to nothing!");
2545
2546 // Okay, it looks like we really DO need a umax expr. Check to see if we
2547 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002548 FoldingSetNodeID ID;
2549 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002550 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2551 ID.AddPointer(Ops[i]);
2552 void *IP = 0;
2553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002554 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2555 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002556 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2557 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002558 UniqueSCEVs.InsertNode(S, IP);
2559 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002560}
2561
Dan Gohman9311ef62009-06-24 14:49:00 +00002562const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2563 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002564 // ~smax(~x, ~y) == smin(x, y).
2565 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2566}
2567
Dan Gohman9311ef62009-06-24 14:49:00 +00002568const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2569 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002570 // ~umax(~x, ~y) == umin(x, y)
2571 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2572}
2573
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002574const SCEV *ScalarEvolution::getSizeOfExpr(Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002575 // If we have TargetData, we can bypass creating a target-independent
2576 // constant expression and then folding it back into a ConstantInt.
2577 // This is just a compile-time optimization.
2578 if (TD)
2579 return getConstant(TD->getIntPtrType(getContext()),
2580 TD->getTypeAllocSize(AllocTy));
2581
Dan Gohman4f8eea82010-02-01 18:27:38 +00002582 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002584 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2585 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002586 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Dan Gohman4f8eea82010-02-01 18:27:38 +00002587 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2588}
2589
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002590const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00002591 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2592 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002593 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2594 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002595 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Dan Gohman4f8eea82010-02-01 18:27:38 +00002596 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2597}
2598
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002599const SCEV *ScalarEvolution::getOffsetOfExpr(StructType *STy,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002600 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002601 // If we have TargetData, we can bypass creating a target-independent
2602 // constant expression and then folding it back into a ConstantInt.
2603 // This is just a compile-time optimization.
2604 if (TD)
2605 return getConstant(TD->getIntPtrType(getContext()),
2606 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2607
Dan Gohman0f5efe52010-01-28 02:15:55 +00002608 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002610 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2611 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002612 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002613 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002614}
2615
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002616const SCEV *ScalarEvolution::getOffsetOfExpr(Type *CTy,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002617 Constant *FieldNo) {
2618 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002619 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002620 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2621 C = Folded;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002622 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002623 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002624}
2625
Dan Gohman0bba49c2009-07-07 17:06:11 +00002626const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002627 // Don't attempt to do anything other than create a SCEVUnknown object
2628 // here. createSCEV only calls getUnknown after checking for all other
2629 // interesting possibilities, and any other code that calls getUnknown
2630 // is doing so in order to hide a value from SCEV canonicalization.
2631
Dan Gohman1c343752009-06-27 21:21:31 +00002632 FoldingSetNodeID ID;
2633 ID.AddInteger(scUnknown);
2634 ID.AddPointer(V);
2635 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002636 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2637 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2638 "Stale SCEVUnknown in uniquing map!");
2639 return S;
2640 }
2641 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2642 FirstUnknown);
2643 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002644 UniqueSCEVs.InsertNode(S, IP);
2645 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002646}
2647
Chris Lattner53e677a2004-04-02 20:23:17 +00002648//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002649// Basic SCEV Analysis and PHI Idiom Recognition Code
2650//
2651
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002652/// isSCEVable - Test if values of the given type are analyzable within
2653/// the SCEV framework. This primarily includes integer types, and it
2654/// can optionally include pointer types if the ScalarEvolution class
2655/// has access to target-specific information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002656bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002657 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002658 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002659}
2660
2661/// getTypeSizeInBits - Return the size in bits of the specified type,
2662/// for which isSCEVable must return true.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002663uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002664 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2665
2666 // If we have a TargetData, use it!
2667 if (TD)
2668 return TD->getTypeSizeInBits(Ty);
2669
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002670 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002671 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002672 return Ty->getPrimitiveSizeInBits();
2673
2674 // The only other support type is pointer. Without TargetData, conservatively
2675 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002676 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002677 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002678}
2679
2680/// getEffectiveSCEVType - Return a type with the same bitwidth as
2681/// the given type and which represents how SCEV will treat the given
2682/// type, for which isSCEVable must return true. For pointer types,
2683/// this is the pointer-sized integer type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002684Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002685 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2686
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002687 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002688 return Ty;
2689
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002690 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002691 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002692 if (TD) return TD->getIntPtrType(getContext());
2693
2694 // Without TargetData, conservatively assume pointers are 64-bit.
2695 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002696}
Chris Lattner53e677a2004-04-02 20:23:17 +00002697
Dan Gohman0bba49c2009-07-07 17:06:11 +00002698const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002699 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002700}
2701
Chris Lattner53e677a2004-04-02 20:23:17 +00002702/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2703/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002704const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002705 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002706
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002707 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2708 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002709 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002710
2711 // The process of creating a SCEV for V may have caused other SCEVs
2712 // to have been created, so it's necessary to insert the new entry
2713 // from scratch, rather than trying to remember the insert position
2714 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002715 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002716 return S;
2717}
2718
Dan Gohman2d1be872009-04-16 03:18:22 +00002719/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2720///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002721const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002722 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002723 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002724 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002725
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002726 Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002727 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002728 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002729 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002730}
2731
2732/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002733const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002734 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002735 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002736 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002737
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002738 Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002739 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002740 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002741 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002742 return getMinusSCEV(AllOnes, V);
2743}
2744
Andrew Trick3228cc22011-03-14 16:50:06 +00002745/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattner992efb02011-01-09 22:26:35 +00002746const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00002747 SCEV::NoWrapFlags Flags) {
Andrew Trick4dbe2002011-03-15 01:16:14 +00002748 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
2749
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002750 // Fast path: X - X --> 0.
2751 if (LHS == RHS)
2752 return getConstant(LHS->getType(), 0);
2753
Dan Gohman2d1be872009-04-16 03:18:22 +00002754 // X - Y --> X + -Y
Andrew Trick3228cc22011-03-14 16:50:06 +00002755 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman2d1be872009-04-16 03:18:22 +00002756}
2757
2758/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2759/// input value to the specified type. If the type must be extended, it is zero
2760/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002761const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002762ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
2763 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002764 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2765 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002766 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002767 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002768 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002769 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002770 return getTruncateExpr(V, Ty);
2771 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002772}
2773
2774/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2775/// input value to the specified type. If the type must be extended, it is sign
2776/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002777const SCEV *
2778ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002779 Type *Ty) {
2780 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002781 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2782 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002783 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002784 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002785 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002786 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002787 return getTruncateExpr(V, Ty);
2788 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002789}
2790
Dan Gohman467c4302009-05-13 03:46:30 +00002791/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2792/// input value to the specified type. If the type must be extended, it is zero
2793/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002794const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002795ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
2796 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002797 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2798 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002799 "Cannot noop or zero extend with non-integer arguments!");
2800 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2801 "getNoopOrZeroExtend cannot truncate!");
2802 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2803 return V; // No conversion
2804 return getZeroExtendExpr(V, Ty);
2805}
2806
2807/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2808/// input value to the specified type. If the type must be extended, it is sign
2809/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002810const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002811ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
2812 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002813 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2814 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002815 "Cannot noop or sign extend with non-integer arguments!");
2816 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2817 "getNoopOrSignExtend cannot truncate!");
2818 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2819 return V; // No conversion
2820 return getSignExtendExpr(V, Ty);
2821}
2822
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002823/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2824/// the input value to the specified type. If the type must be extended,
2825/// it is extended with unspecified bits. The conversion must not be
2826/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002827const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002828ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
2829 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002830 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2831 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002832 "Cannot noop or any extend with non-integer arguments!");
2833 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2834 "getNoopOrAnyExtend cannot truncate!");
2835 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2836 return V; // No conversion
2837 return getAnyExtendExpr(V, Ty);
2838}
2839
Dan Gohman467c4302009-05-13 03:46:30 +00002840/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2841/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002842const SCEV *
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002843ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
2844 Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002845 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2846 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002847 "Cannot truncate or noop with non-integer arguments!");
2848 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2849 "getTruncateOrNoop cannot extend!");
2850 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2851 return V; // No conversion
2852 return getTruncateExpr(V, Ty);
2853}
2854
Dan Gohmana334aa72009-06-22 00:31:57 +00002855/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2856/// the types using zero-extension, and then perform a umax operation
2857/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002858const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2859 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002860 const SCEV *PromotedLHS = LHS;
2861 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002862
2863 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2864 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2865 else
2866 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2867
2868 return getUMaxExpr(PromotedLHS, PromotedRHS);
2869}
2870
Dan Gohmanc9759e82009-06-22 15:03:27 +00002871/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2872/// the types using zero-extension, and then perform a umin operation
2873/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002874const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2875 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002876 const SCEV *PromotedLHS = LHS;
2877 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002878
2879 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2880 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2881 else
2882 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2883
2884 return getUMinExpr(PromotedLHS, PromotedRHS);
2885}
2886
Andrew Trickb12a7542011-03-17 23:51:11 +00002887/// getPointerBase - Transitively follow the chain of pointer-type operands
2888/// until reaching a SCEV that does not have a single pointer operand. This
2889/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
2890/// but corner cases do exist.
2891const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
2892 // A pointer operand may evaluate to a nonpointer expression, such as null.
2893 if (!V->getType()->isPointerTy())
2894 return V;
2895
2896 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
2897 return getPointerBase(Cast->getOperand());
2898 }
2899 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
2900 const SCEV *PtrOp = 0;
2901 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
2902 I != E; ++I) {
2903 if ((*I)->getType()->isPointerTy()) {
2904 // Cannot find the base of an expression with multiple pointer operands.
2905 if (PtrOp)
2906 return V;
2907 PtrOp = *I;
2908 }
2909 }
2910 if (!PtrOp)
2911 return V;
2912 return getPointerBase(PtrOp);
2913 }
2914 return V;
2915}
2916
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002917/// PushDefUseChildren - Push users of the given Instruction
2918/// onto the given Worklist.
2919static void
2920PushDefUseChildren(Instruction *I,
2921 SmallVectorImpl<Instruction *> &Worklist) {
2922 // Push the def-use children onto the Worklist stack.
2923 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2924 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002925 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002926}
2927
2928/// ForgetSymbolicValue - This looks up computed SCEV values for all
2929/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002930/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002931/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002932void
Dan Gohman85669632010-02-25 06:57:05 +00002933ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002934 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002935 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002936
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002937 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002938 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002939 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002940 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002941 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002942
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002943 ValueExprMapType::iterator It =
2944 ValueExprMap.find(static_cast<Value *>(I));
2945 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002946 const SCEV *Old = It->second;
2947
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002948 // Short-circuit the def-use traversal if the symbolic name
2949 // ceases to appear in expressions.
Dan Gohman4ce32db2010-11-17 22:27:42 +00002950 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002951 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002952
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002953 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002954 // structure, it's a PHI that's in the progress of being computed
2955 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2956 // additional loop trip count information isn't going to change anything.
2957 // In the second case, createNodeForPHI will perform the necessary
2958 // updates on its own when it gets to that point. In the third, we do
2959 // want to forget the SCEVUnknown.
2960 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002961 !isa<SCEVUnknown>(Old) ||
2962 (I != PN && Old == SymName)) {
Dan Gohman56a75682010-11-17 23:28:48 +00002963 forgetMemoizedResults(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002964 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002965 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002966 }
2967
2968 PushDefUseChildren(I, Worklist);
2969 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002970}
Chris Lattner53e677a2004-04-02 20:23:17 +00002971
2972/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2973/// a loop header, making it a potential recurrence, or it doesn't.
2974///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002975const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002976 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2977 if (L->getHeader() == PN->getParent()) {
2978 // The loop may have multiple entrances or multiple exits; we can analyze
2979 // this phi as an addrec if it has a unique entry value and a unique
2980 // backedge value.
2981 Value *BEValueV = 0, *StartValueV = 0;
2982 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2983 Value *V = PN->getIncomingValue(i);
2984 if (L->contains(PN->getIncomingBlock(i))) {
2985 if (!BEValueV) {
2986 BEValueV = V;
2987 } else if (BEValueV != V) {
2988 BEValueV = 0;
2989 break;
2990 }
2991 } else if (!StartValueV) {
2992 StartValueV = V;
2993 } else if (StartValueV != V) {
2994 StartValueV = 0;
2995 break;
2996 }
2997 }
2998 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002999 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003000 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003001 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003002 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003003 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00003004
3005 // Using this symbolic name for the PHI, analyze the value coming around
3006 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00003007 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00003008
3009 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3010 // has a special value for the first iteration of the loop.
3011
3012 // If the value coming around the backedge is an add with the symbolic
3013 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00003014 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003015 // If there is a single occurrence of the symbolic value, replace it
3016 // with a recurrence.
3017 unsigned FoundIndex = Add->getNumOperands();
3018 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3019 if (Add->getOperand(i) == SymbolicName)
3020 if (FoundIndex == e) {
3021 FoundIndex = i;
3022 break;
3023 }
3024
3025 if (FoundIndex != Add->getNumOperands()) {
3026 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003027 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00003028 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3029 if (i != FoundIndex)
3030 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00003031 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00003032
3033 // This is not a valid addrec if the step amount is varying each
3034 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00003035 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00003036 (isa<SCEVAddRecExpr>(Accum) &&
3037 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick3228cc22011-03-14 16:50:06 +00003038 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohmana10756e2010-01-21 02:09:26 +00003039
3040 // If the increment doesn't overflow, then neither the addrec nor
3041 // the post-increment will overflow.
3042 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3043 if (OBO->hasNoUnsignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00003044 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohmana10756e2010-01-21 02:09:26 +00003045 if (OBO->hasNoSignedWrap())
Andrew Trick3228cc22011-03-14 16:50:06 +00003046 Flags = setFlags(Flags, SCEV::FlagNSW);
Andrew Trick635f7182011-03-09 17:23:39 +00003047 } else if (const GEPOperator *GEP =
Andrew Trick3228cc22011-03-14 16:50:06 +00003048 dyn_cast<GEPOperator>(BEValueV)) {
3049 // If the increment is an inbounds GEP, then we know the address
3050 // space cannot be wrapped around. We cannot make any guarantee
3051 // about signed or unsigned overflow because pointers are
3052 // unsigned but we may have a negative index from the base
3053 // pointer.
3054 if (GEP->isInBounds())
Andrew Trickc343c1e2011-03-15 00:37:00 +00003055 Flags = setFlags(Flags, SCEV::FlagNW);
Dan Gohmana10756e2010-01-21 02:09:26 +00003056 }
3057
Dan Gohman27dead42010-04-12 07:49:36 +00003058 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick3228cc22011-03-14 16:50:06 +00003059 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohmaneb490a72009-07-25 01:22:26 +00003060
Dan Gohmana10756e2010-01-21 02:09:26 +00003061 // Since the no-wrap flags are on the increment, they apply to the
3062 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00003063 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00003064 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick3228cc22011-03-14 16:50:06 +00003065 Accum, L, Flags);
Chris Lattner53e677a2004-04-02 20:23:17 +00003066
3067 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00003068 // to be symbolic. We now need to go back and purge all of the
3069 // entries for the scalars that use the symbolic expression.
3070 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003071 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00003072 return PHISCEV;
3073 }
3074 }
Dan Gohman622ed672009-05-04 22:02:23 +00003075 } else if (const SCEVAddRecExpr *AddRec =
3076 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00003077 // Otherwise, this could be a loop like this:
3078 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3079 // In this case, j = {1,+,1} and BEValue is j.
3080 // Because the other in-value of i (0) fits the evolution of BEValue
3081 // i really is an addrec evolution.
3082 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00003083 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00003084
3085 // If StartVal = j.start - j.stride, we can use StartVal as the
3086 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003087 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00003088 AddRec->getOperand(1))) {
Andrew Trick3228cc22011-03-14 16:50:06 +00003089 // FIXME: For constant StartVal, we should be able to infer
3090 // no-wrap flags.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003091 const SCEV *PHISCEV =
Andrew Trick3228cc22011-03-14 16:50:06 +00003092 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3093 SCEV::FlagAnyWrap);
Chris Lattner97156e72006-04-26 18:34:07 +00003094
3095 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00003096 // to be symbolic. We now need to go back and purge all of the
3097 // entries for the scalars that use the symbolic expression.
3098 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003099 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00003100 return PHISCEV;
3101 }
3102 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003103 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003104 }
Dan Gohman27dead42010-04-12 07:49:36 +00003105 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003106
Dan Gohman85669632010-02-25 06:57:05 +00003107 // If the PHI has a single incoming value, follow that value, unless the
3108 // PHI's incoming blocks are in a different loop, in which case doing so
3109 // risks breaking LCSSA form. Instcombine would normally zap these, but
3110 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00003111 if (Value *V = SimplifyInstruction(PN, TD, DT))
3112 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohman85669632010-02-25 06:57:05 +00003113 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00003114
Chris Lattner53e677a2004-04-02 20:23:17 +00003115 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003116 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00003117}
3118
Dan Gohman26466c02009-05-08 20:26:55 +00003119/// createNodeForGEP - Expand GEP instructions into add and multiply
3120/// operations. This allows them to be analyzed by regular SCEV code.
3121///
Dan Gohmand281ed22009-12-18 02:09:29 +00003122const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00003123
Dan Gohmanb9f96512010-06-30 07:16:37 +00003124 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3125 // Add expression, because the Instruction may be guarded by control flow
3126 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00003127 // context.
Chris Lattner8ebaf902011-02-13 03:14:49 +00003128 bool isInBounds = GEP->isInBounds();
Dan Gohman7a642572010-06-29 01:41:41 +00003129
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003130 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00003131 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00003132 // Don't attempt to analyze GEPs over unsized objects.
3133 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
3134 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00003135 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00003136 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00003137 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00003138 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00003139 I != E; ++I) {
3140 Value *Index = *I;
3141 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003142 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Dan Gohman26466c02009-05-08 20:26:55 +00003143 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00003144 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00003145 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
3146
Dan Gohmanb9f96512010-06-30 07:16:37 +00003147 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00003148 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00003149 } else {
3150 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00003151 const SCEV *ElementSize = getSizeOfExpr(*GTI);
3152 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003153 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00003154 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3155
Dan Gohmanb9f96512010-06-30 07:16:37 +00003156 // Multiply the index by the element size to compute the element offset.
Andrew Trick3228cc22011-03-14 16:50:06 +00003157 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
3158 isInBounds ? SCEV::FlagNSW :
3159 SCEV::FlagAnyWrap);
Dan Gohmanb9f96512010-06-30 07:16:37 +00003160
3161 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00003162 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00003163 }
3164 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00003165
3166 // Get the SCEV for the GEP base.
3167 const SCEV *BaseS = getSCEV(Base);
3168
Dan Gohmanb9f96512010-06-30 07:16:37 +00003169 // Add the total offset from all the GEP indices to the base.
Andrew Trick3228cc22011-03-14 16:50:06 +00003170 return getAddExpr(BaseS, TotalOffset,
3171 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
Dan Gohman26466c02009-05-08 20:26:55 +00003172}
3173
Nick Lewycky83bb0052007-11-22 07:59:40 +00003174/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3175/// guaranteed to end in (at every loop iteration). It is, at the same time,
3176/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3177/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003178uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00003179ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00003180 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00003181 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00003182
Dan Gohman622ed672009-05-04 22:02:23 +00003183 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00003184 return std::min(GetMinTrailingZeros(T->getOperand()),
3185 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003186
Dan Gohman622ed672009-05-04 22:02:23 +00003187 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003188 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3189 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3190 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00003191 }
3192
Dan Gohman622ed672009-05-04 22:02:23 +00003193 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003194 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3195 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3196 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00003197 }
3198
Dan Gohman622ed672009-05-04 22:02:23 +00003199 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003200 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003201 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003202 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003203 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003204 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003205 }
3206
Dan Gohman622ed672009-05-04 22:02:23 +00003207 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003208 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003209 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3210 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00003211 for (unsigned i = 1, e = M->getNumOperands();
3212 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003213 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00003214 BitWidth);
3215 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003216 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003217
Dan Gohman622ed672009-05-04 22:02:23 +00003218 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00003219 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003220 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003221 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003222 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00003223 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00003224 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00003225
Dan Gohman622ed672009-05-04 22:02:23 +00003226 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003227 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003228 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003229 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003230 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003231 return MinOpRes;
3232 }
3233
Dan Gohman622ed672009-05-04 22:02:23 +00003234 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00003235 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003236 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00003237 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00003238 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00003239 return MinOpRes;
3240 }
3241
Dan Gohman2c364ad2009-06-19 23:29:04 +00003242 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3243 // For a SCEVUnknown, ask ValueTracking.
3244 unsigned BitWidth = getTypeSizeInBits(U->getType());
3245 APInt Mask = APInt::getAllOnesValue(BitWidth);
3246 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3247 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3248 return Zeros.countTrailingOnes();
3249 }
3250
3251 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00003252 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00003253}
Chris Lattner53e677a2004-04-02 20:23:17 +00003254
Dan Gohman85b05a22009-07-13 21:35:55 +00003255/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3256///
3257ConstantRange
3258ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003259 // See if we've computed this range already.
3260 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3261 if (I != UnsignedRanges.end())
3262 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003263
3264 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003265 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003266
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003267 unsigned BitWidth = getTypeSizeInBits(S->getType());
3268 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3269
3270 // If the value has known zeros, the maximum unsigned value will have those
3271 // known zeros as well.
3272 uint32_t TZ = GetMinTrailingZeros(S);
3273 if (TZ != 0)
3274 ConservativeResult =
3275 ConstantRange(APInt::getMinValue(BitWidth),
3276 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3277
Dan Gohman85b05a22009-07-13 21:35:55 +00003278 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3279 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3280 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3281 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003282 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003283 }
3284
3285 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3286 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3287 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3288 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003289 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003290 }
3291
3292 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3293 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3294 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3295 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003296 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003297 }
3298
3299 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3300 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3301 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3302 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003303 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003304 }
3305
3306 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3307 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3308 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003309 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003310 }
3311
3312 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3313 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003314 return setUnsignedRange(ZExt,
3315 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003316 }
3317
3318 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3319 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003320 return setUnsignedRange(SExt,
3321 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003322 }
3323
3324 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3325 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003326 return setUnsignedRange(Trunc,
3327 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003328 }
3329
Dan Gohman85b05a22009-07-13 21:35:55 +00003330 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003331 // If there's no unsigned wrap, the value will never be less than its
3332 // initial value.
Andrew Trick3228cc22011-03-14 16:50:06 +00003333 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohmana10756e2010-01-21 02:09:26 +00003334 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003335 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003336 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003337 ConservativeResult.intersectWith(
3338 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003339
3340 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003341 if (AddRec->isAffine()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003342 Type *Ty = AddRec->getType();
Dan Gohman85b05a22009-07-13 21:35:55 +00003343 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003344 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3345 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003346 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3347
3348 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003349 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003350
3351 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003352 ConstantRange StepRange = getSignedRange(Step);
3353 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3354 ConstantRange EndRange =
3355 StartRange.add(MaxBECountRange.multiply(StepRange));
3356
3357 // Check for overflow. This must be done with ConstantRange arithmetic
3358 // because we could be called from within the ScalarEvolution overflow
3359 // checking code.
3360 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3361 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3362 ConstantRange ExtMaxBECountRange =
3363 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3364 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3365 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3366 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003367 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003368
Dan Gohman85b05a22009-07-13 21:35:55 +00003369 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3370 EndRange.getUnsignedMin());
3371 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3372 EndRange.getUnsignedMax());
3373 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003374 return setUnsignedRange(AddRec, ConservativeResult);
3375 return setUnsignedRange(AddRec,
3376 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003377 }
3378 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003379
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003380 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003381 }
3382
3383 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3384 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003385 APInt Mask = APInt::getAllOnesValue(BitWidth);
3386 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3387 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003388 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003389 return setUnsignedRange(U, ConservativeResult);
3390 return setUnsignedRange(U,
3391 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003392 }
3393
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003394 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003395}
3396
Dan Gohman85b05a22009-07-13 21:35:55 +00003397/// getSignedRange - Determine the signed range for a particular SCEV.
3398///
3399ConstantRange
3400ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohmana3bbf242011-01-24 17:54:18 +00003401 // See if we've computed this range already.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003402 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3403 if (I != SignedRanges.end())
3404 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003405
Dan Gohman85b05a22009-07-13 21:35:55 +00003406 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003407 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003408
Dan Gohman52fddd32010-01-26 04:40:18 +00003409 unsigned BitWidth = getTypeSizeInBits(S->getType());
3410 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3411
3412 // If the value has known zeros, the maximum signed value will have those
3413 // known zeros as well.
3414 uint32_t TZ = GetMinTrailingZeros(S);
3415 if (TZ != 0)
3416 ConservativeResult =
3417 ConstantRange(APInt::getSignedMinValue(BitWidth),
3418 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3419
Dan Gohman85b05a22009-07-13 21:35:55 +00003420 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3421 ConstantRange X = getSignedRange(Add->getOperand(0));
3422 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3423 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003424 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003425 }
3426
Dan Gohman85b05a22009-07-13 21:35:55 +00003427 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3428 ConstantRange X = getSignedRange(Mul->getOperand(0));
3429 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3430 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003431 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003432 }
3433
Dan Gohman85b05a22009-07-13 21:35:55 +00003434 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3435 ConstantRange X = getSignedRange(SMax->getOperand(0));
3436 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3437 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003438 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003439 }
Dan Gohman62849c02009-06-24 01:05:09 +00003440
Dan Gohman85b05a22009-07-13 21:35:55 +00003441 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3442 ConstantRange X = getSignedRange(UMax->getOperand(0));
3443 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3444 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003445 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003446 }
Dan Gohman62849c02009-06-24 01:05:09 +00003447
Dan Gohman85b05a22009-07-13 21:35:55 +00003448 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3449 ConstantRange X = getSignedRange(UDiv->getLHS());
3450 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003451 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003452 }
Dan Gohman62849c02009-06-24 01:05:09 +00003453
Dan Gohman85b05a22009-07-13 21:35:55 +00003454 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3455 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003456 return setSignedRange(ZExt,
3457 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003458 }
3459
3460 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3461 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003462 return setSignedRange(SExt,
3463 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003464 }
3465
3466 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3467 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003468 return setSignedRange(Trunc,
3469 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003470 }
3471
Dan Gohman85b05a22009-07-13 21:35:55 +00003472 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003473 // If there's no signed wrap, and all the operands have the same sign or
3474 // zero, the value won't ever change sign.
Andrew Trick3228cc22011-03-14 16:50:06 +00003475 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003476 bool AllNonNeg = true;
3477 bool AllNonPos = true;
3478 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3479 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3480 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3481 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003482 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003483 ConservativeResult = ConservativeResult.intersectWith(
3484 ConstantRange(APInt(BitWidth, 0),
3485 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003486 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003487 ConservativeResult = ConservativeResult.intersectWith(
3488 ConstantRange(APInt::getSignedMinValue(BitWidth),
3489 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003490 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003491
3492 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003493 if (AddRec->isAffine()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003494 Type *Ty = AddRec->getType();
Dan Gohman85b05a22009-07-13 21:35:55 +00003495 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003496 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3497 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003498 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3499
3500 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003501 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003502
3503 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003504 ConstantRange StepRange = getSignedRange(Step);
3505 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3506 ConstantRange EndRange =
3507 StartRange.add(MaxBECountRange.multiply(StepRange));
3508
3509 // Check for overflow. This must be done with ConstantRange arithmetic
3510 // because we could be called from within the ScalarEvolution overflow
3511 // checking code.
3512 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3513 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3514 ConstantRange ExtMaxBECountRange =
3515 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3516 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3517 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3518 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003519 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003520
Dan Gohman85b05a22009-07-13 21:35:55 +00003521 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3522 EndRange.getSignedMin());
3523 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3524 EndRange.getSignedMax());
3525 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003526 return setSignedRange(AddRec, ConservativeResult);
3527 return setSignedRange(AddRec,
3528 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003529 }
Dan Gohman62849c02009-06-24 01:05:09 +00003530 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003531
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003532 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003533 }
3534
Dan Gohman2c364ad2009-06-19 23:29:04 +00003535 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3536 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003537 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003538 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003539 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3540 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003541 return setSignedRange(U, ConservativeResult);
3542 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003543 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003544 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003545 }
3546
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003547 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003548}
3549
Chris Lattner53e677a2004-04-02 20:23:17 +00003550/// createSCEV - We know that there is no SCEV for the specified value.
3551/// Analyze the expression.
3552///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003553const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003554 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003555 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003556
Dan Gohman6c459a22008-06-22 19:56:46 +00003557 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003558 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003559 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003560
3561 // Don't attempt to analyze instructions in blocks that aren't
3562 // reachable. Such instructions don't matter, and they aren't required
3563 // to obey basic rules for definitions dominating uses which this
3564 // analysis depends on.
3565 if (!DT->isReachableFromEntry(I->getParent()))
3566 return getUnknown(V);
3567 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003568 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003569 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3570 return getConstant(CI);
3571 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003572 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003573 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3574 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003575 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003576 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003577
Dan Gohmanca178902009-07-17 20:47:02 +00003578 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003579 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003580 case Instruction::Add: {
3581 // The simple thing to do would be to just call getSCEV on both operands
3582 // and call getAddExpr with the result. However if we're looking at a
3583 // bunch of things all added together, this can be quite inefficient,
3584 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3585 // Instead, gather up all the operands and make a single getAddExpr call.
3586 // LLVM IR canonical form means we need only traverse the left operands.
3587 SmallVector<const SCEV *, 4> AddOps;
3588 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003589 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3590 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3591 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3592 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003593 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003594 const SCEV *Op1 = getSCEV(U->getOperand(1));
3595 if (Opcode == Instruction::Sub)
3596 AddOps.push_back(getNegativeSCEV(Op1));
3597 else
3598 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003599 }
3600 AddOps.push_back(getSCEV(U->getOperand(0)));
Andrew Trick54337672011-09-10 01:09:50 +00003601 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3602 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(V);
3603 if (OBO->hasNoSignedWrap())
3604 setFlags(Flags, SCEV::FlagNSW);
3605 if (OBO->hasNoUnsignedWrap())
3606 setFlags(Flags, SCEV::FlagNUW);
3607 return getAddExpr(AddOps, Flags);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003608 }
3609 case Instruction::Mul: {
3610 // See the Add code above.
3611 SmallVector<const SCEV *, 4> MulOps;
3612 MulOps.push_back(getSCEV(U->getOperand(1)));
3613 for (Value *Op = U->getOperand(0);
Andrew Trick635f7182011-03-09 17:23:39 +00003614 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003615 Op = U->getOperand(0)) {
3616 U = cast<Operator>(Op);
3617 MulOps.push_back(getSCEV(U->getOperand(1)));
3618 }
3619 MulOps.push_back(getSCEV(U->getOperand(0)));
3620 return getMulExpr(MulOps);
3621 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003622 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003623 return getUDivExpr(getSCEV(U->getOperand(0)),
3624 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003625 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003626 return getMinusSCEV(getSCEV(U->getOperand(0)),
3627 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003628 case Instruction::And:
3629 // For an expression like x&255 that merely masks off the high bits,
3630 // use zext(trunc(x)) as the SCEV expression.
3631 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003632 if (CI->isNullValue())
3633 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003634 if (CI->isAllOnesValue())
3635 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003636 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003637
3638 // Instcombine's ShrinkDemandedConstant may strip bits out of
3639 // constants, obscuring what would otherwise be a low-bits mask.
3640 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3641 // knew about to reconstruct a low-bits mask value.
3642 unsigned LZ = A.countLeadingZeros();
3643 unsigned BitWidth = A.getBitWidth();
3644 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3645 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3646 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3647
3648 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3649
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003650 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003651 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003652 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003653 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003654 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003655 }
3656 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003657
Dan Gohman6c459a22008-06-22 19:56:46 +00003658 case Instruction::Or:
3659 // If the RHS of the Or is a constant, we may have something like:
3660 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3661 // optimizations will transparently handle this case.
3662 //
3663 // In order for this transformation to be safe, the LHS must be of the
3664 // form X*(2^n) and the Or constant must be less than 2^n.
3665 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003666 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003667 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003668 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003669 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3670 // Build a plain add SCEV.
3671 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3672 // If the LHS of the add was an addrec and it has no-wrap flags,
3673 // transfer the no-wrap flags, since an or won't introduce a wrap.
3674 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3675 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick3228cc22011-03-14 16:50:06 +00003676 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3677 OldAR->getNoWrapFlags());
Dan Gohman1f96e672009-09-17 18:05:20 +00003678 }
3679 return S;
3680 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003681 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003682 break;
3683 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003684 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003685 // If the RHS of the xor is a signbit, then this is just an add.
3686 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003687 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003688 return getAddExpr(getSCEV(U->getOperand(0)),
3689 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003690
3691 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003692 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003693 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003694
3695 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3696 // This is a variant of the check for xor with -1, and it handles
3697 // the case where instcombine has trimmed non-demanded bits out
3698 // of an xor with -1.
3699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3700 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3701 if (BO->getOpcode() == Instruction::And &&
3702 LCI->getValue() == CI->getValue())
3703 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003704 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003705 Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003706 const SCEV *Z0 = Z->getOperand();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003707 Type *Z0Ty = Z0->getType();
Dan Gohman82052832009-06-18 00:00:20 +00003708 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3709
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003710 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003711 // mask off the high bits. Complement the operand and
3712 // re-apply the zext.
3713 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3714 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3715
3716 // If C is a single bit, it may be in the sign-bit position
3717 // before the zero-extend. In this case, represent the xor
3718 // using an add, which is equivalent, and re-apply the zext.
Jay Foad40f8f622010-12-07 08:25:19 +00003719 APInt Trunc = CI->getValue().trunc(Z0TySize);
3720 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohman82052832009-06-18 00:00:20 +00003721 Trunc.isSignBit())
3722 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3723 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003724 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003725 }
3726 break;
3727
3728 case Instruction::Shl:
3729 // Turn shift left of a constant amount into a multiply.
3730 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003731 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003732
3733 // If the shift count is not less than the bitwidth, the result of
3734 // the shift is undefined. Don't try to analyze it, because the
3735 // resolution chosen here may differ from the resolution chosen in
3736 // other parts of the compiler.
3737 if (SA->getValue().uge(BitWidth))
3738 break;
3739
Owen Andersoneed707b2009-07-24 23:12:02 +00003740 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003741 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003742 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003743 }
3744 break;
3745
Nick Lewycky01eaf802008-07-07 06:15:49 +00003746 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003747 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003748 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003749 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003750
3751 // If the shift count is not less than the bitwidth, the result of
3752 // the shift is undefined. Don't try to analyze it, because the
3753 // resolution chosen here may differ from the resolution chosen in
3754 // other parts of the compiler.
3755 if (SA->getValue().uge(BitWidth))
3756 break;
3757
Owen Andersoneed707b2009-07-24 23:12:02 +00003758 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003759 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003760 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003761 }
3762 break;
3763
Dan Gohman4ee29af2009-04-21 02:26:00 +00003764 case Instruction::AShr:
3765 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3766 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003767 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003768 if (L->getOpcode() == Instruction::Shl &&
3769 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003770 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3771
3772 // If the shift count is not less than the bitwidth, the result of
3773 // the shift is undefined. Don't try to analyze it, because the
3774 // resolution chosen here may differ from the resolution chosen in
3775 // other parts of the compiler.
3776 if (CI->getValue().uge(BitWidth))
3777 break;
3778
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003779 uint64_t Amt = BitWidth - CI->getZExtValue();
3780 if (Amt == BitWidth)
3781 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003782 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003783 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003784 IntegerType::get(getContext(),
3785 Amt)),
3786 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003787 }
3788 break;
3789
Dan Gohman6c459a22008-06-22 19:56:46 +00003790 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003791 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003792
3793 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003794 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003795
3796 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003797 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003798
3799 case Instruction::BitCast:
3800 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003801 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003802 return getSCEV(U->getOperand(0));
3803 break;
3804
Dan Gohman4f8eea82010-02-01 18:27:38 +00003805 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3806 // lead to pointer expressions which cannot safely be expanded to GEPs,
3807 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3808 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003809
Dan Gohman26466c02009-05-08 20:26:55 +00003810 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003811 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003812
Dan Gohman6c459a22008-06-22 19:56:46 +00003813 case Instruction::PHI:
3814 return createNodeForPHI(cast<PHINode>(U));
3815
3816 case Instruction::Select:
3817 // This could be a smax or umax that was lowered earlier.
3818 // Try to recover it.
3819 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3820 Value *LHS = ICI->getOperand(0);
3821 Value *RHS = ICI->getOperand(1);
3822 switch (ICI->getPredicate()) {
3823 case ICmpInst::ICMP_SLT:
3824 case ICmpInst::ICMP_SLE:
3825 std::swap(LHS, RHS);
3826 // fall through
3827 case ICmpInst::ICMP_SGT:
3828 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003829 // a >s b ? a+x : b+x -> smax(a, b)+x
3830 // a >s b ? b+x : a+x -> smin(a, b)+x
3831 if (LHS->getType() == U->getType()) {
3832 const SCEV *LS = getSCEV(LHS);
3833 const SCEV *RS = getSCEV(RHS);
3834 const SCEV *LA = getSCEV(U->getOperand(1));
3835 const SCEV *RA = getSCEV(U->getOperand(2));
3836 const SCEV *LDiff = getMinusSCEV(LA, LS);
3837 const SCEV *RDiff = getMinusSCEV(RA, RS);
3838 if (LDiff == RDiff)
3839 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3840 LDiff = getMinusSCEV(LA, RS);
3841 RDiff = getMinusSCEV(RA, LS);
3842 if (LDiff == RDiff)
3843 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3844 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003845 break;
3846 case ICmpInst::ICMP_ULT:
3847 case ICmpInst::ICMP_ULE:
3848 std::swap(LHS, RHS);
3849 // fall through
3850 case ICmpInst::ICMP_UGT:
3851 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003852 // a >u b ? a+x : b+x -> umax(a, b)+x
3853 // a >u b ? b+x : a+x -> umin(a, b)+x
3854 if (LHS->getType() == U->getType()) {
3855 const SCEV *LS = getSCEV(LHS);
3856 const SCEV *RS = getSCEV(RHS);
3857 const SCEV *LA = getSCEV(U->getOperand(1));
3858 const SCEV *RA = getSCEV(U->getOperand(2));
3859 const SCEV *LDiff = getMinusSCEV(LA, LS);
3860 const SCEV *RDiff = getMinusSCEV(RA, RS);
3861 if (LDiff == RDiff)
3862 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3863 LDiff = getMinusSCEV(LA, RS);
3864 RDiff = getMinusSCEV(RA, LS);
3865 if (LDiff == RDiff)
3866 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3867 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003868 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003869 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003870 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3871 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003872 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003873 cast<ConstantInt>(RHS)->isZero()) {
3874 const SCEV *One = getConstant(LHS->getType(), 1);
3875 const SCEV *LS = getSCEV(LHS);
3876 const SCEV *LA = getSCEV(U->getOperand(1));
3877 const SCEV *RA = getSCEV(U->getOperand(2));
3878 const SCEV *LDiff = getMinusSCEV(LA, LS);
3879 const SCEV *RDiff = getMinusSCEV(RA, One);
3880 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003881 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003882 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003883 break;
3884 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003885 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3886 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003887 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003888 cast<ConstantInt>(RHS)->isZero()) {
3889 const SCEV *One = getConstant(LHS->getType(), 1);
3890 const SCEV *LS = getSCEV(LHS);
3891 const SCEV *LA = getSCEV(U->getOperand(1));
3892 const SCEV *RA = getSCEV(U->getOperand(2));
3893 const SCEV *LDiff = getMinusSCEV(LA, One);
3894 const SCEV *RDiff = getMinusSCEV(RA, LS);
3895 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003896 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003897 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003898 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003899 default:
3900 break;
3901 }
3902 }
3903
3904 default: // We cannot analyze this expression.
3905 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003906 }
3907
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003908 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003909}
3910
3911
3912
3913//===----------------------------------------------------------------------===//
3914// Iteration Count Computation Code
3915//
3916
Andrew Trickb1831c62011-08-11 23:36:16 +00003917/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
3918/// normal unsigned value, if possible. Returns 0 if the trip count is unknown
3919/// or not constant. Will also return 0 if the maximum trip count is very large
3920/// (>= 2^32)
3921unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
3922 BasicBlock *ExitBlock) {
3923 const SCEVConstant *ExitCount =
3924 dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock));
3925 if (!ExitCount)
3926 return 0;
3927
3928 ConstantInt *ExitConst = ExitCount->getValue();
3929
3930 // Guard against huge trip counts.
3931 if (ExitConst->getValue().getActiveBits() > 32)
3932 return 0;
3933
3934 // In case of integer overflow, this returns 0, which is correct.
3935 return ((unsigned)ExitConst->getZExtValue()) + 1;
3936}
3937
3938/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
3939/// trip count of this loop as a normal unsigned value, if possible. This
3940/// means that the actual trip count is always a multiple of the returned
3941/// value (don't forget the trip count could very well be zero as well!).
3942///
3943/// Returns 1 if the trip count is unknown or not guaranteed to be the
3944/// multiple of a constant (which is also the case if the trip count is simply
3945/// constant, use getSmallConstantTripCount for that case), Will also return 1
3946/// if the trip count is very large (>= 2^32).
3947unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
3948 BasicBlock *ExitBlock) {
3949 const SCEV *ExitCount = getExitCount(L, ExitBlock);
3950 if (ExitCount == getCouldNotCompute())
3951 return 1;
3952
3953 // Get the trip count from the BE count by adding 1.
3954 const SCEV *TCMul = getAddExpr(ExitCount,
3955 getConstant(ExitCount->getType(), 1));
3956 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
3957 // to factor simple cases.
3958 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
3959 TCMul = Mul->getOperand(0);
3960
3961 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
3962 if (!MulC)
3963 return 1;
3964
3965 ConstantInt *Result = MulC->getValue();
3966
3967 // Guard against huge trip counts.
3968 if (!Result || Result->getValue().getActiveBits() > 32)
3969 return 1;
3970
3971 return (unsigned)Result->getZExtValue();
3972}
3973
Andrew Trick5116ff62011-07-26 17:19:55 +00003974// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickfcb43562011-08-02 04:23:35 +00003975// this loop is guaranteed not to exit via ExitintBlock. Otherwise return
Andrew Trick5116ff62011-07-26 17:19:55 +00003976// SCEVCouldNotCompute.
Andrew Trickfcb43562011-08-02 04:23:35 +00003977const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
3978 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick5116ff62011-07-26 17:19:55 +00003979}
3980
Dan Gohman46bdfb02009-02-24 18:55:53 +00003981/// getBackedgeTakenCount - If the specified loop has a predictable
3982/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3983/// object. The backedge-taken count is the number of times the loop header
3984/// will be branched to from within the loop. This is one less than the
3985/// trip count of the loop, since it doesn't count the first iteration,
3986/// when the header is branched to from outside the loop.
3987///
3988/// Note that it is not valid to call this method on a loop without a
3989/// loop-invariant backedge-taken count (see
3990/// hasLoopInvariantBackedgeTakenCount).
3991///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003992const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00003993 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohmana1af7572009-04-30 20:47:05 +00003994}
3995
3996/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3997/// return the least SCEV value that is known never to be less than the
3998/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003999const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004000 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004001}
4002
Dan Gohman59ae6b92009-07-08 19:23:34 +00004003/// PushLoopPHIs - Push PHI nodes in the header of the given loop
4004/// onto the given Worklist.
4005static void
4006PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4007 BasicBlock *Header = L->getHeader();
4008
4009 // Push all Loop-header PHIs onto the Worklist stack.
4010 for (BasicBlock::iterator I = Header->begin();
4011 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4012 Worklist.push_back(PN);
4013}
4014
Dan Gohmana1af7572009-04-30 20:47:05 +00004015const ScalarEvolution::BackedgeTakenInfo &
4016ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004017 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004018 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00004019 // update the value. The temporary CouldNotCompute value tells SCEV
4020 // code elsewhere that it shouldn't attempt to request a new
4021 // backedge-taken count, which could result in infinite recursion.
Dan Gohman77a2c4c2011-05-09 18:44:09 +00004022 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick5116ff62011-07-26 17:19:55 +00004023 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnerf1859892011-01-09 02:16:18 +00004024 if (!Pair.second)
4025 return Pair.first->second;
Dan Gohman01ecca22009-04-27 20:16:15 +00004026
Andrew Trick5116ff62011-07-26 17:19:55 +00004027 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4028 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4029 // must be cleared in this scope.
4030 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4031
4032 if (Result.getExact(this) != getCouldNotCompute()) {
4033 assert(isLoopInvariant(Result.getExact(this), L) &&
4034 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnerf1859892011-01-09 02:16:18 +00004035 "Computed backedge-taken count isn't loop invariant for loop!");
4036 ++NumTripCountsComputed;
Andrew Trick5116ff62011-07-26 17:19:55 +00004037 }
4038 else if (Result.getMax(this) == getCouldNotCompute() &&
4039 isa<PHINode>(L->getHeader()->begin())) {
4040 // Only count loops that have phi nodes as not being computable.
4041 ++NumTripCountsNotComputed;
Chris Lattnerf1859892011-01-09 02:16:18 +00004042 }
Dan Gohmana1af7572009-04-30 20:47:05 +00004043
Chris Lattnerf1859892011-01-09 02:16:18 +00004044 // Now that we know more about the trip count for this loop, forget any
4045 // existing SCEV values for PHI nodes in this loop since they are only
4046 // conservative estimates made without the benefit of trip count
4047 // information. This is similar to the code in forgetLoop, except that
4048 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick5116ff62011-07-26 17:19:55 +00004049 if (Result.hasAnyInfo()) {
Chris Lattnerf1859892011-01-09 02:16:18 +00004050 SmallVector<Instruction *, 16> Worklist;
4051 PushLoopPHIs(L, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004052
Chris Lattnerf1859892011-01-09 02:16:18 +00004053 SmallPtrSet<Instruction *, 8> Visited;
4054 while (!Worklist.empty()) {
4055 Instruction *I = Worklist.pop_back_val();
4056 if (!Visited.insert(I)) continue;
Dan Gohman59ae6b92009-07-08 19:23:34 +00004057
Chris Lattnerf1859892011-01-09 02:16:18 +00004058 ValueExprMapType::iterator It =
4059 ValueExprMap.find(static_cast<Value *>(I));
4060 if (It != ValueExprMap.end()) {
4061 const SCEV *Old = It->second;
Dan Gohman6678e7b2010-11-17 02:44:44 +00004062
Chris Lattnerf1859892011-01-09 02:16:18 +00004063 // SCEVUnknown for a PHI either means that it has an unrecognized
4064 // structure, or it's a PHI that's in the progress of being computed
4065 // by createNodeForPHI. In the former case, additional loop trip
4066 // count information isn't going to change anything. In the later
4067 // case, createNodeForPHI will perform the necessary updates on its
4068 // own when it gets to that point.
4069 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4070 forgetMemoizedResults(Old);
4071 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004072 }
Chris Lattnerf1859892011-01-09 02:16:18 +00004073 if (PHINode *PN = dyn_cast<PHINode>(I))
4074 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004075 }
Chris Lattnerf1859892011-01-09 02:16:18 +00004076
4077 PushDefUseChildren(I, Worklist);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004078 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004079 }
Dan Gohman308bec32011-04-25 22:48:29 +00004080
4081 // Re-lookup the insert position, since the call to
4082 // ComputeBackedgeTakenCount above could result in a
4083 // recusive call to getBackedgeTakenInfo (on a different
4084 // loop), which would invalidate the iterator computed
4085 // earlier.
4086 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattner53e677a2004-04-02 20:23:17 +00004087}
4088
Dan Gohman4c7279a2009-10-31 15:04:55 +00004089/// forgetLoop - This method should be called by the client when it has
4090/// changed a loop in a way that may effect ScalarEvolution's ability to
4091/// compute a trip count, or if the loop is deleted.
4092void ScalarEvolution::forgetLoop(const Loop *L) {
4093 // Drop any stored trip count value.
Andrew Trick5116ff62011-07-26 17:19:55 +00004094 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4095 BackedgeTakenCounts.find(L);
4096 if (BTCPos != BackedgeTakenCounts.end()) {
4097 BTCPos->second.clear();
4098 BackedgeTakenCounts.erase(BTCPos);
4099 }
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00004100
Dan Gohman4c7279a2009-10-31 15:04:55 +00004101 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00004102 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00004103 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00004104
Dan Gohman59ae6b92009-07-08 19:23:34 +00004105 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00004106 while (!Worklist.empty()) {
4107 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00004108 if (!Visited.insert(I)) continue;
4109
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004110 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4111 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00004112 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004113 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00004114 if (PHINode *PN = dyn_cast<PHINode>(I))
4115 ConstantEvolutionLoopExitValue.erase(PN);
4116 }
4117
4118 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00004119 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00004120
4121 // Forget all contained loops too, to avoid dangling entries in the
4122 // ValuesAtScopes map.
4123 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4124 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00004125}
4126
Eric Christophere6cbfa62010-07-29 01:25:38 +00004127/// forgetValue - This method should be called by the client when it has
4128/// changed a value in a way that may effect its value, or which may
4129/// disconnect it from a def-use chain linking it to a loop.
4130void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00004131 Instruction *I = dyn_cast<Instruction>(V);
4132 if (!I) return;
4133
4134 // Drop information about expressions based on loop-header PHIs.
4135 SmallVector<Instruction *, 16> Worklist;
4136 Worklist.push_back(I);
4137
4138 SmallPtrSet<Instruction *, 8> Visited;
4139 while (!Worklist.empty()) {
4140 I = Worklist.pop_back_val();
4141 if (!Visited.insert(I)) continue;
4142
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004143 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4144 if (It != ValueExprMap.end()) {
Dan Gohman56a75682010-11-17 23:28:48 +00004145 forgetMemoizedResults(It->second);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00004146 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00004147 if (PHINode *PN = dyn_cast<PHINode>(I))
4148 ConstantEvolutionLoopExitValue.erase(PN);
4149 }
4150
4151 PushDefUseChildren(I, Worklist);
4152 }
4153}
4154
Andrew Trick5116ff62011-07-26 17:19:55 +00004155/// getExact - Get the exact loop backedge taken count considering all loop
4156/// exits. If all exits are computable, this is the minimum computed count.
4157const SCEV *
4158ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4159 // If any exits were not computable, the loop is not computable.
4160 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4161
4162 // We need at least one computable exit.
Andrew Trickfcb43562011-08-02 04:23:35 +00004163 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick5116ff62011-07-26 17:19:55 +00004164 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4165
4166 const SCEV *BECount = 0;
4167 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4168 ENT != 0; ENT = ENT->getNextExit()) {
4169
4170 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4171
4172 if (!BECount)
4173 BECount = ENT->ExactNotTaken;
4174 else
4175 BECount = SE->getUMinFromMismatchedTypes(BECount, ENT->ExactNotTaken);
4176 }
Andrew Trick252ef7a2011-09-02 21:20:46 +00004177 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick5116ff62011-07-26 17:19:55 +00004178 return BECount;
4179}
4180
4181/// getExact - Get the exact not taken count for this loop exit.
4182const SCEV *
Andrew Trickfcb43562011-08-02 04:23:35 +00004183ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick5116ff62011-07-26 17:19:55 +00004184 ScalarEvolution *SE) const {
4185 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4186 ENT != 0; ENT = ENT->getNextExit()) {
4187
Andrew Trickfcb43562011-08-02 04:23:35 +00004188 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick5116ff62011-07-26 17:19:55 +00004189 return ENT->ExactNotTaken;
4190 }
4191 return SE->getCouldNotCompute();
4192}
4193
4194/// getMax - Get the max backedge taken count for the loop.
4195const SCEV *
4196ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4197 return Max ? Max : SE->getCouldNotCompute();
4198}
4199
4200/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4201/// computable exit into a persistent ExitNotTakenInfo array.
4202ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4203 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4204 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4205
4206 if (!Complete)
4207 ExitNotTaken.setIncomplete();
4208
4209 unsigned NumExits = ExitCounts.size();
4210 if (NumExits == 0) return;
4211
Andrew Trickfcb43562011-08-02 04:23:35 +00004212 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick5116ff62011-07-26 17:19:55 +00004213 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4214 if (NumExits == 1) return;
4215
4216 // Handle the rare case of multiple computable exits.
4217 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4218
4219 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4220 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4221 PrevENT->setNextExit(ENT);
Andrew Trickfcb43562011-08-02 04:23:35 +00004222 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick5116ff62011-07-26 17:19:55 +00004223 ENT->ExactNotTaken = ExitCounts[i].second;
4224 }
4225}
4226
4227/// clear - Invalidate this result and free the ExitNotTakenInfo array.
4228void ScalarEvolution::BackedgeTakenInfo::clear() {
Andrew Trickfcb43562011-08-02 04:23:35 +00004229 ExitNotTaken.ExitingBlock = 0;
Andrew Trick5116ff62011-07-26 17:19:55 +00004230 ExitNotTaken.ExactNotTaken = 0;
4231 delete[] ExitNotTaken.getNextExit();
4232}
4233
Dan Gohman46bdfb02009-02-24 18:55:53 +00004234/// ComputeBackedgeTakenCount - Compute the number of times the backedge
4235/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00004236ScalarEvolution::BackedgeTakenInfo
4237ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00004238 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00004239 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00004240
Dan Gohmana334aa72009-06-22 00:31:57 +00004241 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004242 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5116ff62011-07-26 17:19:55 +00004243 bool CouldComputeBECount = true;
4244 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Dan Gohmana334aa72009-06-22 00:31:57 +00004245 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004246 ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
4247 if (EL.Exact == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00004248 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00004249 // we won't be able to compute an exact value for the loop.
Andrew Trick5116ff62011-07-26 17:19:55 +00004250 CouldComputeBECount = false;
4251 else
4252 ExitCounts.push_back(std::make_pair(ExitingBlocks[i], EL.Exact));
4253
Dan Gohman1c343752009-06-27 21:21:31 +00004254 if (MaxBECount == getCouldNotCompute())
Andrew Trick5116ff62011-07-26 17:19:55 +00004255 MaxBECount = EL.Max;
4256 else if (EL.Max != getCouldNotCompute())
4257 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, EL.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004258 }
4259
Andrew Trick5116ff62011-07-26 17:19:55 +00004260 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004261}
4262
Andrew Trick5116ff62011-07-26 17:19:55 +00004263/// ComputeExitLimit - Compute the number of times the backedge of the specified
4264/// loop will execute if it exits via the specified block.
4265ScalarEvolution::ExitLimit
4266ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohmana334aa72009-06-22 00:31:57 +00004267
4268 // Okay, we've chosen an exiting block. See what condition causes us to
4269 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00004270 //
4271 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00004272 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00004273 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004274 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00004275
Chris Lattner8b0e3602007-01-07 02:24:26 +00004276 // At this point, we know we have a conditional branch that determines whether
4277 // the loop is exited. However, we don't know if the branch is executed each
4278 // time through the loop. If not, then the execution count of the branch will
4279 // not be equal to the trip count of the loop.
4280 //
4281 // Currently we check for this by checking to see if the Exit branch goes to
4282 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00004283 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00004284 // loop header. This is common for un-rotated loops.
4285 //
4286 // If both of those tests fail, walk up the unique predecessor chain to the
4287 // header, stopping if there is an edge that doesn't exit the loop. If the
4288 // header is reached, the execution count of the branch will be equal to the
4289 // trip count of the loop.
4290 //
4291 // More extensive analysis could be done to handle more cases here.
4292 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00004293 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00004294 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00004295 ExitBr->getParent() != L->getHeader()) {
4296 // The simple checks failed, try climbing the unique predecessor chain
4297 // up to the header.
4298 bool Ok = false;
4299 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
4300 BasicBlock *Pred = BB->getUniquePredecessor();
4301 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00004302 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004303 TerminatorInst *PredTerm = Pred->getTerminator();
4304 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4305 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4306 if (PredSucc == BB)
4307 continue;
4308 // If the predecessor has a successor that isn't BB and isn't
4309 // outside the loop, assume the worst.
4310 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00004311 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004312 }
4313 if (Pred == L->getHeader()) {
4314 Ok = true;
4315 break;
4316 }
4317 BB = Pred;
4318 }
4319 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00004320 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004321 }
4322
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004323 // Proceed to the next level to examine the exit condition expression.
Andrew Trick5116ff62011-07-26 17:19:55 +00004324 return ComputeExitLimitFromCond(L, ExitBr->getCondition(),
4325 ExitBr->getSuccessor(0),
4326 ExitBr->getSuccessor(1));
Dan Gohmana334aa72009-06-22 00:31:57 +00004327}
4328
Andrew Trick5116ff62011-07-26 17:19:55 +00004329/// ComputeExitLimitFromCond - Compute the number of times the
Dan Gohmana334aa72009-06-22 00:31:57 +00004330/// backedge of the specified loop will execute if its exit condition
4331/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5116ff62011-07-26 17:19:55 +00004332ScalarEvolution::ExitLimit
4333ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4334 Value *ExitCond,
4335 BasicBlock *TBB,
4336 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004337 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00004338 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4339 if (BO->getOpcode() == Instruction::And) {
4340 // Recurse on the operands of the and.
Andrew Trick5116ff62011-07-26 17:19:55 +00004341 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4342 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004343 const SCEV *BECount = getCouldNotCompute();
4344 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004345 if (L->contains(TBB)) {
4346 // Both conditions must be true for the loop to continue executing.
4347 // Choose the less conservative count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004348 if (EL0.Exact == getCouldNotCompute() ||
4349 EL1.Exact == getCouldNotCompute())
Dan Gohman1c343752009-06-27 21:21:31 +00004350 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004351 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004352 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4353 if (EL0.Max == getCouldNotCompute())
4354 MaxBECount = EL1.Max;
4355 else if (EL1.Max == getCouldNotCompute())
4356 MaxBECount = EL0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004357 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004358 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004359 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004360 // Both conditions must be true at the same time for the loop to exit.
4361 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004362 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick5116ff62011-07-26 17:19:55 +00004363 if (EL0.Max == EL1.Max)
4364 MaxBECount = EL0.Max;
4365 if (EL0.Exact == EL1.Exact)
4366 BECount = EL0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004367 }
4368
Andrew Trick5116ff62011-07-26 17:19:55 +00004369 return ExitLimit(BECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004370 }
4371 if (BO->getOpcode() == Instruction::Or) {
4372 // Recurse on the operands of the or.
Andrew Trick5116ff62011-07-26 17:19:55 +00004373 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4374 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00004375 const SCEV *BECount = getCouldNotCompute();
4376 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00004377 if (L->contains(FBB)) {
4378 // Both conditions must be false for the loop to continue executing.
4379 // Choose the less conservative count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004380 if (EL0.Exact == getCouldNotCompute() ||
4381 EL1.Exact == getCouldNotCompute())
Dan Gohman1c343752009-06-27 21:21:31 +00004382 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00004383 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004384 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4385 if (EL0.Max == getCouldNotCompute())
4386 MaxBECount = EL1.Max;
4387 else if (EL1.Max == getCouldNotCompute())
4388 MaxBECount = EL0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00004389 else
Andrew Trick5116ff62011-07-26 17:19:55 +00004390 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00004391 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00004392 // Both conditions must be false at the same time for the loop to exit.
4393 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00004394 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick5116ff62011-07-26 17:19:55 +00004395 if (EL0.Max == EL1.Max)
4396 MaxBECount = EL0.Max;
4397 if (EL0.Exact == EL1.Exact)
4398 BECount = EL0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00004399 }
4400
Andrew Trick5116ff62011-07-26 17:19:55 +00004401 return ExitLimit(BECount, MaxBECount);
Dan Gohmana334aa72009-06-22 00:31:57 +00004402 }
4403 }
4404
4405 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00004406 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00004407 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Andrew Trick5116ff62011-07-26 17:19:55 +00004408 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004409
Dan Gohman00cb5b72010-02-19 18:12:07 +00004410 // Check for a constant condition. These are normally stripped out by
4411 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4412 // preserve the CFG and is temporarily leaving constant conditions
4413 // in place.
4414 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4415 if (L->contains(FBB) == !CI->getZExtValue())
4416 // The backedge is always taken.
4417 return getCouldNotCompute();
4418 else
4419 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00004420 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00004421 }
4422
Eli Friedman361e54d2009-05-09 12:32:42 +00004423 // If it's not an integer or pointer comparison then compute it the hard way.
Andrew Trick5116ff62011-07-26 17:19:55 +00004424 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmana334aa72009-06-22 00:31:57 +00004425}
4426
Andrew Trick5116ff62011-07-26 17:19:55 +00004427/// ComputeExitLimitFromICmp - Compute the number of times the
Dan Gohmana334aa72009-06-22 00:31:57 +00004428/// backedge of the specified loop will execute if its exit condition
4429/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
Andrew Trick5116ff62011-07-26 17:19:55 +00004430ScalarEvolution::ExitLimit
4431ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4432 ICmpInst *ExitCond,
4433 BasicBlock *TBB,
4434 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004435
Reid Spencere4d87aa2006-12-23 06:05:41 +00004436 // If the condition was exit on true, convert the condition to exit on false
4437 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00004438 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004439 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004440 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004441 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00004442
4443 // Handle common loops like: for (X = "string"; *X; ++X)
4444 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4445 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick5116ff62011-07-26 17:19:55 +00004446 ExitLimit ItCnt =
4447 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004448 if (ItCnt.hasAnyInfo())
4449 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00004450 }
4451
Dan Gohman0bba49c2009-07-07 17:06:11 +00004452 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4453 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00004454
4455 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00004456 LHS = getSCEVAtScope(LHS, L);
4457 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004458
Dan Gohman64a845e2009-06-24 04:48:43 +00004459 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004460 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00004461 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00004462 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00004463 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004464 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00004465 }
4466
Dan Gohman03557dc2010-05-03 16:35:17 +00004467 // Simplify the operands before analyzing them.
4468 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4469
Chris Lattner53e677a2004-04-02 20:23:17 +00004470 // If we have a comparison of a chrec against a constant, try to use value
4471 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00004472 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4473 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00004474 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00004475 // Form the constant range.
4476 ConstantRange CompRange(
4477 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004478
Dan Gohman0bba49c2009-07-07 17:06:11 +00004479 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00004480 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00004481 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004482
Chris Lattner53e677a2004-04-02 20:23:17 +00004483 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004484 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004485 // Convert to: while (X-Y != 0)
Andrew Trick5116ff62011-07-26 17:19:55 +00004486 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4487 if (EL.hasAnyInfo()) return EL;
Chris Lattner53e677a2004-04-02 20:23:17 +00004488 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004489 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004490 case ICmpInst::ICMP_EQ: { // while (X == Y)
4491 // Convert to: while (X-Y == 0)
Andrew Trick5116ff62011-07-26 17:19:55 +00004492 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4493 if (EL.hasAnyInfo()) return EL;
Chris Lattner53e677a2004-04-02 20:23:17 +00004494 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004495 }
4496 case ICmpInst::ICMP_SLT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004497 ExitLimit EL = HowManyLessThans(LHS, RHS, L, true);
4498 if (EL.hasAnyInfo()) return EL;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004499 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004500 }
4501 case ICmpInst::ICMP_SGT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004502 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
Dan Gohmana1af7572009-04-30 20:47:05 +00004503 getNotSCEV(RHS), L, true);
Andrew Trick5116ff62011-07-26 17:19:55 +00004504 if (EL.hasAnyInfo()) return EL;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004505 break;
4506 }
4507 case ICmpInst::ICMP_ULT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004508 ExitLimit EL = HowManyLessThans(LHS, RHS, L, false);
4509 if (EL.hasAnyInfo()) return EL;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004510 break;
4511 }
4512 case ICmpInst::ICMP_UGT: {
Andrew Trick5116ff62011-07-26 17:19:55 +00004513 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
Dan Gohmana1af7572009-04-30 20:47:05 +00004514 getNotSCEV(RHS), L, false);
Andrew Trick5116ff62011-07-26 17:19:55 +00004515 if (EL.hasAnyInfo()) return EL;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004516 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004517 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004518 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004519#if 0
David Greene25e0e872009-12-23 22:18:14 +00004520 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004521 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004522 dbgs() << "[unsigned] ";
4523 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004524 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004525 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004526#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004527 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004528 }
Andrew Trick5116ff62011-07-26 17:19:55 +00004529 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004530}
4531
Chris Lattner673e02b2004-10-12 01:49:27 +00004532static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004533EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4534 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004535 const SCEV *InVal = SE.getConstant(C);
4536 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004537 assert(isa<SCEVConstant>(Val) &&
4538 "Evaluation of SCEV at constant didn't fold correctly?");
4539 return cast<SCEVConstant>(Val)->getValue();
4540}
4541
4542/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4543/// and a GEP expression (missing the pointer index) indexing into it, return
4544/// the addressed element of the initializer or null if the index expression is
4545/// invalid.
4546static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004547GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004548 const std::vector<ConstantInt*> &Indices) {
4549 Constant *Init = GV->getInitializer();
4550 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004551 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004552 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4553 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4554 Init = cast<Constant>(CS->getOperand(Idx));
4555 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4556 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4557 Init = cast<Constant>(CA->getOperand(Idx));
4558 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004559 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004560 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004561 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004562 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004563 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004564 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004565 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004566 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004567 }
4568 return 0;
4569 } else {
4570 return 0; // Unknown initializer type
4571 }
4572 }
4573 return Init;
4574}
4575
Andrew Trick5116ff62011-07-26 17:19:55 +00004576/// ComputeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman46bdfb02009-02-24 18:55:53 +00004577/// 'icmp op load X, cst', try to see if we can compute the backedge
4578/// execution count.
Andrew Trick5116ff62011-07-26 17:19:55 +00004579ScalarEvolution::ExitLimit
4580ScalarEvolution::ComputeLoadConstantCompareExitLimit(
4581 LoadInst *LI,
4582 Constant *RHS,
4583 const Loop *L,
4584 ICmpInst::Predicate predicate) {
4585
Dan Gohman1c343752009-06-27 21:21:31 +00004586 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004587
4588 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004589 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004590 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004591 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004592
4593 // Make sure that it is really a constant global we are gepping, with an
4594 // initializer, and make sure the first IDX is really 0.
4595 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004596 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004597 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4598 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004599 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004600
4601 // Okay, we allow one non-constant index into the GEP instruction.
4602 Value *VarIdx = 0;
4603 std::vector<ConstantInt*> Indexes;
4604 unsigned VarIdxNum = 0;
4605 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4606 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4607 Indexes.push_back(CI);
4608 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004609 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004610 VarIdx = GEP->getOperand(i);
4611 VarIdxNum = i-2;
4612 Indexes.push_back(0);
4613 }
4614
4615 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4616 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004617 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004618 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004619
4620 // We can only recognize very limited forms of loop index expressions, in
4621 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004622 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004623 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004624 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4625 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004626 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004627
4628 unsigned MaxSteps = MaxBruteForceIterations;
4629 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004630 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004631 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004632 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004633
4634 // Form the GEP offset.
4635 Indexes[VarIdxNum] = Val;
4636
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004637 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004638 if (Result == 0) break; // Cannot compute!
4639
4640 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004641 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004642 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004643 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004644#if 0
David Greene25e0e872009-12-23 22:18:14 +00004645 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004646 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4647 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004648#endif
4649 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004650 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004651 }
4652 }
Dan Gohman1c343752009-06-27 21:21:31 +00004653 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004654}
4655
4656
Chris Lattner3221ad02004-04-17 22:58:41 +00004657/// CanConstantFold - Return true if we can constant fold an instruction of the
4658/// specified type, assuming that all operands were constants.
4659static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004660 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewycky614fef62011-10-22 19:58:20 +00004661 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4662 isa<LoadInst>(I))
Chris Lattner3221ad02004-04-17 22:58:41 +00004663 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004664
Chris Lattner3221ad02004-04-17 22:58:41 +00004665 if (const CallInst *CI = dyn_cast<CallInst>(I))
4666 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004667 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004668 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004669}
4670
Andrew Trick13d31e02011-10-05 03:25:31 +00004671/// Determine whether this instruction can constant evolve within this loop
4672/// assuming its operands can all constant evolve.
4673static bool canConstantEvolve(Instruction *I, const Loop *L) {
4674 // An instruction outside of the loop can't be derived from a loop PHI.
4675 if (!L->contains(I)) return false;
4676
4677 if (isa<PHINode>(I)) {
4678 if (L->getHeader() == I->getParent())
4679 return true;
4680 else
4681 // We don't currently keep track of the control flow needed to evaluate
4682 // PHIs, so we cannot handle PHIs inside of loops.
4683 return false;
4684 }
4685
4686 // If we won't be able to constant fold this expression even if the operands
4687 // are constants, bail early.
4688 return CanConstantFold(I);
4689}
4690
4691/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
4692/// recursing through each instruction operand until reaching a loop header phi.
4693static PHINode *
4694getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Trick28ab7db2011-10-05 05:58:49 +00004695 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick13d31e02011-10-05 03:25:31 +00004696
4697 // Otherwise, we can evaluate this instruction if all of its operands are
4698 // constant or derived from a PHI node themselves.
4699 PHINode *PHI = 0;
4700 for (Instruction::op_iterator OpI = UseInst->op_begin(),
4701 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
4702
4703 if (isa<Constant>(*OpI)) continue;
4704
4705 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
4706 if (!OpInst || !canConstantEvolve(OpInst, L)) return 0;
4707
4708 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trickef8a4c22011-10-05 22:06:53 +00004709 if (!P)
4710 // If this operand is already visited, reuse the prior result.
4711 // We may have P != PHI if this is the deepest point at which the
4712 // inconsistent paths meet.
4713 P = PHIMap.lookup(OpInst);
4714 if (!P) {
4715 // Recurse and memoize the results, whether a phi is found or not.
4716 // This recursive call invalidates pointers into PHIMap.
4717 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
4718 PHIMap[OpInst] = P;
Andrew Trick28ab7db2011-10-05 05:58:49 +00004719 }
Andrew Trick28ab7db2011-10-05 05:58:49 +00004720 if (P == 0) return 0; // Not evolving from PHI
4721 if (PHI && PHI != P) return 0; // Evolving from multiple different PHIs.
4722 PHI = P;
Andrew Trick13d31e02011-10-05 03:25:31 +00004723 }
4724 // This is a expression evolving from a constant PHI!
4725 return PHI;
4726}
4727
Chris Lattner3221ad02004-04-17 22:58:41 +00004728/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4729/// in the loop that V is derived from. We allow arbitrary operations along the
4730/// way, but the operands of an operation must either be constants or a value
4731/// derived from a constant PHI. If this expression does not fit with these
4732/// constraints, return null.
4733static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004734 Instruction *I = dyn_cast<Instruction>(V);
Andrew Trick13d31e02011-10-05 03:25:31 +00004735 if (I == 0 || !canConstantEvolve(I, L)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004736
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004737 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Andrew Trick13d31e02011-10-05 03:25:31 +00004738 return PN;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004739 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004740
Andrew Trick13d31e02011-10-05 03:25:31 +00004741 // Record non-constant instructions contained by the loop.
Andrew Trick28ab7db2011-10-05 05:58:49 +00004742 DenseMap<Instruction *, PHINode *> PHIMap;
4743 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattner3221ad02004-04-17 22:58:41 +00004744}
4745
4746/// EvaluateExpression - Given an expression that passes the
4747/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4748/// in the loop has the value PHIVal. If we can't fold this expression for some
4749/// reason, return null.
Andrew Trick13d31e02011-10-05 03:25:31 +00004750static Constant *EvaluateExpression(Value *V, const Loop *L,
4751 DenseMap<Instruction *, Constant *> &Vals,
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004752 const TargetData *TD) {
Andrew Trick28ab7db2011-10-05 05:58:49 +00004753 // Convenient constant check, but redundant for recursive calls.
Reid Spencere8404342004-07-18 00:18:30 +00004754 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewycky614fef62011-10-22 19:58:20 +00004755 Instruction *I = dyn_cast<Instruction>(V);
4756 if (!I) return 0;
Andrew Trick13d31e02011-10-05 03:25:31 +00004757
Andrew Trick13d31e02011-10-05 03:25:31 +00004758 if (Constant *C = Vals.lookup(I)) return C;
4759
Nick Lewycky614fef62011-10-22 19:58:20 +00004760 // An instruction inside the loop depends on a value outside the loop that we
4761 // weren't given a mapping for, or a value such as a call inside the loop.
4762 if (!canConstantEvolve(I, L)) return 0;
4763
4764 // An unmapped PHI can be due to a branch or another loop inside this loop,
4765 // or due to this not being the initial iteration through a loop where we
4766 // couldn't compute the evolution of this particular PHI last time.
4767 if (isa<PHINode>(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004768
Dan Gohman9d4588f2010-06-22 13:15:46 +00004769 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004770
4771 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Trick28ab7db2011-10-05 05:58:49 +00004772 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
4773 if (!Operand) {
Nick Lewycky4c7f1ca2011-10-14 09:38:46 +00004774 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
4775 if (!Operands[i]) return 0;
Andrew Trick28ab7db2011-10-05 05:58:49 +00004776 continue;
4777 }
4778 Constant *C = EvaluateExpression(Operand, L, Vals, TD);
4779 Vals[Operand] = C;
4780 if (!C) return 0;
4781 Operands[i] = C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004782 }
4783
Nick Lewycky614fef62011-10-22 19:58:20 +00004784 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004785 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004786 Operands[1], TD);
Nick Lewycky614fef62011-10-22 19:58:20 +00004787 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4788 if (!LI->isVolatile())
4789 return ConstantFoldLoadFromConstPtr(Operands[0], TD);
4790 }
Jay Foad1d2f5692011-07-19 13:32:40 +00004791 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004792}
4793
4794/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4795/// in the header of its containing loop, we know the loop executes a
4796/// constant number of times, and the PHI node is just a recurrence
4797/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004798Constant *
4799ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004800 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004801 const Loop *L) {
Dan Gohman77a2c4c2011-05-09 18:44:09 +00004802 DenseMap<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004803 ConstantEvolutionLoopExitValue.find(PN);
4804 if (I != ConstantEvolutionLoopExitValue.end())
4805 return I->second;
4806
Dan Gohmane0567812010-04-08 23:03:40 +00004807 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004808 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4809
4810 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4811
Andrew Trick13d31e02011-10-05 03:25:31 +00004812 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewycky614fef62011-10-22 19:58:20 +00004813 BasicBlock *Header = L->getHeader();
4814 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick13d31e02011-10-05 03:25:31 +00004815
Chris Lattner3221ad02004-04-17 22:58:41 +00004816 // Since the loop is canonicalized, the PHI node must have two entries. One
4817 // entry must be a constant (coming in from outside of the loop), and the
4818 // second must be derived from the same PHI.
4819 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Nick Lewycky614fef62011-10-22 19:58:20 +00004820 PHINode *PHI = 0;
4821 for (BasicBlock::iterator I = Header->begin();
4822 (PHI = dyn_cast<PHINode>(I)); ++I) {
4823 Constant *StartCST =
4824 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
4825 if (StartCST == 0) continue;
4826 CurrentIterVals[PHI] = StartCST;
4827 }
4828 if (!CurrentIterVals.count(PN))
4829 return RetVal = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004830
4831 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Chris Lattner3221ad02004-04-17 22:58:41 +00004832
4833 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004834 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004835 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004836
Dan Gohman46bdfb02009-02-24 18:55:53 +00004837 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004838 unsigned IterationNum = 0;
Andrew Trick13d31e02011-10-05 03:25:31 +00004839 for (; ; ++IterationNum) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004840 if (IterationNum == NumIterations)
Andrew Trick13d31e02011-10-05 03:25:31 +00004841 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattner3221ad02004-04-17 22:58:41 +00004842
Nick Lewycky614fef62011-10-22 19:58:20 +00004843 // Compute the value of the PHIs for the next iteration.
Andrew Trick13d31e02011-10-05 03:25:31 +00004844 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewycky614fef62011-10-22 19:58:20 +00004845 DenseMap<Instruction *, Constant *> NextIterVals;
Andrew Trick13d31e02011-10-05 03:25:31 +00004846 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004847 if (NextPHI == 0)
4848 return 0; // Couldn't evaluate!
Andrew Trick13d31e02011-10-05 03:25:31 +00004849 NextIterVals[PN] = NextPHI;
Nick Lewycky614fef62011-10-22 19:58:20 +00004850
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004851 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
4852
Nick Lewycky614fef62011-10-22 19:58:20 +00004853 // Also evaluate the other PHI nodes. However, we don't get to stop if we
4854 // cease to be able to evaluate one of them or if they stop evolving,
4855 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd7ecff42011-11-12 03:09:12 +00004856 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Nick Lewycky614fef62011-10-22 19:58:20 +00004857 for (DenseMap<Instruction *, Constant *>::const_iterator
4858 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
4859 PHINode *PHI = dyn_cast<PHINode>(I->first);
Nick Lewycky5bef0eb2011-10-24 05:51:01 +00004860 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Nick Lewyckyd7ecff42011-11-12 03:09:12 +00004861 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
4862 }
4863 // We use two distinct loops because EvaluateExpression may invalidate any
4864 // iterators into CurrentIterVals.
4865 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
4866 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
4867 PHINode *PHI = I->first;
Nick Lewycky614fef62011-10-22 19:58:20 +00004868 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004869 if (!NextPHI) { // Not already computed.
4870 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
4871 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD);
4872 }
4873 if (NextPHI != I->second)
4874 StoppedEvolving = false;
Nick Lewycky614fef62011-10-22 19:58:20 +00004875 }
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004876
4877 // If all entries in CurrentIterVals == NextIterVals then we can stop
4878 // iterating, the loop can't continue to change.
4879 if (StoppedEvolving)
4880 return RetVal = CurrentIterVals[PN];
4881
Andrew Trick13d31e02011-10-05 03:25:31 +00004882 CurrentIterVals.swap(NextIterVals);
Chris Lattner3221ad02004-04-17 22:58:41 +00004883 }
4884}
4885
Andrew Trick5116ff62011-07-26 17:19:55 +00004886/// ComputeExitCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004887/// constant number of times (the condition evolves only from constants),
4888/// try to evaluate a few iterations of the loop until we get the exit
4889/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004890/// evaluate the trip count of the loop, return getCouldNotCompute().
Nick Lewycky614fef62011-10-22 19:58:20 +00004891const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
4892 Value *Cond,
4893 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004894 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004895 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004896
Dan Gohmanb92654d2010-06-19 14:17:24 +00004897 // If the loop is canonicalized, the PHI will have exactly two entries.
4898 // That's the only form we support here.
4899 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4900
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004901 DenseMap<Instruction *, Constant *> CurrentIterVals;
4902 BasicBlock *Header = L->getHeader();
4903 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
4904
Dan Gohmanb92654d2010-06-19 14:17:24 +00004905 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004906 // second must be derived from the same PHI.
4907 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004908 PHINode *PHI = 0;
4909 for (BasicBlock::iterator I = Header->begin();
4910 (PHI = dyn_cast<PHINode>(I)); ++I) {
4911 Constant *StartCST =
4912 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
4913 if (StartCST == 0) continue;
4914 CurrentIterVals[PHI] = StartCST;
4915 }
4916 if (!CurrentIterVals.count(PN))
4917 return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004918
4919 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4920 // the loop symbolically to determine when the condition gets a value of
4921 // "ExitWhen".
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004922
4923 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4924 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004925 ConstantInt *CondVal =
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004926 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L,
4927 CurrentIterVals, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004928
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004929 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004930 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004931
Reid Spencere8019bb2007-03-01 07:25:48 +00004932 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004933 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004934 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004935 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004936
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004937 // Update all the PHI nodes for the next iteration.
4938 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd7ecff42011-11-12 03:09:12 +00004939
4940 // Create a list of which PHIs we need to compute. We want to do this before
4941 // calling EvaluateExpression on them because that may invalidate iterators
4942 // into CurrentIterVals.
4943 SmallVector<PHINode *, 8> PHIsToCompute;
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004944 for (DenseMap<Instruction *, Constant *>::const_iterator
4945 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
4946 PHINode *PHI = dyn_cast<PHINode>(I->first);
4947 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd7ecff42011-11-12 03:09:12 +00004948 PHIsToCompute.push_back(PHI);
4949 }
4950 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
4951 E = PHIsToCompute.end(); I != E; ++I) {
4952 PHINode *PHI = *I;
Duncan Sandsf8a9eb12011-10-25 12:28:52 +00004953 Constant *&NextPHI = NextIterVals[PHI];
4954 if (NextPHI) continue; // Already computed!
4955
4956 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
4957 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD);
4958 }
4959 CurrentIterVals.swap(NextIterVals);
Chris Lattner7980fb92004-04-17 18:36:24 +00004960 }
4961
4962 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004963 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004964}
4965
Dan Gohmane7125f42009-09-03 15:00:26 +00004966/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004967/// at the specified scope in the program. The L value specifies a loop
4968/// nest to evaluate the expression at, where null is the top-level or a
4969/// specified loop is immediately inside of the loop.
4970///
4971/// This method can be used to compute the exit value for a variable defined
4972/// in a loop by querying what the value will hold in the parent loop.
4973///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004974/// In the case that a relevant loop exit value cannot be computed, the
4975/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004976const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004977 // Check to see if we've folded this expression at this loop before.
4978 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4979 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4980 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4981 if (!Pair.second)
4982 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004983
Dan Gohman42214892009-08-31 21:15:23 +00004984 // Otherwise compute it.
4985 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004986 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004987 return C;
4988}
4989
Nick Lewycky614fef62011-10-22 19:58:20 +00004990/// This builds up a Constant using the ConstantExpr interface. That way, we
4991/// will return Constants for objects which aren't represented by a
4992/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
4993/// Returns NULL if the SCEV isn't representable as a Constant.
4994static Constant *BuildConstantFromSCEV(const SCEV *V) {
4995 switch (V->getSCEVType()) {
4996 default: // TODO: smax, umax.
4997 case scCouldNotCompute:
4998 case scAddRecExpr:
4999 break;
5000 case scConstant:
5001 return cast<SCEVConstant>(V)->getValue();
5002 case scUnknown:
5003 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5004 case scSignExtend: {
5005 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5006 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5007 return ConstantExpr::getSExt(CastOp, SS->getType());
5008 break;
5009 }
5010 case scZeroExtend: {
5011 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5012 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5013 return ConstantExpr::getZExt(CastOp, SZ->getType());
5014 break;
5015 }
5016 case scTruncate: {
5017 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5018 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5019 return ConstantExpr::getTrunc(CastOp, ST->getType());
5020 break;
5021 }
5022 case scAddExpr: {
5023 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5024 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5025 if (C->getType()->isPointerTy())
5026 C = ConstantExpr::getBitCast(C, Type::getInt8PtrTy(C->getContext()));
5027 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5028 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5029 if (!C2) return 0;
5030
5031 // First pointer!
5032 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5033 std::swap(C, C2);
5034 // The offsets have been converted to bytes. We can add bytes to an
5035 // i8* by GEP with the byte count in the first index.
5036 C = ConstantExpr::getBitCast(C,Type::getInt8PtrTy(C->getContext()));
5037 }
5038
5039 // Don't bother trying to sum two pointers. We probably can't
5040 // statically compute a load that results from it anyway.
5041 if (C2->getType()->isPointerTy())
5042 return 0;
5043
5044 if (C->getType()->isPointerTy()) {
5045 if (cast<PointerType>(C->getType())->getElementType()->isStructTy())
5046 C2 = ConstantExpr::getIntegerCast(
5047 C2, Type::getInt32Ty(C->getContext()), true);
5048 C = ConstantExpr::getGetElementPtr(C, C2);
5049 } else
5050 C = ConstantExpr::getAdd(C, C2);
5051 }
5052 return C;
5053 }
5054 break;
5055 }
5056 case scMulExpr: {
5057 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5058 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5059 // Don't bother with pointers at all.
5060 if (C->getType()->isPointerTy()) return 0;
5061 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5062 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
5063 if (!C2 || C2->getType()->isPointerTy()) return 0;
5064 C = ConstantExpr::getMul(C, C2);
5065 }
5066 return C;
5067 }
5068 break;
5069 }
5070 case scUDivExpr: {
5071 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5072 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5073 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5074 if (LHS->getType() == RHS->getType())
5075 return ConstantExpr::getUDiv(LHS, RHS);
5076 break;
5077 }
5078 }
5079 return 0;
5080}
5081
Dan Gohman42214892009-08-31 21:15:23 +00005082const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00005083 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005084
Nick Lewycky3e630762008-02-20 06:48:22 +00005085 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00005086 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00005087 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00005088 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005089 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00005090 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5091 if (PHINode *PN = dyn_cast<PHINode>(I))
5092 if (PN->getParent() == LI->getHeader()) {
5093 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00005094 // to see if the loop that contains it has a known backedge-taken
5095 // count. If so, we may be able to force computation of the exit
5096 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005097 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00005098 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00005099 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00005100 // Okay, we know how many times the containing loop executes. If
5101 // this is a constant evolving PHI node, get the final value at
5102 // the specified iteration number.
5103 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00005104 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00005105 LI);
Dan Gohman09987962009-06-29 21:31:18 +00005106 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00005107 }
5108 }
5109
Reid Spencer09906f32006-12-04 21:33:23 +00005110 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00005111 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00005112 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00005113 // result. This is particularly useful for computing loop exit values.
5114 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00005115 SmallVector<Constant *, 4> Operands;
5116 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00005117 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5118 Value *Op = I->getOperand(i);
5119 if (Constant *C = dyn_cast<Constant>(Op)) {
5120 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00005121 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00005122 }
Dan Gohman11046452010-06-29 23:43:06 +00005123
5124 // If any of the operands is non-constant and if they are
5125 // non-integer and non-pointer, don't even try to analyze them
5126 // with scev techniques.
5127 if (!isSCEVable(Op->getType()))
5128 return V;
5129
5130 const SCEV *OrigV = getSCEV(Op);
5131 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5132 MadeImprovement |= OrigV != OpV;
5133
Nick Lewycky614fef62011-10-22 19:58:20 +00005134 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohman11046452010-06-29 23:43:06 +00005135 if (!C) return V;
5136 if (C->getType() != Op->getType())
5137 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5138 Op->getType(),
5139 false),
5140 C, Op->getType());
5141 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00005142 }
Dan Gohman64a845e2009-06-24 04:48:43 +00005143
Dan Gohman11046452010-06-29 23:43:06 +00005144 // Check to see if getSCEVAtScope actually made an improvement.
5145 if (MadeImprovement) {
5146 Constant *C = 0;
5147 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5148 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
5149 Operands[0], Operands[1], TD);
Nick Lewycky614fef62011-10-22 19:58:20 +00005150 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5151 if (!LI->isVolatile())
5152 C = ConstantFoldLoadFromConstPtr(Operands[0], TD);
5153 } else
Dan Gohman11046452010-06-29 23:43:06 +00005154 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00005155 Operands, TD);
Dan Gohman11046452010-06-29 23:43:06 +00005156 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00005157 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00005158 }
Chris Lattner3221ad02004-04-17 22:58:41 +00005159 }
5160 }
5161
5162 // This is some other type of SCEVUnknown, just return it.
5163 return V;
5164 }
5165
Dan Gohman622ed672009-05-04 22:02:23 +00005166 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005167 // Avoid performing the look-up in the common case where the specified
5168 // expression has no loop-variant portions.
5169 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005170 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005171 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005172 // Okay, at least one of these operands is loop variant but might be
5173 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00005174 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5175 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00005176 NewOps.push_back(OpAtScope);
5177
5178 for (++i; i != e; ++i) {
5179 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005180 NewOps.push_back(OpAtScope);
5181 }
5182 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005183 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00005184 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005185 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00005186 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005187 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00005188 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005189 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00005190 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00005191 }
5192 }
5193 // If we got here, all operands are loop invariant.
5194 return Comm;
5195 }
5196
Dan Gohman622ed672009-05-04 22:02:23 +00005197 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005198 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5199 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00005200 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5201 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005202 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00005203 }
5204
5205 // If this is a loop recurrence for a loop that does not contain L, then we
5206 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00005207 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00005208 // First, attempt to evaluate each operand.
5209 // Avoid performing the look-up in the common case where the specified
5210 // expression has no loop-variant portions.
5211 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5212 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5213 if (OpAtScope == AddRec->getOperand(i))
5214 continue;
5215
5216 // Okay, at least one of these operands is loop variant but might be
5217 // foldable. Build a new instance of the folded commutative expression.
5218 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5219 AddRec->op_begin()+i);
5220 NewOps.push_back(OpAtScope);
5221 for (++i; i != e; ++i)
5222 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5223
Andrew Trick3f95c882011-04-27 01:21:25 +00005224 const SCEV *FoldedRec =
Andrew Trick3228cc22011-03-14 16:50:06 +00005225 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick3f95c882011-04-27 01:21:25 +00005226 AddRec->getNoWrapFlags(SCEV::FlagNW));
5227 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick104f4ad2011-04-27 05:42:17 +00005228 // The addrec may be folded to a nonrecurrence, for example, if the
5229 // induction variable is multiplied by zero after constant folding. Go
5230 // ahead and return the folded value.
Andrew Trick3f95c882011-04-27 01:21:25 +00005231 if (!AddRec)
5232 return FoldedRec;
Dan Gohman11046452010-06-29 23:43:06 +00005233 break;
5234 }
5235
5236 // If the scope is outside the addrec's loop, evaluate it by using the
5237 // loop exit value of the addrec.
5238 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005239 // To evaluate this recurrence, we need to know how many times the AddRec
5240 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005241 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00005242 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005243
Eli Friedmanb42a6262008-08-04 23:49:06 +00005244 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005245 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005246 }
Dan Gohman11046452010-06-29 23:43:06 +00005247
Dan Gohmand594e6f2009-05-24 23:25:42 +00005248 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00005249 }
5250
Dan Gohman622ed672009-05-04 22:02:23 +00005251 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005252 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00005253 if (Op == Cast->getOperand())
5254 return Cast; // must be loop invariant
5255 return getZeroExtendExpr(Op, Cast->getType());
5256 }
5257
Dan Gohman622ed672009-05-04 22:02:23 +00005258 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005259 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00005260 if (Op == Cast->getOperand())
5261 return Cast; // must be loop invariant
5262 return getSignExtendExpr(Op, Cast->getType());
5263 }
5264
Dan Gohman622ed672009-05-04 22:02:23 +00005265 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005266 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00005267 if (Op == Cast->getOperand())
5268 return Cast; // must be loop invariant
5269 return getTruncateExpr(Op, Cast->getType());
5270 }
5271
Torok Edwinc23197a2009-07-14 16:55:14 +00005272 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00005273 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00005274}
5275
Dan Gohman66a7e852009-05-08 20:38:54 +00005276/// getSCEVAtScope - This is a convenience function which does
5277/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00005278const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005279 return getSCEVAtScope(getSCEV(V), L);
5280}
5281
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005282/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5283/// following equation:
5284///
5285/// A * X = B (mod N)
5286///
5287/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5288/// A and B isn't important.
5289///
5290/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005291static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005292 ScalarEvolution &SE) {
5293 uint32_t BW = A.getBitWidth();
5294 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5295 assert(A != 0 && "A must be non-zero.");
5296
5297 // 1. D = gcd(A, N)
5298 //
5299 // The gcd of A and N may have only one prime factor: 2. The number of
5300 // trailing zeros in A is its multiplicity
5301 uint32_t Mult2 = A.countTrailingZeros();
5302 // D = 2^Mult2
5303
5304 // 2. Check if B is divisible by D.
5305 //
5306 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5307 // is not less than multiplicity of this prime factor for D.
5308 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005309 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005310
5311 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5312 // modulo (N / D).
5313 //
5314 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5315 // bit width during computations.
5316 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5317 APInt Mod(BW + 1, 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00005318 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00005319 APInt I = AD.multiplicativeInverse(Mod);
5320
5321 // 4. Compute the minimum unsigned root of the equation:
5322 // I * (B / D) mod (N / D)
5323 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5324
5325 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5326 // bits.
5327 return SE.getConstant(Result.trunc(BW));
5328}
Chris Lattner53e677a2004-04-02 20:23:17 +00005329
5330/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5331/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5332/// might be the same) or two SCEVCouldNotCompute objects.
5333///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005334static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00005335SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005336 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005337 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5338 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5339 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005340
Chris Lattner53e677a2004-04-02 20:23:17 +00005341 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00005342 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00005343 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005344 return std::make_pair(CNC, CNC);
5345 }
5346
Reid Spencere8019bb2007-03-01 07:25:48 +00005347 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00005348 const APInt &L = LC->getValue()->getValue();
5349 const APInt &M = MC->getValue()->getValue();
5350 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00005351 APInt Two(BitWidth, 2);
5352 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005353
Dan Gohman64a845e2009-06-24 04:48:43 +00005354 {
Reid Spencere8019bb2007-03-01 07:25:48 +00005355 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00005356 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00005357 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5358 // The B coefficient is M-N/2
5359 APInt B(M);
5360 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005361
Reid Spencere8019bb2007-03-01 07:25:48 +00005362 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00005363 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00005364
Reid Spencere8019bb2007-03-01 07:25:48 +00005365 // Compute the B^2-4ac term.
5366 APInt SqrtTerm(B);
5367 SqrtTerm *= B;
5368 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00005369
Reid Spencere8019bb2007-03-01 07:25:48 +00005370 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5371 // integer value or else APInt::sqrt() will assert.
5372 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005373
Dan Gohman64a845e2009-06-24 04:48:43 +00005374 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00005375 // The divisions must be performed as signed divisions.
5376 APInt NegB(-B);
Nick Lewycky1cbae182011-10-03 07:10:45 +00005377 APInt TwoA(A << 1);
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00005378 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00005379 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00005380 return std::make_pair(CNC, CNC);
5381 }
5382
Owen Andersone922c022009-07-22 00:24:57 +00005383 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00005384
5385 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00005386 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00005387 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00005388 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005389
Dan Gohman64a845e2009-06-24 04:48:43 +00005390 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00005391 SE.getConstant(Solution2));
Nick Lewycky1cbae182011-10-03 07:10:45 +00005392 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00005393}
5394
5395/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005396/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick3228cc22011-03-14 16:50:06 +00005397///
5398/// This is only used for loops with a "x != y" exit test. The exit condition is
5399/// now expressed as a single expression, V = x-y. So the exit test is
5400/// effectively V != 0. We know and take advantage of the fact that this
5401/// expression only being used in a comparison by zero context.
Andrew Trick5116ff62011-07-26 17:19:55 +00005402ScalarEvolution::ExitLimit
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005403ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005404 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00005405 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005406 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00005407 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00005408 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005409 }
5410
Dan Gohman35738ac2009-05-04 22:30:44 +00005411 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00005412 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005413 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005414
Chris Lattner7975e3e2011-01-09 22:39:48 +00005415 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5416 // the quadratic equation to solve it.
5417 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5418 std::pair<const SCEV *,const SCEV *> Roots =
5419 SolveQuadraticEquation(AddRec, *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00005420 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5421 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005422 if (R1 && R2) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00005423#if 0
David Greene25e0e872009-12-23 22:18:14 +00005424 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005425 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00005426#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00005427 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005428 if (ConstantInt *CB =
Chris Lattner53e1d452011-01-09 22:58:47 +00005429 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5430 R1->getValue(),
5431 R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005432 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005433 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick635f7182011-03-09 17:23:39 +00005434
Chris Lattner53e677a2004-04-02 20:23:17 +00005435 // We can only use this value if the chrec ends up with an exact zero
5436 // value at this index. When solving for "X*X != 5", for example, we
5437 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005438 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00005439 if (Val->isZero())
5440 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00005441 }
5442 }
Chris Lattner7975e3e2011-01-09 22:39:48 +00005443 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005444 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005445
Chris Lattner7975e3e2011-01-09 22:39:48 +00005446 // Otherwise we can only handle this if it is affine.
5447 if (!AddRec->isAffine())
5448 return getCouldNotCompute();
5449
5450 // If this is an affine expression, the execution count of this branch is
5451 // the minimum unsigned root of the following equation:
5452 //
5453 // Start + Step*N = 0 (mod 2^BW)
5454 //
5455 // equivalent to:
5456 //
5457 // Step*N = -Start (mod 2^BW)
5458 //
5459 // where BW is the common bit width of Start and Step.
5460
5461 // Get the initial value for the loop.
5462 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5463 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5464
5465 // For now we handle only constant steps.
Andrew Trick3228cc22011-03-14 16:50:06 +00005466 //
5467 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5468 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5469 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5470 // We have not yet seen any such cases.
Chris Lattner7975e3e2011-01-09 22:39:48 +00005471 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5472 if (StepC == 0)
5473 return getCouldNotCompute();
5474
Andrew Trick3228cc22011-03-14 16:50:06 +00005475 // For positive steps (counting up until unsigned overflow):
5476 // N = -Start/Step (as unsigned)
5477 // For negative steps (counting down to zero):
5478 // N = Start/-Step
5479 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005480 bool CountDown = StepC->getValue()->getValue().isNegative();
5481 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick3228cc22011-03-14 16:50:06 +00005482
5483 // Handle unitary steps, which cannot wraparound.
Andrew Trickdcfd4042011-03-14 17:28:02 +00005484 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5485 // N = Distance (as unsigned)
Nick Lewycky1cbae182011-10-03 07:10:45 +00005486 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
5487 ConstantRange CR = getUnsignedRange(Start);
5488 const SCEV *MaxBECount;
5489 if (!CountDown && CR.getUnsignedMin().isMinValue())
5490 // When counting up, the worst starting value is 1, not 0.
5491 MaxBECount = CR.getUnsignedMax().isMinValue()
5492 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
5493 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
5494 else
5495 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
5496 : -CR.getUnsignedMin());
5497 return ExitLimit(Distance, MaxBECount);
5498 }
Andrew Trick635f7182011-03-09 17:23:39 +00005499
Andrew Trickdcfd4042011-03-14 17:28:02 +00005500 // If the recurrence is known not to wraparound, unsigned divide computes the
5501 // back edge count. We know that the value will either become zero (and thus
5502 // the loop terminates), that the loop will terminate through some other exit
5503 // condition first, or that the loop has undefined behavior. This means
5504 // we can't "miss" the exit value, even with nonunit stride.
5505 //
5506 // FIXME: Prove that loops always exhibits *acceptable* undefined
5507 // behavior. Loops must exhibit defined behavior until a wrapped value is
5508 // actually used. So the trip count computed by udiv could be smaller than the
5509 // number of well-defined iterations.
5510 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5511 // FIXME: We really want an "isexact" bit for udiv.
5512 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Chris Lattner7975e3e2011-01-09 22:39:48 +00005513
5514 // Then, try to solve the above equation provided that Start is constant.
5515 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5516 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5517 -StartC->getValue()->getValue(),
5518 *this);
Dan Gohman1c343752009-06-27 21:21:31 +00005519 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005520}
5521
5522/// HowFarToNonZero - Return the number of times a backedge checking the
5523/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005524/// CouldNotCompute
Andrew Trick5116ff62011-07-26 17:19:55 +00005525ScalarEvolution::ExitLimit
Dan Gohmanf6d009f2010-02-24 17:31:30 +00005526ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005527 // Loops that look like: while (X == 0) are very strange indeed. We don't
5528 // handle them yet except for the trivial case. This could be expanded in the
5529 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005530
Chris Lattner53e677a2004-04-02 20:23:17 +00005531 // If the value is a constant, check to see if it is known to be non-zero
5532 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00005533 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00005534 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00005535 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00005536 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00005537 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005538
Chris Lattner53e677a2004-04-02 20:23:17 +00005539 // We could implement others, but I really doubt anyone writes loops like
5540 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00005541 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005542}
5543
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005544/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5545/// (which may not be an immediate predecessor) which has exactly one
5546/// successor from which BB is reachable, or null if no such block is
5547/// found.
5548///
Dan Gohman005752b2010-04-15 16:19:08 +00005549std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005550ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00005551 // If the block has a unique predecessor, then there is no path from the
5552 // predecessor to the block that does not go through the direct edge
5553 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005554 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00005555 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005556
5557 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00005558 // If the header has a unique predecessor outside the loop, it must be
5559 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005560 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00005561 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005562
Dan Gohman005752b2010-04-15 16:19:08 +00005563 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005564}
5565
Dan Gohman763bad12009-06-20 00:35:32 +00005566/// HasSameValue - SCEV structural equivalence is usually sufficient for
5567/// testing whether two expressions are equal, however for the purposes of
5568/// looking for a condition guarding a loop, it can be useful to be a little
5569/// more general, since a front-end may have replicated the controlling
5570/// expression.
5571///
Dan Gohman0bba49c2009-07-07 17:06:11 +00005572static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00005573 // Quick check to see if they are the same SCEV.
5574 if (A == B) return true;
5575
5576 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5577 // two different instructions with the same value. Check for this case.
5578 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5579 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5580 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5581 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00005582 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00005583 return true;
5584
5585 // Otherwise assume they may have a different value.
5586 return false;
5587}
5588
Dan Gohmane9796502010-04-24 01:28:42 +00005589/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5590/// predicate Pred. Return true iff any changes were made.
5591///
5592bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5593 const SCEV *&LHS, const SCEV *&RHS) {
5594 bool Changed = false;
5595
5596 // Canonicalize a constant to the right side.
5597 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5598 // Check for both operands constant.
5599 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5600 if (ConstantExpr::getICmp(Pred,
5601 LHSC->getValue(),
5602 RHSC->getValue())->isNullValue())
5603 goto trivially_false;
5604 else
5605 goto trivially_true;
5606 }
5607 // Otherwise swap the operands to put the constant on the right.
5608 std::swap(LHS, RHS);
5609 Pred = ICmpInst::getSwappedPredicate(Pred);
5610 Changed = true;
5611 }
5612
5613 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00005614 // addrec's loop, put the addrec on the left. Also make a dominance check,
5615 // as both operands could be addrecs loop-invariant in each other's loop.
5616 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5617 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00005618 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00005619 std::swap(LHS, RHS);
5620 Pred = ICmpInst::getSwappedPredicate(Pred);
5621 Changed = true;
5622 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00005623 }
Dan Gohmane9796502010-04-24 01:28:42 +00005624
5625 // If there's a constant operand, canonicalize comparisons with boundary
5626 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5627 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5628 const APInt &RA = RC->getValue()->getValue();
5629 switch (Pred) {
5630 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5631 case ICmpInst::ICMP_EQ:
5632 case ICmpInst::ICMP_NE:
5633 break;
5634 case ICmpInst::ICMP_UGE:
5635 if ((RA - 1).isMinValue()) {
5636 Pred = ICmpInst::ICMP_NE;
5637 RHS = getConstant(RA - 1);
5638 Changed = true;
5639 break;
5640 }
5641 if (RA.isMaxValue()) {
5642 Pred = ICmpInst::ICMP_EQ;
5643 Changed = true;
5644 break;
5645 }
5646 if (RA.isMinValue()) goto trivially_true;
5647
5648 Pred = ICmpInst::ICMP_UGT;
5649 RHS = getConstant(RA - 1);
5650 Changed = true;
5651 break;
5652 case ICmpInst::ICMP_ULE:
5653 if ((RA + 1).isMaxValue()) {
5654 Pred = ICmpInst::ICMP_NE;
5655 RHS = getConstant(RA + 1);
5656 Changed = true;
5657 break;
5658 }
5659 if (RA.isMinValue()) {
5660 Pred = ICmpInst::ICMP_EQ;
5661 Changed = true;
5662 break;
5663 }
5664 if (RA.isMaxValue()) goto trivially_true;
5665
5666 Pred = ICmpInst::ICMP_ULT;
5667 RHS = getConstant(RA + 1);
5668 Changed = true;
5669 break;
5670 case ICmpInst::ICMP_SGE:
5671 if ((RA - 1).isMinSignedValue()) {
5672 Pred = ICmpInst::ICMP_NE;
5673 RHS = getConstant(RA - 1);
5674 Changed = true;
5675 break;
5676 }
5677 if (RA.isMaxSignedValue()) {
5678 Pred = ICmpInst::ICMP_EQ;
5679 Changed = true;
5680 break;
5681 }
5682 if (RA.isMinSignedValue()) goto trivially_true;
5683
5684 Pred = ICmpInst::ICMP_SGT;
5685 RHS = getConstant(RA - 1);
5686 Changed = true;
5687 break;
5688 case ICmpInst::ICMP_SLE:
5689 if ((RA + 1).isMaxSignedValue()) {
5690 Pred = ICmpInst::ICMP_NE;
5691 RHS = getConstant(RA + 1);
5692 Changed = true;
5693 break;
5694 }
5695 if (RA.isMinSignedValue()) {
5696 Pred = ICmpInst::ICMP_EQ;
5697 Changed = true;
5698 break;
5699 }
5700 if (RA.isMaxSignedValue()) goto trivially_true;
5701
5702 Pred = ICmpInst::ICMP_SLT;
5703 RHS = getConstant(RA + 1);
5704 Changed = true;
5705 break;
5706 case ICmpInst::ICMP_UGT:
5707 if (RA.isMinValue()) {
5708 Pred = ICmpInst::ICMP_NE;
5709 Changed = true;
5710 break;
5711 }
5712 if ((RA + 1).isMaxValue()) {
5713 Pred = ICmpInst::ICMP_EQ;
5714 RHS = getConstant(RA + 1);
5715 Changed = true;
5716 break;
5717 }
5718 if (RA.isMaxValue()) goto trivially_false;
5719 break;
5720 case ICmpInst::ICMP_ULT:
5721 if (RA.isMaxValue()) {
5722 Pred = ICmpInst::ICMP_NE;
5723 Changed = true;
5724 break;
5725 }
5726 if ((RA - 1).isMinValue()) {
5727 Pred = ICmpInst::ICMP_EQ;
5728 RHS = getConstant(RA - 1);
5729 Changed = true;
5730 break;
5731 }
5732 if (RA.isMinValue()) goto trivially_false;
5733 break;
5734 case ICmpInst::ICMP_SGT:
5735 if (RA.isMinSignedValue()) {
5736 Pred = ICmpInst::ICMP_NE;
5737 Changed = true;
5738 break;
5739 }
5740 if ((RA + 1).isMaxSignedValue()) {
5741 Pred = ICmpInst::ICMP_EQ;
5742 RHS = getConstant(RA + 1);
5743 Changed = true;
5744 break;
5745 }
5746 if (RA.isMaxSignedValue()) goto trivially_false;
5747 break;
5748 case ICmpInst::ICMP_SLT:
5749 if (RA.isMaxSignedValue()) {
5750 Pred = ICmpInst::ICMP_NE;
5751 Changed = true;
5752 break;
5753 }
5754 if ((RA - 1).isMinSignedValue()) {
5755 Pred = ICmpInst::ICMP_EQ;
5756 RHS = getConstant(RA - 1);
5757 Changed = true;
5758 break;
5759 }
5760 if (RA.isMinSignedValue()) goto trivially_false;
5761 break;
5762 }
5763 }
5764
5765 // Check for obvious equality.
5766 if (HasSameValue(LHS, RHS)) {
5767 if (ICmpInst::isTrueWhenEqual(Pred))
5768 goto trivially_true;
5769 if (ICmpInst::isFalseWhenEqual(Pred))
5770 goto trivially_false;
5771 }
5772
Dan Gohman03557dc2010-05-03 16:35:17 +00005773 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5774 // adding or subtracting 1 from one of the operands.
5775 switch (Pred) {
5776 case ICmpInst::ICMP_SLE:
5777 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5778 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005779 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005780 Pred = ICmpInst::ICMP_SLT;
5781 Changed = true;
5782 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005783 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005784 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005785 Pred = ICmpInst::ICMP_SLT;
5786 Changed = true;
5787 }
5788 break;
5789 case ICmpInst::ICMP_SGE:
5790 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005791 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005792 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005793 Pred = ICmpInst::ICMP_SGT;
5794 Changed = true;
5795 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5796 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005797 SCEV::FlagNSW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005798 Pred = ICmpInst::ICMP_SGT;
5799 Changed = true;
5800 }
5801 break;
5802 case ICmpInst::ICMP_ULE:
5803 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005804 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005805 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005806 Pred = ICmpInst::ICMP_ULT;
5807 Changed = true;
5808 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005809 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005810 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005811 Pred = ICmpInst::ICMP_ULT;
5812 Changed = true;
5813 }
5814 break;
5815 case ICmpInst::ICMP_UGE:
5816 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005817 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005818 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005819 Pred = ICmpInst::ICMP_UGT;
5820 Changed = true;
5821 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005822 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick3228cc22011-03-14 16:50:06 +00005823 SCEV::FlagNUW);
Dan Gohman03557dc2010-05-03 16:35:17 +00005824 Pred = ICmpInst::ICMP_UGT;
5825 Changed = true;
5826 }
5827 break;
5828 default:
5829 break;
5830 }
5831
Dan Gohmane9796502010-04-24 01:28:42 +00005832 // TODO: More simplifications are possible here.
5833
5834 return Changed;
5835
5836trivially_true:
5837 // Return 0 == 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005838 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005839 Pred = ICmpInst::ICMP_EQ;
5840 return true;
5841
5842trivially_false:
5843 // Return 0 != 0.
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00005844 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohmane9796502010-04-24 01:28:42 +00005845 Pred = ICmpInst::ICMP_NE;
5846 return true;
5847}
5848
Dan Gohman85b05a22009-07-13 21:35:55 +00005849bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5850 return getSignedRange(S).getSignedMax().isNegative();
5851}
5852
5853bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5854 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5855}
5856
5857bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5858 return !getSignedRange(S).getSignedMin().isNegative();
5859}
5860
5861bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5862 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5863}
5864
5865bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5866 return isKnownNegative(S) || isKnownPositive(S);
5867}
5868
5869bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5870 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005871 // Canonicalize the inputs first.
5872 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5873
Dan Gohman53c66ea2010-04-11 22:16:48 +00005874 // If LHS or RHS is an addrec, check to see if the condition is true in
5875 // every iteration of the loop.
5876 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5877 if (isLoopEntryGuardedByCond(
5878 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5879 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005880 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005881 return true;
5882 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5883 if (isLoopEntryGuardedByCond(
5884 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5885 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005886 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005887 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005888
Dan Gohman53c66ea2010-04-11 22:16:48 +00005889 // Otherwise see what can be done with known constant ranges.
5890 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5891}
5892
5893bool
5894ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5895 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005896 if (HasSameValue(LHS, RHS))
5897 return ICmpInst::isTrueWhenEqual(Pred);
5898
Dan Gohman53c66ea2010-04-11 22:16:48 +00005899 // This code is split out from isKnownPredicate because it is called from
5900 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005901 switch (Pred) {
5902 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005903 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005904 break;
5905 case ICmpInst::ICMP_SGT:
5906 Pred = ICmpInst::ICMP_SLT;
5907 std::swap(LHS, RHS);
5908 case ICmpInst::ICMP_SLT: {
5909 ConstantRange LHSRange = getSignedRange(LHS);
5910 ConstantRange RHSRange = getSignedRange(RHS);
5911 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5912 return true;
5913 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5914 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005915 break;
5916 }
5917 case ICmpInst::ICMP_SGE:
5918 Pred = ICmpInst::ICMP_SLE;
5919 std::swap(LHS, RHS);
5920 case ICmpInst::ICMP_SLE: {
5921 ConstantRange LHSRange = getSignedRange(LHS);
5922 ConstantRange RHSRange = getSignedRange(RHS);
5923 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5924 return true;
5925 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5926 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005927 break;
5928 }
5929 case ICmpInst::ICMP_UGT:
5930 Pred = ICmpInst::ICMP_ULT;
5931 std::swap(LHS, RHS);
5932 case ICmpInst::ICMP_ULT: {
5933 ConstantRange LHSRange = getUnsignedRange(LHS);
5934 ConstantRange RHSRange = getUnsignedRange(RHS);
5935 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5936 return true;
5937 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5938 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005939 break;
5940 }
5941 case ICmpInst::ICMP_UGE:
5942 Pred = ICmpInst::ICMP_ULE;
5943 std::swap(LHS, RHS);
5944 case ICmpInst::ICMP_ULE: {
5945 ConstantRange LHSRange = getUnsignedRange(LHS);
5946 ConstantRange RHSRange = getUnsignedRange(RHS);
5947 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5948 return true;
5949 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5950 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005951 break;
5952 }
5953 case ICmpInst::ICMP_NE: {
5954 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5955 return true;
5956 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5957 return true;
5958
5959 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5960 if (isKnownNonZero(Diff))
5961 return true;
5962 break;
5963 }
5964 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005965 // The check at the top of the function catches the case where
5966 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005967 break;
5968 }
5969 return false;
5970}
5971
5972/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5973/// protected by a conditional between LHS and RHS. This is used to
5974/// to eliminate casts.
5975bool
5976ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5977 ICmpInst::Predicate Pred,
5978 const SCEV *LHS, const SCEV *RHS) {
5979 // Interpret a null as meaning no loop, where there is obviously no guard
5980 // (interprocedural conditions notwithstanding).
5981 if (!L) return true;
5982
5983 BasicBlock *Latch = L->getLoopLatch();
5984 if (!Latch)
5985 return false;
5986
5987 BranchInst *LoopContinuePredicate =
5988 dyn_cast<BranchInst>(Latch->getTerminator());
5989 if (!LoopContinuePredicate ||
5990 LoopContinuePredicate->isUnconditional())
5991 return false;
5992
Dan Gohmanaf08a362010-08-10 23:46:30 +00005993 return isImpliedCond(Pred, LHS, RHS,
5994 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005995 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005996}
5997
Dan Gohman3948d0b2010-04-11 19:27:13 +00005998/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005999/// by a conditional between LHS and RHS. This is used to help avoid max
6000/// expressions in loop trip counts, and to eliminate casts.
6001bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00006002ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6003 ICmpInst::Predicate Pred,
6004 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00006005 // Interpret a null as meaning no loop, where there is obviously no guard
6006 // (interprocedural conditions notwithstanding).
6007 if (!L) return false;
6008
Dan Gohman859b4822009-05-18 15:36:09 +00006009 // Starting at the loop predecessor, climb up the predecessor chain, as long
6010 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00006011 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00006012 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00006013 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00006014 Pair.first;
6015 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00006016
6017 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00006018 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00006019 if (!LoopEntryPredicate ||
6020 LoopEntryPredicate->isUnconditional())
6021 continue;
6022
Dan Gohmanaf08a362010-08-10 23:46:30 +00006023 if (isImpliedCond(Pred, LHS, RHS,
6024 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00006025 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00006026 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00006027 }
6028
Dan Gohman38372182008-08-12 20:17:31 +00006029 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00006030}
6031
Dan Gohman0f4b2852009-07-21 23:03:19 +00006032/// isImpliedCond - Test whether the condition described by Pred, LHS,
6033/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00006034bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00006035 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00006036 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00006037 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006038 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00006039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00006040 if (BO->getOpcode() == Instruction::And) {
6041 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00006042 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6043 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00006044 } else if (BO->getOpcode() == Instruction::Or) {
6045 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00006046 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6047 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00006048 }
6049 }
6050
Dan Gohmanaf08a362010-08-10 23:46:30 +00006051 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00006052 if (!ICI) return false;
6053
Dan Gohman85b05a22009-07-13 21:35:55 +00006054 // Bail if the ICmp's operands' types are wider than the needed type
6055 // before attempting to call getSCEV on them. This avoids infinite
6056 // recursion, since the analysis of widening casts can require loop
6057 // exit condition information for overflow checking, which would
6058 // lead back here.
6059 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00006060 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00006061 return false;
6062
Dan Gohman0f4b2852009-07-21 23:03:19 +00006063 // Now that we found a conditional branch that dominates the loop, check to
6064 // see if it is the comparison we are looking for.
6065 ICmpInst::Predicate FoundPred;
6066 if (Inverse)
6067 FoundPred = ICI->getInversePredicate();
6068 else
6069 FoundPred = ICI->getPredicate();
6070
6071 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6072 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00006073
6074 // Balance the types. The case where FoundLHS' type is wider than
6075 // LHS' type is checked for above.
6076 if (getTypeSizeInBits(LHS->getType()) >
6077 getTypeSizeInBits(FoundLHS->getType())) {
6078 if (CmpInst::isSigned(Pred)) {
6079 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6080 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6081 } else {
6082 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6083 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6084 }
6085 }
6086
Dan Gohman0f4b2852009-07-21 23:03:19 +00006087 // Canonicalize the query to match the way instcombine will have
6088 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00006089 if (SimplifyICmpOperands(Pred, LHS, RHS))
6090 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00006091 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00006092 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6093 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00006094 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00006095
6096 // Check to see if we can make the LHS or RHS match.
6097 if (LHS == FoundRHS || RHS == FoundLHS) {
6098 if (isa<SCEVConstant>(RHS)) {
6099 std::swap(FoundLHS, FoundRHS);
6100 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6101 } else {
6102 std::swap(LHS, RHS);
6103 Pred = ICmpInst::getSwappedPredicate(Pred);
6104 }
6105 }
6106
6107 // Check whether the found predicate is the same as the desired predicate.
6108 if (FoundPred == Pred)
6109 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6110
6111 // Check whether swapping the found predicate makes it the same as the
6112 // desired predicate.
6113 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6114 if (isa<SCEVConstant>(RHS))
6115 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6116 else
6117 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6118 RHS, LHS, FoundLHS, FoundRHS);
6119 }
6120
6121 // Check whether the actual condition is beyond sufficient.
6122 if (FoundPred == ICmpInst::ICMP_EQ)
6123 if (ICmpInst::isTrueWhenEqual(Pred))
6124 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6125 return true;
6126 if (Pred == ICmpInst::ICMP_NE)
6127 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6128 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6129 return true;
6130
6131 // Otherwise assume the worst.
6132 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00006133}
6134
Dan Gohman0f4b2852009-07-21 23:03:19 +00006135/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006136/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00006137/// and FoundRHS is true.
6138bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6139 const SCEV *LHS, const SCEV *RHS,
6140 const SCEV *FoundLHS,
6141 const SCEV *FoundRHS) {
6142 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6143 FoundLHS, FoundRHS) ||
6144 // ~x < ~y --> x > y
6145 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6146 getNotSCEV(FoundRHS),
6147 getNotSCEV(FoundLHS));
6148}
6149
6150/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006151/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00006152/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00006153bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00006154ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6155 const SCEV *LHS, const SCEV *RHS,
6156 const SCEV *FoundLHS,
6157 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00006158 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00006159 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6160 case ICmpInst::ICMP_EQ:
6161 case ICmpInst::ICMP_NE:
6162 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6163 return true;
6164 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00006165 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00006166 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00006167 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6168 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00006169 return true;
6170 break;
6171 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00006172 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00006173 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6174 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00006175 return true;
6176 break;
6177 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00006178 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00006179 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6180 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00006181 return true;
6182 break;
6183 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00006184 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00006185 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6186 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00006187 return true;
6188 break;
6189 }
6190
6191 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00006192}
6193
Dan Gohman51f53b72009-06-21 23:46:38 +00006194/// getBECount - Subtract the end and start values and divide by the step,
6195/// rounding up, to get the number of times the backedge is executed. Return
6196/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006197const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00006198 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00006199 const SCEV *Step,
6200 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00006201 assert(!isKnownNegative(Step) &&
6202 "This code doesn't handle negative strides yet!");
6203
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006204 Type *Ty = Start->getType();
Andrew Tricke62289b2011-03-09 17:29:58 +00006205
6206 // When Start == End, we have an exact BECount == 0. Short-circuit this case
6207 // here because SCEV may not be able to determine that the unsigned division
6208 // after rounding is zero.
6209 if (Start == End)
6210 return getConstant(Ty, 0);
6211
Dan Gohmandeff6212010-05-03 22:09:21 +00006212 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00006213 const SCEV *Diff = getMinusSCEV(End, Start);
6214 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00006215
6216 // Add an adjustment to the difference between End and Start so that
6217 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006218 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00006219
Dan Gohman1f96e672009-09-17 18:05:20 +00006220 if (!NoWrap) {
6221 // Check Add for unsigned overflow.
6222 // TODO: More sophisticated things could be done here.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006223 Type *WideTy = IntegerType::get(getContext(),
Dan Gohman1f96e672009-09-17 18:05:20 +00006224 getTypeSizeInBits(Ty) + 1);
6225 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
6226 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
6227 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
6228 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
6229 return getCouldNotCompute();
6230 }
Dan Gohman51f53b72009-06-21 23:46:38 +00006231
6232 return getUDivExpr(Add, Step);
6233}
6234
Chris Lattnerdb25de42005-08-15 23:33:51 +00006235/// HowManyLessThans - Return the number of times a backedge containing the
6236/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00006237/// CouldNotCompute.
Andrew Trick5116ff62011-07-26 17:19:55 +00006238ScalarEvolution::ExitLimit
Dan Gohman64a845e2009-06-24 04:48:43 +00006239ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
6240 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00006241 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00006242 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00006243
Dan Gohman35738ac2009-05-04 22:30:44 +00006244 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00006245 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00006246 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00006247
Dan Gohman1f96e672009-09-17 18:05:20 +00006248 // Check to see if we have a flag which makes analysis easy.
Nick Lewycky89d093d2011-11-09 07:11:37 +00006249 bool NoWrap = isSigned ?
6250 AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNW)) :
6251 AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNW));
Dan Gohman1f96e672009-09-17 18:05:20 +00006252
Chris Lattnerdb25de42005-08-15 23:33:51 +00006253 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00006254 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00006255 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00006256
Dan Gohman52fddd32010-01-26 04:40:18 +00006257 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00006258 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00006259 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00006260 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00006261 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00006262 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00006263 // value and past the maximum value for its type in a single step.
6264 // Note that it's not sufficient to check NoWrap here, because even
6265 // though the value after a wrap is undefined, it's not undefined
6266 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00006267 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00006268 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00006269 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00006270 if (isSigned) {
6271 APInt Max = APInt::getSignedMaxValue(BitWidth);
6272 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
6273 .slt(getSignedRange(RHS).getSignedMax()))
6274 return getCouldNotCompute();
6275 } else {
6276 APInt Max = APInt::getMaxValue(BitWidth);
6277 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
6278 .ult(getUnsignedRange(RHS).getUnsignedMax()))
6279 return getCouldNotCompute();
6280 }
Dan Gohmana1af7572009-04-30 20:47:05 +00006281 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00006282 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00006283 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00006284
Dan Gohmana1af7572009-04-30 20:47:05 +00006285 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
6286 // m. So, we count the number of iterations in which {n,+,s} < m is true.
6287 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00006288 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00006289
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00006290 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00006291 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00006292
Dan Gohmana1af7572009-04-30 20:47:05 +00006293 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00006294 const SCEV *MinStart = getConstant(isSigned ?
6295 getSignedRange(Start).getSignedMin() :
6296 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00006297
Dan Gohmana1af7572009-04-30 20:47:05 +00006298 // If we know that the condition is true in order to enter the loop,
6299 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00006300 // only know that it will execute (max(m,n)-n)/s times. In both cases,
6301 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006302 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00006303 if (!isLoopEntryGuardedByCond(L,
6304 isSigned ? ICmpInst::ICMP_SLT :
6305 ICmpInst::ICMP_ULT,
6306 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00006307 End = isSigned ? getSMaxExpr(RHS, Start)
6308 : getUMaxExpr(RHS, Start);
6309
6310 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00006311 const SCEV *MaxEnd = getConstant(isSigned ?
6312 getSignedRange(End).getSignedMax() :
6313 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00006314
Dan Gohman52fddd32010-01-26 04:40:18 +00006315 // If MaxEnd is within a step of the maximum integer value in its type,
6316 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006317 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00006318 // compute the correct value.
6319 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00006320 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00006321 MaxEnd = isSigned ?
6322 getSMinExpr(MaxEnd,
6323 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
6324 StepMinusOne)) :
6325 getUMinExpr(MaxEnd,
6326 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
6327 StepMinusOne));
6328
Dan Gohmana1af7572009-04-30 20:47:05 +00006329 // Finally, we subtract these two values and divide, rounding up, to get
6330 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00006331 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00006332
6333 // The maximum backedge count is similar, except using the minimum start
6334 // value and the maximum end value.
Andrew Tricke62289b2011-03-09 17:29:58 +00006335 // If we already have an exact constant BECount, use it instead.
6336 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
6337 : getBECount(MinStart, MaxEnd, Step, NoWrap);
6338
6339 // If the stride is nonconstant, and NoWrap == true, then
6340 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
6341 // exact BECount and invalid MaxBECount, which should be avoided to catch
6342 // more optimization opportunities.
6343 if (isa<SCEVCouldNotCompute>(MaxBECount))
6344 MaxBECount = BECount;
Dan Gohmana1af7572009-04-30 20:47:05 +00006345
Andrew Trick5116ff62011-07-26 17:19:55 +00006346 return ExitLimit(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00006347 }
6348
Dan Gohman1c343752009-06-27 21:21:31 +00006349 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00006350}
6351
Chris Lattner53e677a2004-04-02 20:23:17 +00006352/// getNumIterationsInRange - Return the number of iterations of this loop that
6353/// produce values in the specified constant range. Another way of looking at
6354/// this is that it returns the first iteration number where the value is not in
6355/// the condition, thus computing the exit count. If the iteration count can't
6356/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006357const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00006358 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00006359 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006360 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006361
6362 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00006363 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00006364 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00006365 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00006366 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00006367 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickc343c1e2011-03-15 00:37:00 +00006368 getNoWrapFlags(FlagNW));
Dan Gohman622ed672009-05-04 22:02:23 +00006369 if (const SCEVAddRecExpr *ShiftedAddRec =
6370 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00006371 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00006372 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00006373 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006374 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006375 }
6376
6377 // The only time we can solve this is when we have all constant indices.
6378 // Otherwise, we cannot determine the overflow conditions.
6379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6380 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006381 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006382
6383
6384 // Okay at this point we know that all elements of the chrec are constants and
6385 // that the start element is zero.
6386
6387 // First check to see if the range contains zero. If not, the first
6388 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00006389 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00006390 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00006391 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006392
Chris Lattner53e677a2004-04-02 20:23:17 +00006393 if (isAffine()) {
6394 // If this is an affine expression then we have this situation:
6395 // Solve {0,+,A} in Range === Ax in Range
6396
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006397 // We know that zero is in the range. If A is positive then we know that
6398 // the upper value of the range must be the first possible exit value.
6399 // If A is negative then the lower of the range is the last possible loop
6400 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00006401 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006402 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
6403 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00006404
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00006405 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00006406 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00006407 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00006408
6409 // Evaluate at the exit value. If we really did fall out of the valid
6410 // range, then we computed our trip count, otherwise wrap around or other
6411 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00006412 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006413 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006414 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006415
6416 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00006417 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00006418 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00006419 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00006420 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00006421 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00006422 } else if (isQuadratic()) {
6423 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
6424 // quadratic equation to solve it. To do this, we must frame our problem in
6425 // terms of figuring out when zero is crossed, instead of when
6426 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00006427 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00006428 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick3228cc22011-03-14 16:50:06 +00006429 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
6430 // getNoWrapFlags(FlagNW)
6431 FlagAnyWrap);
Chris Lattner53e677a2004-04-02 20:23:17 +00006432
6433 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00006434 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00006435 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00006436 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6437 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00006438 if (R1) {
6439 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006440 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006441 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00006442 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00006443 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00006444 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006445
Chris Lattner53e677a2004-04-02 20:23:17 +00006446 // Make sure the root is not off by one. The returned iteration should
6447 // not be in the range, but the previous one should be. When solving
6448 // for "X*X < 5", for example, we should not return a root of 2.
6449 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00006450 R1->getValue(),
6451 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006452 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006453 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00006454 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00006455 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006456
Dan Gohman246b2562007-10-22 18:31:58 +00006457 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006458 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00006459 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006460 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006461 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006462
Chris Lattner53e677a2004-04-02 20:23:17 +00006463 // If R1 was not in the range, then it is a good return value. Make
6464 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00006465 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00006466 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00006467 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00006468 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00006469 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006470 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00006471 }
6472 }
6473 }
6474
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00006475 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00006476}
6477
6478
6479
6480//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00006481// SCEVCallbackVH Class Implementation
6482//===----------------------------------------------------------------------===//
6483
Dan Gohman1959b752009-05-19 19:22:47 +00006484void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006485 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00006486 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6487 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006488 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00006489 // this now dangles!
6490}
6491
Dan Gohman81f91212010-07-28 01:09:07 +00006492void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00006493 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00006494
Dan Gohman35738ac2009-05-04 22:30:44 +00006495 // Forget all the expressions associated with users of the old value,
6496 // so that future queries will recompute the expressions using the new
6497 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00006498 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00006499 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00006500 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00006501 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6502 UI != UE; ++UI)
6503 Worklist.push_back(*UI);
6504 while (!Worklist.empty()) {
6505 User *U = Worklist.pop_back_val();
6506 // Deleting the Old value will cause this to dangle. Postpone
6507 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00006508 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00006509 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00006510 if (!Visited.insert(U))
6511 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00006512 if (PHINode *PN = dyn_cast<PHINode>(U))
6513 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006514 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00006515 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6516 UI != UE; ++UI)
6517 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00006518 }
Dan Gohman59846ac2010-07-28 00:28:25 +00006519 // Delete the Old value.
6520 if (PHINode *PN = dyn_cast<PHINode>(Old))
6521 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006522 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00006523 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00006524}
6525
Dan Gohman1959b752009-05-19 19:22:47 +00006526ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00006527 : CallbackVH(V), SE(se) {}
6528
6529//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00006530// ScalarEvolution Class Implementation
6531//===----------------------------------------------------------------------===//
6532
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006533ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00006534 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00006535 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006536}
6537
Chris Lattner53e677a2004-04-02 20:23:17 +00006538bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006539 this->F = &F;
6540 LI = &getAnalysis<LoopInfo>();
6541 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00006542 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00006543 return false;
6544}
6545
6546void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00006547 // Iterate through all the SCEVUnknown instances and call their
6548 // destructors, so that they release their references to their values.
6549 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6550 U->~SCEVUnknown();
6551 FirstUnknown = 0;
6552
Dan Gohmane8ac3f32010-08-27 18:55:03 +00006553 ValueExprMap.clear();
Andrew Trick5116ff62011-07-26 17:19:55 +00006554
6555 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
6556 // that a loop had multiple computable exits.
6557 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
6558 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
6559 I != E; ++I) {
6560 I->second.clear();
6561 }
6562
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006563 BackedgeTakenCounts.clear();
6564 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00006565 ValuesAtScopes.clear();
Dan Gohman714b5292010-11-17 23:21:44 +00006566 LoopDispositions.clear();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006567 BlockDispositions.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00006568 UnsignedRanges.clear();
6569 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00006570 UniqueSCEVs.clear();
6571 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00006572}
6573
6574void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6575 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00006576 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00006577 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00006578}
6579
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006580bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006581 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00006582}
6583
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006584static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00006585 const Loop *L) {
6586 // Print all inner loops first
6587 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6588 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006589
Dan Gohman30733292010-01-09 18:17:45 +00006590 OS << "Loop ";
6591 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6592 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006593
Dan Gohman5d984912009-12-18 01:14:11 +00006594 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00006595 L->getExitBlocks(ExitBlocks);
6596 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00006597 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006598
Dan Gohman46bdfb02009-02-24 18:55:53 +00006599 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6600 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00006601 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00006602 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00006603 }
6604
Dan Gohman30733292010-01-09 18:17:45 +00006605 OS << "\n"
6606 "Loop ";
6607 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6608 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00006609
6610 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6611 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6612 } else {
6613 OS << "Unpredictable max backedge-taken count. ";
6614 }
6615
6616 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006617}
6618
Dan Gohman5d984912009-12-18 01:14:11 +00006619void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00006620 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006621 // out SCEV values of all instructions that are interesting. Doing
6622 // this potentially causes it to create new SCEV objects though,
6623 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00006624 // observable from outside the class though, so casting away the
6625 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00006626 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00006627
Dan Gohman30733292010-01-09 18:17:45 +00006628 OS << "Classifying expressions for: ";
6629 WriteAsOperand(OS, F, /*PrintType=*/false);
6630 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00006631 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00006632 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00006633 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00006634 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006635 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006636 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00006637
Dan Gohman0c689c52009-06-19 17:49:54 +00006638 const Loop *L = LI->getLoopFor((*I).getParent());
6639
Dan Gohman0bba49c2009-07-07 17:06:11 +00006640 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00006641 if (AtUse != SV) {
6642 OS << " --> ";
6643 AtUse->print(OS);
6644 }
6645
6646 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00006647 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00006648 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00006649 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00006650 OS << "<<Unknown>>";
6651 } else {
6652 OS << *ExitValue;
6653 }
6654 }
6655
Chris Lattner53e677a2004-04-02 20:23:17 +00006656 OS << "\n";
6657 }
6658
Dan Gohman30733292010-01-09 18:17:45 +00006659 OS << "Determining loop execution counts for: ";
6660 WriteAsOperand(OS, F, /*PrintType=*/false);
6661 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00006662 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6663 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00006664}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00006665
Dan Gohman714b5292010-11-17 23:21:44 +00006666ScalarEvolution::LoopDisposition
6667ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6668 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6669 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6670 Values.insert(std::make_pair(L, LoopVariant));
6671 if (!Pair.second)
6672 return Pair.first->second;
6673
6674 LoopDisposition D = computeLoopDisposition(S, L);
6675 return LoopDispositions[S][L] = D;
6676}
6677
6678ScalarEvolution::LoopDisposition
6679ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00006680 switch (S->getSCEVType()) {
6681 case scConstant:
Dan Gohman714b5292010-11-17 23:21:44 +00006682 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006683 case scTruncate:
6684 case scZeroExtend:
6685 case scSignExtend:
Dan Gohman714b5292010-11-17 23:21:44 +00006686 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006687 case scAddRecExpr: {
6688 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6689
Dan Gohman714b5292010-11-17 23:21:44 +00006690 // If L is the addrec's loop, it's computable.
6691 if (AR->getLoop() == L)
6692 return LoopComputable;
6693
Dan Gohman17ead4f2010-11-17 21:23:15 +00006694 // Add recurrences are never invariant in the function-body (null loop).
6695 if (!L)
Dan Gohman714b5292010-11-17 23:21:44 +00006696 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006697
6698 // This recurrence is variant w.r.t. L if L contains AR's loop.
6699 if (L->contains(AR->getLoop()))
Dan Gohman714b5292010-11-17 23:21:44 +00006700 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006701
6702 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6703 if (AR->getLoop()->contains(L))
Dan Gohman714b5292010-11-17 23:21:44 +00006704 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006705
6706 // This recurrence is variant w.r.t. L if any of its operands
6707 // are variant.
6708 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6709 I != E; ++I)
6710 if (!isLoopInvariant(*I, L))
Dan Gohman714b5292010-11-17 23:21:44 +00006711 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006712
6713 // Otherwise it's loop-invariant.
Dan Gohman714b5292010-11-17 23:21:44 +00006714 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006715 }
6716 case scAddExpr:
6717 case scMulExpr:
6718 case scUMaxExpr:
6719 case scSMaxExpr: {
6720 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman17ead4f2010-11-17 21:23:15 +00006721 bool HasVarying = false;
6722 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6723 I != E; ++I) {
Dan Gohman714b5292010-11-17 23:21:44 +00006724 LoopDisposition D = getLoopDisposition(*I, L);
6725 if (D == LoopVariant)
6726 return LoopVariant;
6727 if (D == LoopComputable)
6728 HasVarying = true;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006729 }
Dan Gohman714b5292010-11-17 23:21:44 +00006730 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006731 }
6732 case scUDivExpr: {
6733 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman714b5292010-11-17 23:21:44 +00006734 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6735 if (LD == LoopVariant)
6736 return LoopVariant;
6737 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6738 if (RD == LoopVariant)
6739 return LoopVariant;
6740 return (LD == LoopInvariant && RD == LoopInvariant) ?
6741 LoopInvariant : LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006742 }
6743 case scUnknown:
Dan Gohman714b5292010-11-17 23:21:44 +00006744 // All non-instruction values are loop invariant. All instructions are loop
6745 // invariant if they are not contained in the specified loop.
6746 // Instructions are never considered invariant in the function body
6747 // (null loop) because they are defined within the "loop".
6748 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6749 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6750 return LoopInvariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006751 case scCouldNotCompute:
6752 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman714b5292010-11-17 23:21:44 +00006753 return LoopVariant;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006754 default: break;
6755 }
6756 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman714b5292010-11-17 23:21:44 +00006757 return LoopVariant;
6758}
6759
6760bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6761 return getLoopDisposition(S, L) == LoopInvariant;
6762}
6763
6764bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6765 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohman17ead4f2010-11-17 21:23:15 +00006766}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006767
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006768ScalarEvolution::BlockDisposition
6769ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6770 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6771 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6772 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6773 if (!Pair.second)
6774 return Pair.first->second;
6775
6776 BlockDisposition D = computeBlockDisposition(S, BB);
6777 return BlockDispositions[S][BB] = D;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006778}
6779
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006780ScalarEvolution::BlockDisposition
6781ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006782 switch (S->getSCEVType()) {
6783 case scConstant:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006784 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006785 case scTruncate:
6786 case scZeroExtend:
6787 case scSignExtend:
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006788 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006789 case scAddRecExpr: {
6790 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006791 // to test for proper dominance too, because the instruction which
6792 // produces the addrec's value is a PHI, and a PHI effectively properly
6793 // dominates its entire containing block.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006794 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6795 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006796 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006797 }
6798 // FALL THROUGH into SCEVNAryExpr handling.
6799 case scAddExpr:
6800 case scMulExpr:
6801 case scUMaxExpr:
6802 case scSMaxExpr: {
6803 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006804 bool Proper = true;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006805 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006806 I != E; ++I) {
6807 BlockDisposition D = getBlockDisposition(*I, BB);
6808 if (D == DoesNotDominateBlock)
6809 return DoesNotDominateBlock;
6810 if (D == DominatesBlock)
6811 Proper = false;
6812 }
6813 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006814 }
6815 case scUDivExpr: {
6816 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006817 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6818 BlockDisposition LD = getBlockDisposition(LHS, BB);
6819 if (LD == DoesNotDominateBlock)
6820 return DoesNotDominateBlock;
6821 BlockDisposition RD = getBlockDisposition(RHS, BB);
6822 if (RD == DoesNotDominateBlock)
6823 return DoesNotDominateBlock;
6824 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6825 ProperlyDominatesBlock : DominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006826 }
6827 case scUnknown:
6828 if (Instruction *I =
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006829 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6830 if (I->getParent() == BB)
6831 return DominatesBlock;
6832 if (DT->properlyDominates(I->getParent(), BB))
6833 return ProperlyDominatesBlock;
6834 return DoesNotDominateBlock;
6835 }
6836 return ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006837 case scCouldNotCompute:
6838 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006839 return DoesNotDominateBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006840 default: break;
6841 }
6842 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006843 return DoesNotDominateBlock;
6844}
6845
6846bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6847 return getBlockDisposition(S, BB) >= DominatesBlock;
6848}
6849
6850bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6851 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006852}
Dan Gohman4ce32db2010-11-17 22:27:42 +00006853
6854bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6855 switch (S->getSCEVType()) {
6856 case scConstant:
6857 return false;
6858 case scTruncate:
6859 case scZeroExtend:
6860 case scSignExtend: {
6861 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6862 const SCEV *CastOp = Cast->getOperand();
6863 return Op == CastOp || hasOperand(CastOp, Op);
6864 }
6865 case scAddRecExpr:
6866 case scAddExpr:
6867 case scMulExpr:
6868 case scUMaxExpr:
6869 case scSMaxExpr: {
6870 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6871 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6872 I != E; ++I) {
6873 const SCEV *NAryOp = *I;
6874 if (NAryOp == Op || hasOperand(NAryOp, Op))
6875 return true;
6876 }
6877 return false;
6878 }
6879 case scUDivExpr: {
6880 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6881 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6882 return LHS == Op || hasOperand(LHS, Op) ||
6883 RHS == Op || hasOperand(RHS, Op);
6884 }
6885 case scUnknown:
6886 return false;
6887 case scCouldNotCompute:
6888 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6889 return false;
6890 default: break;
6891 }
6892 llvm_unreachable("Unknown SCEV kind!");
6893 return false;
6894}
Dan Gohman56a75682010-11-17 23:28:48 +00006895
6896void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6897 ValuesAtScopes.erase(S);
6898 LoopDispositions.erase(S);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +00006899 BlockDispositions.erase(S);
Dan Gohman56a75682010-11-17 23:28:48 +00006900 UnsignedRanges.erase(S);
6901 SignedRanges.erase(S);
6902}