blob: fdbeecae440f5bb6632a279d20601ae639c7ffe9 [file] [log] [blame]
Nick Lewycky97756402014-09-01 05:17:15 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-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 Gohmanef2ae2c2009-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 Lattnerd934c702004-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 Brukman01808ca2005-04-21 21:13:18 +000030//
Chris Lattnerd934c702004-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 Lattnerd934c702004-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Analysis/ScalarEvolution.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000062#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000066#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000068#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000071#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000073#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000074#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000077#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000078#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000079#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000081#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000082#include "llvm/IR/Instructions.h"
83#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000084#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000085#include "llvm/IR/Operator.h"
Chris Lattner996795b2006-06-28 23:17:24 +000086#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000087#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000088#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000089#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000090#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000091#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000092using namespace llvm;
93
Chandler Carruthf1221bd2014-04-22 02:48:03 +000094#define DEBUG_TYPE "scalar-evolution"
95
Chris Lattner57ef9422006-12-19 22:30:33 +000096STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
104
Dan Gohmand78c4002008-05-13 00:00:25 +0000105static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000106MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000108 "symbolically execute a constant "
109 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000110 cl::init(100));
111
Benjamin Kramer214935e2012-10-26 17:31:32 +0000112// FIXME: Enable this with XDEBUG when the test suite is clean.
113static cl::opt<bool>
114VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
116
Owen Anderson8ac477f2010-10-12 19:48:12 +0000117INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +0000119INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000120INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000121INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000122INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000123INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000124 "Scalar Evolution Analysis", false, true)
Devang Patel8c78a0b2007-05-03 01:11:54 +0000125char ScalarEvolution::ID = 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000126
127//===----------------------------------------------------------------------===//
128// SCEV class definitions
129//===----------------------------------------------------------------------===//
130
131//===----------------------------------------------------------------------===//
132// Implementation of the SCEV class.
133//
Dan Gohman3423e722009-06-30 20:13:32 +0000134
Manman Ren49d684e2012-09-12 05:06:18 +0000135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerd934c702004-04-02 20:23:17 +0000136void SCEV::dump() const {
David Greenedf1c4972009-12-23 22:18:14 +0000137 print(dbgs());
138 dbgs() << '\n';
Dan Gohmane20f8242009-04-21 00:47:46 +0000139}
Manman Renc3366cc2012-09-06 19:55:56 +0000140#endif
Dan Gohmane20f8242009-04-21 00:47:46 +0000141
Dan Gohman534749b2010-11-17 22:27:42 +0000142void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000143 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000144 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000146 return;
147 case scTruncate: {
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
152 return;
153 }
154 case scZeroExtend: {
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
159 return;
160 }
161 case scSignExtend: {
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
166 return;
167 }
168 case scAddRecExpr: {
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
173 OS << "}<";
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000175 OS << "nuw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000176 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000177 OS << "nsw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
180 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000182 OS << ">";
183 return;
184 }
185 case scAddExpr:
186 case scMulExpr:
187 case scUMaxExpr:
188 case scSMaxExpr: {
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000190 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
196 }
197 OS << "(";
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
199 I != E; ++I) {
200 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000201 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000202 OS << OpStr;
203 }
204 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000205 switch (NAry->getSCEVType()) {
206 case scAddExpr:
207 case scMulExpr:
208 if (NAry->getNoWrapFlags(FlagNUW))
209 OS << "<nuw>";
210 if (NAry->getNoWrapFlags(FlagNSW))
211 OS << "<nsw>";
212 }
Dan Gohman534749b2010-11-17 22:27:42 +0000213 return;
214 }
215 case scUDivExpr: {
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
218 return;
219 }
220 case scUnknown: {
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000222 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
225 return;
226 }
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
229 return;
230 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000231
Chris Lattner229907c2011-07-18 04:54:35 +0000232 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000233 Constant *FieldNo;
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000236 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000237 OS << ")";
238 return;
239 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000240
Dan Gohman534749b2010-11-17 22:27:42 +0000241 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000242 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000243 return;
244 }
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
247 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000248 }
249 llvm_unreachable("Unknown SCEV kind!");
250}
251
Chris Lattner229907c2011-07-18 04:54:35 +0000252Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000253 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000254 case scConstant:
255 return cast<SCEVConstant>(this)->getType();
256 case scTruncate:
257 case scZeroExtend:
258 case scSignExtend:
259 return cast<SCEVCastExpr>(this)->getType();
260 case scAddRecExpr:
261 case scMulExpr:
262 case scUMaxExpr:
263 case scSMaxExpr:
264 return cast<SCEVNAryExpr>(this)->getType();
265 case scAddExpr:
266 return cast<SCEVAddExpr>(this)->getType();
267 case scUDivExpr:
268 return cast<SCEVUDivExpr>(this)->getType();
269 case scUnknown:
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000273 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000274 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000275}
276
Dan Gohmanbe928e32008-06-18 16:23:07 +0000277bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
280 return false;
281}
282
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000283bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
286 return false;
287}
Chris Lattnerd934c702004-04-02 20:23:17 +0000288
Dan Gohman18a96bb2009-06-24 00:30:26 +0000289bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
292 return false;
293}
294
Andrew Trick881a7762012-01-07 00:27:31 +0000295/// isNonConstantNegative - Return true if the specified scev is negated, but
296/// not a constant.
297bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
300
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
304
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
307}
308
Owen Anderson04052ec2009-06-22 21:57:23 +0000309SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000311
Chris Lattnerd934c702004-04-02 20:23:17 +0000312bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
314}
315
Dan Gohmanaf752342009-07-07 17:06:11 +0000316const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000317 FoldingSetNodeID ID;
318 ID.AddInteger(scConstant);
319 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000320 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000323 UniqueSCEVs.InsertNode(S, IP);
324 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000325}
Chris Lattnerd934c702004-04-02 20:23:17 +0000326
Nick Lewycky31eaca52014-01-27 10:04:03 +0000327const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000328 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000329}
330
Dan Gohmanaf752342009-07-07 17:06:11 +0000331const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000332ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000334 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000335}
336
Dan Gohman24ceda82010-06-18 19:54:20 +0000337SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000338 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000340
Dan Gohman24ceda82010-06-18 19:54:20 +0000341SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000342 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000343 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000346 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000347}
Chris Lattnerd934c702004-04-02 20:23:17 +0000348
Dan Gohman24ceda82010-06-18 19:54:20 +0000349SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000350 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000354 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000355}
356
Dan Gohman24ceda82010-06-18 19:54:20 +0000357SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000358 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000362 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000363}
364
Dan Gohman7cac9572010-08-02 23:49:30 +0000365void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000366 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000367 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000368
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
371
372 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000373 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374}
375
376void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000377 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000378 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000379
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
382
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
385 // this SCEVUnknown.
386 setValPtr(New);
387}
388
Chris Lattner229907c2011-07-18 04:54:35 +0000389bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
397 if (CI->isOne()) {
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
399 ->getElementType();
400 return true;
401 }
Dan Gohmancf913832010-01-28 02:15:55 +0000402
403 return false;
404}
405
Chris Lattner229907c2011-07-18 04:54:35 +0000406bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000412 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000414 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
419 if (CI->isOne() &&
420 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000421 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000422 AllocTy = STy->getElementType(1);
423 return true;
424 }
425 }
426 }
Dan Gohmancf913832010-01-28 02:15:55 +0000427
428 return false;
429}
430
Chris Lattner229907c2011-07-18 04:54:35 +0000431bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000439 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000443 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000444 CTy = Ty;
445 FieldNo = CE->getOperand(2);
446 return true;
447 }
448 }
449
450 return false;
451}
452
Chris Lattnereb3e8402004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
457namespace {
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
460 /// expressions.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000461 class SCEVComplexityCompare {
Dan Gohman3324b9e2010-08-13 20:17:27 +0000462 const LoopInfo *const LI;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000463 public:
Dan Gohman992db002010-07-23 21:18:55 +0000464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000465
Dan Gohman27065672010-08-27 15:26:01 +0000466 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman27065672010-08-27 15:26:01 +0000468 return compare(LHS, RHS) < 0;
469 }
470
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
476 if (LHS == RHS)
Dan Gohman27065672010-08-27 15:26:01 +0000477 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000478
Dan Gohman9ba542c2009-05-07 14:39:04 +0000479 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman5ae31022010-07-23 21:20:52 +0000480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
481 if (LType != RType)
Dan Gohman27065672010-08-27 15:26:01 +0000482 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000483
Dan Gohman24ceda82010-06-18 19:54:20 +0000484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
Benjamin Kramer987b8502014-02-11 19:02:55 +0000487 switch (static_cast<SCEVTypes>(LType)) {
Dan Gohman27065672010-08-27 15:26:01 +0000488 case scUnknown: {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000491
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000494 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000495
496 // Order pointer values after integer values. This helps SCEVExpander
497 // form GEPs.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman5ae31022010-07-23 21:20:52 +0000500 if (LIsPointer != RIsPointer)
Dan Gohman27065672010-08-27 15:26:01 +0000501 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000502
503 // Compare getValueID values.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
Dan Gohman5ae31022010-07-23 21:20:52 +0000506 if (LID != RID)
Dan Gohman27065672010-08-27 15:26:01 +0000507 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000508
509 // Sort arguments by their position.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000514 }
515
Dan Gohman27065672010-08-27 15:26:01 +0000516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman24ceda82010-06-18 19:54:20 +0000520
521 // Compare loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000528 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000529 }
Dan Gohman24ceda82010-06-18 19:54:20 +0000530
531 // Compare the number of operands.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000534 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000535 }
536
Dan Gohman27065672010-08-27 15:26:01 +0000537 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000538 }
539
Dan Gohman27065672010-08-27 15:26:01 +0000540 case scConstant: {
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000543
544 // Compare constant values.
Dan Gohmanf2961822010-08-16 16:25:35 +0000545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman5ae31022010-07-23 21:20:52 +0000548 if (LBitWidth != RBitWidth)
Dan Gohman27065672010-08-27 15:26:01 +0000549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
Dan Gohman24ceda82010-06-18 19:54:20 +0000551 }
552
Dan Gohman27065672010-08-27 15:26:01 +0000553 case scAddRecExpr: {
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000556
557 // Compare addrec loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000563 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000564 }
Dan Gohman27065672010-08-27 15:26:01 +0000565
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
570
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
574 if (X != 0)
575 return X;
576 }
577
578 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000579 }
580
Dan Gohman27065672010-08-27 15:26:01 +0000581 case scAddExpr:
582 case scMulExpr:
583 case scSMaxExpr:
584 case scUMaxExpr: {
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000587
588 // Lexicographically compare n-ary expressions.
Dan Gohman5ae31022010-07-23 21:20:52 +0000589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
Andrew Trickc3bc8b82013-07-31 02:43:40 +0000590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
592
Dan Gohman5ae31022010-07-23 21:20:52 +0000593 for (unsigned i = 0; i != LNumOps; ++i) {
594 if (i >= RNumOps)
Dan Gohman27065672010-08-27 15:26:01 +0000595 return 1;
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
597 if (X != 0)
598 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000599 }
Dan Gohman27065672010-08-27 15:26:01 +0000600 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000601 }
602
Dan Gohman27065672010-08-27 15:26:01 +0000603 case scUDivExpr: {
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000606
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
609 if (X != 0)
610 return X;
611 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman24ceda82010-06-18 19:54:20 +0000612 }
613
Dan Gohman27065672010-08-27 15:26:01 +0000614 case scTruncate:
615 case scZeroExtend:
616 case scSignExtend: {
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000619
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
622 }
623
Benjamin Kramer987b8502014-02-11 19:02:55 +0000624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman24ceda82010-06-18 19:54:20 +0000626 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000627 llvm_unreachable("Unknown SCEV kind!");
Chris Lattnereb3e8402004-06-20 06:23:15 +0000628 }
629 };
630}
631
632/// GroupByComplexity - Given a list of SCEV objects, order them by their
633/// complexity, and group objects of the same complexity together by value.
634/// When this routine is finished, we know that any duplicates in the vector are
635/// consecutive and that complexity is monotonically increasing.
636///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000637/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000638/// results from this routine. In other words, we don't want the results of
639/// this to depend on where the addresses of various SCEV objects happened to
640/// land in memory.
641///
Dan Gohmanaf752342009-07-07 17:06:11 +0000642static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000643 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
647 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
650 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000651 return;
652 }
653
Dan Gohman24ceda82010-06-18 19:54:20 +0000654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
656
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
664
665 // If there are any objects of the same complexity and same value as this
666 // one, group them.
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
673 }
674 }
675 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000676}
677
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000678namespace {
679struct FindSCEVSize {
680 int Size;
681 FindSCEVSize() : Size(0) {}
682
683 bool follow(const SCEV *S) {
684 ++Size;
685 // Keep looking at all operands of S.
686 return true;
687 }
688 bool isDone() const {
689 return false;
690 }
691};
692}
693
694// Returns the size of the SCEV S.
695static inline int sizeOfSCEV(const SCEV *S) {
696 FindSCEVSize F;
697 SCEVTraversal<FindSCEVSize> ST(F);
698 ST.visitAll(S);
699 return F.Size;
700}
701
702namespace {
703
David Majnemer4e879362014-12-14 09:12:33 +0000704struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000705public:
706 // Computes the Quotient and Remainder of the division of Numerator by
707 // Denominator.
708 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
709 const SCEV *Denominator, const SCEV **Quotient,
710 const SCEV **Remainder) {
711 assert(Numerator && Denominator && "Uninitialized SCEV");
712
David Majnemer4e879362014-12-14 09:12:33 +0000713 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000714
715 // Check for the trivial case here to avoid having to check for it in the
716 // rest of the code.
717 if (Numerator == Denominator) {
718 *Quotient = D.One;
719 *Remainder = D.Zero;
720 return;
721 }
722
723 if (Numerator->isZero()) {
724 *Quotient = D.Zero;
725 *Remainder = D.Zero;
726 return;
727 }
728
729 // Split the Denominator when it is a product.
730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
731 const SCEV *Q, *R;
732 *Quotient = Numerator;
733 for (const SCEV *Op : T->operands()) {
734 divide(SE, *Quotient, Op, &Q, &R);
735 *Quotient = Q;
736
737 // Bail out when the Numerator is not divisible by one of the terms of
738 // the Denominator.
739 if (!R->isZero()) {
740 *Quotient = D.Zero;
741 *Remainder = Numerator;
742 return;
743 }
744 }
745 *Remainder = D.Zero;
746 return;
747 }
748
749 D.visit(Numerator);
750 *Quotient = D.Quotient;
751 *Remainder = D.Remainder;
752 }
753
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000754 // Except in the trivial case described above, we do not know how to divide
755 // Expr by Denominator for the following functions with empty implementation.
756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762 void visitUnknown(const SCEVUnknown *Numerator) {}
763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
764
David Majnemer4e879362014-12-14 09:12:33 +0000765 void visitConstant(const SCEVConstant *Numerator) {
766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
767 APInt NumeratorVal = Numerator->getValue()->getValue();
768 APInt DenominatorVal = D->getValue()->getValue();
769 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
771
772 if (NumeratorBW > DenominatorBW)
773 DenominatorVal = DenominatorVal.sext(NumeratorBW);
774 else if (NumeratorBW < DenominatorBW)
775 NumeratorVal = NumeratorVal.sext(DenominatorBW);
776
777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780 Quotient = SE.getConstant(QuotientVal);
781 Remainder = SE.getConstant(RemainderVal);
782 return;
783 }
784 }
785
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787 const SCEV *StartQ, *StartR, *StepQ, *StepR;
788 assert(Numerator->isAffine() && "Numerator should be affine");
789 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
790 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
791 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
792 Numerator->getNoWrapFlags());
793 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
794 Numerator->getNoWrapFlags());
795 }
796
797 void visitAddExpr(const SCEVAddExpr *Numerator) {
798 SmallVector<const SCEV *, 2> Qs, Rs;
799 Type *Ty = Denominator->getType();
800
801 for (const SCEV *Op : Numerator->operands()) {
802 const SCEV *Q, *R;
803 divide(SE, Op, Denominator, &Q, &R);
804
805 // Bail out if types do not match.
806 if (Ty != Q->getType() || Ty != R->getType()) {
807 Quotient = Zero;
808 Remainder = Numerator;
809 return;
810 }
811
812 Qs.push_back(Q);
813 Rs.push_back(R);
814 }
815
816 if (Qs.size() == 1) {
817 Quotient = Qs[0];
818 Remainder = Rs[0];
819 return;
820 }
821
822 Quotient = SE.getAddExpr(Qs);
823 Remainder = SE.getAddExpr(Rs);
824 }
825
826 void visitMulExpr(const SCEVMulExpr *Numerator) {
827 SmallVector<const SCEV *, 2> Qs;
828 Type *Ty = Denominator->getType();
829
830 bool FoundDenominatorTerm = false;
831 for (const SCEV *Op : Numerator->operands()) {
832 // Bail out if types do not match.
833 if (Ty != Op->getType()) {
834 Quotient = Zero;
835 Remainder = Numerator;
836 return;
837 }
838
839 if (FoundDenominatorTerm) {
840 Qs.push_back(Op);
841 continue;
842 }
843
844 // Check whether Denominator divides one of the product operands.
845 const SCEV *Q, *R;
846 divide(SE, Op, Denominator, &Q, &R);
847 if (!R->isZero()) {
848 Qs.push_back(Op);
849 continue;
850 }
851
852 // Bail out if types do not match.
853 if (Ty != Q->getType()) {
854 Quotient = Zero;
855 Remainder = Numerator;
856 return;
857 }
858
859 FoundDenominatorTerm = true;
860 Qs.push_back(Q);
861 }
862
863 if (FoundDenominatorTerm) {
864 Remainder = Zero;
865 if (Qs.size() == 1)
866 Quotient = Qs[0];
867 else
868 Quotient = SE.getMulExpr(Qs);
869 return;
870 }
871
872 if (!isa<SCEVUnknown>(Denominator)) {
873 Quotient = Zero;
874 Remainder = Numerator;
875 return;
876 }
877
878 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
879 ValueToValueMap RewriteMap;
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(Zero)->getValue();
882 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
883
884 if (Remainder->isZero()) {
885 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
886 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
887 cast<SCEVConstant>(One)->getValue();
888 Quotient =
889 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
890 return;
891 }
892
893 // Quotient is (Numerator - Remainder) divided by Denominator.
894 const SCEV *Q, *R;
895 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
896 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
897 // This SCEV does not seem to simplify: fail the division here.
898 Quotient = Zero;
899 Remainder = Numerator;
900 return;
901 }
902 divide(SE, Diff, Denominator, &Q, &R);
903 assert(R == Zero &&
904 "(Numerator - Remainder) should evenly divide Denominator");
905 Quotient = Q;
906 }
907
908private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000909 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
910 const SCEV *Denominator)
911 : SE(S), Denominator(Denominator) {
912 Zero = SE.getConstant(Denominator->getType(), 0);
913 One = SE.getConstant(Denominator->getType(), 1);
914
915 // By default, we don't know how to divide Expr by Denominator.
916 // Providing the default here simplifies the rest of the code.
917 Quotient = Zero;
918 Remainder = Numerator;
919 }
920
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000921 ScalarEvolution &SE;
922 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000923};
924
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000925}
926
Chris Lattnerd934c702004-04-02 20:23:17 +0000927//===----------------------------------------------------------------------===//
928// Simple SCEV method implementations
929//===----------------------------------------------------------------------===//
930
Eli Friedman61f67622008-08-04 23:49:06 +0000931/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000932/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000933static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000934 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000935 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000936 // Handle the simplest case efficiently.
937 if (K == 1)
938 return SE.getTruncateOrZeroExtend(It, ResultTy);
939
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000940 // We are using the following formula for BC(It, K):
941 //
942 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
943 //
Eli Friedman61f67622008-08-04 23:49:06 +0000944 // Suppose, W is the bitwidth of the return value. We must be prepared for
945 // overflow. Hence, we must assure that the result of our computation is
946 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
947 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000948 //
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000950 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000951 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
952 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000953 //
Eli Friedman61f67622008-08-04 23:49:06 +0000954 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000955 //
Eli Friedman61f67622008-08-04 23:49:06 +0000956 // This formula is trivially equivalent to the previous formula. However,
957 // this formula can be implemented much more efficiently. The trick is that
958 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
959 // arithmetic. To do exact division in modular arithmetic, all we have
960 // to do is multiply by the inverse. Therefore, this step can be done at
961 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000962 //
Eli Friedman61f67622008-08-04 23:49:06 +0000963 // The next issue is how to safely do the division by 2^T. The way this
964 // is done is by doing the multiplication step at a width of at least W + T
965 // bits. This way, the bottom W+T bits of the product are accurate. Then,
966 // when we perform the division by 2^T (which is equivalent to a right shift
967 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
968 // truncated out after the division by 2^T.
969 //
970 // In comparison to just directly using the first formula, this technique
971 // is much more efficient; using the first formula requires W * K bits,
972 // but this formula less than W + K bits. Also, the first formula requires
973 // a division step, whereas this formula only requires multiplies and shifts.
974 //
975 // It doesn't matter whether the subtraction step is done in the calculation
976 // width or the input iteration count's width; if the subtraction overflows,
977 // the result must be zero anyway. We prefer here to do it in the width of
978 // the induction variable because it helps a lot for certain cases; CodeGen
979 // isn't smart enough to ignore the overflow, which leads to much less
980 // efficient code if the width of the subtraction is wider than the native
981 // register width.
982 //
983 // (It's possible to not widen at all by pulling out factors of 2 before
984 // the multiplication; for example, K=2 can be calculated as
985 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
986 // extra arithmetic, so it's not an obvious win, and it gets
987 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000988
Eli Friedman61f67622008-08-04 23:49:06 +0000989 // Protection from insane SCEVs; this bound is conservative,
990 // but it probably doesn't matter.
991 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000992 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000993
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000994 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000995
Eli Friedman61f67622008-08-04 23:49:06 +0000996 // Calculate K! / 2^T and T; we divide out the factors of two before
997 // multiplying for calculating K! / 2^T to avoid overflow.
998 // Other overflow doesn't matter because we only care about the bottom
999 // W bits of the result.
1000 APInt OddFactorial(W, 1);
1001 unsigned T = 1;
1002 for (unsigned i = 3; i <= K; ++i) {
1003 APInt Mult(W, i);
1004 unsigned TwoFactors = Mult.countTrailingZeros();
1005 T += TwoFactors;
1006 Mult = Mult.lshr(TwoFactors);
1007 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001008 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001009
Eli Friedman61f67622008-08-04 23:49:06 +00001010 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001011 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001012
Dan Gohman8b0a4192010-03-01 17:49:51 +00001013 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001014 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001015
1016 // Calculate the multiplicative inverse of K! / 2^T;
1017 // this multiplication factor will perform the exact division by
1018 // K! / 2^T.
1019 APInt Mod = APInt::getSignedMinValue(W+1);
1020 APInt MultiplyFactor = OddFactorial.zext(W+1);
1021 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1022 MultiplyFactor = MultiplyFactor.trunc(W);
1023
1024 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001025 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001026 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001027 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001028 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001029 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001030 Dividend = SE.getMulExpr(Dividend,
1031 SE.getTruncateOrZeroExtend(S, CalculationTy));
1032 }
1033
1034 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001035 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001036
1037 // Truncate the result, and divide by K! / 2^T.
1038
1039 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1040 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001041}
1042
Chris Lattnerd934c702004-04-02 20:23:17 +00001043/// evaluateAtIteration - Return the value of this chain of recurrences at
1044/// the specified iteration number. We can evaluate this recurrence by
1045/// multiplying each element in the chain by the binomial coefficient
1046/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1047///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001048/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001049///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001050/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001051///
Dan Gohmanaf752342009-07-07 17:06:11 +00001052const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001053 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001054 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001055 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001056 // The computation is correct in the face of overflow provided that the
1057 // multiplication is performed _after_ the evaluation of the binomial
1058 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001059 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001060 if (isa<SCEVCouldNotCompute>(Coeff))
1061 return Coeff;
1062
1063 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001064 }
1065 return Result;
1066}
1067
Chris Lattnerd934c702004-04-02 20:23:17 +00001068//===----------------------------------------------------------------------===//
1069// SCEV Expression folder implementations
1070//===----------------------------------------------------------------------===//
1071
Dan Gohmanaf752342009-07-07 17:06:11 +00001072const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001073 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001074 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001075 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001076 assert(isSCEVable(Ty) &&
1077 "This is not a conversion to a SCEVable type!");
1078 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001079
Dan Gohman3a302cb2009-07-13 20:50:19 +00001080 FoldingSetNodeID ID;
1081 ID.AddInteger(scTruncate);
1082 ID.AddPointer(Op);
1083 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001084 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001085 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1086
Dan Gohman3423e722009-06-30 20:13:32 +00001087 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001088 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001089 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001090 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001091
Dan Gohman79af8542009-04-22 16:20:48 +00001092 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001093 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001094 return getTruncateExpr(ST->getOperand(), Ty);
1095
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001096 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001097 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001098 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1099
1100 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001101 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001102 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1103
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001104 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1105 // eliminate all the truncates.
1106 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1107 SmallVector<const SCEV *, 4> Operands;
1108 bool hasTrunc = false;
1109 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1110 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1111 hasTrunc = isa<SCEVTruncateExpr>(S);
1112 Operands.push_back(S);
1113 }
1114 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001115 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001116 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001117 }
1118
Nick Lewycky5c901f32011-01-19 18:56:00 +00001119 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1120 // eliminate all the truncates.
1121 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1122 SmallVector<const SCEV *, 4> Operands;
1123 bool hasTrunc = false;
1124 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1125 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
1127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001132 }
1133
Dan Gohman5a728c92009-06-18 16:24:47 +00001134 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001136 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00001137 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman2e55cc52009-05-08 21:03:19 +00001138 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001140 }
1141
Dan Gohman89dd42a2010-06-25 18:47:08 +00001142 // The cast wasn't folded; create an explicit cast node. We can reuse
1143 // the existing insert position since if we get here, we won't have
1144 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1146 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001147 UniqueSCEVs.InsertNode(S, IP);
1148 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001149}
1150
Sanjoy Das4153f472015-02-18 01:47:07 +00001151// Get the limit of a recurrence such that incrementing by Step cannot cause
1152// signed overflow as long as the value of the recurrence within the
1153// loop does not exceed this limit before incrementing.
1154static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155 ICmpInst::Predicate *Pred,
1156 ScalarEvolution *SE) {
1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158 if (SE->isKnownPositive(Step)) {
1159 *Pred = ICmpInst::ICMP_SLT;
1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161 SE->getSignedRange(Step).getSignedMax());
1162 }
1163 if (SE->isKnownNegative(Step)) {
1164 *Pred = ICmpInst::ICMP_SGT;
1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166 SE->getSignedRange(Step).getSignedMin());
1167 }
1168 return nullptr;
1169}
1170
1171// Get the limit of a recurrence such that incrementing by Step cannot cause
1172// unsigned overflow as long as the value of the recurrence within the loop does
1173// not exceed this limit before incrementing.
1174static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175 ICmpInst::Predicate *Pred,
1176 ScalarEvolution *SE) {
1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178 *Pred = ICmpInst::ICMP_ULT;
1179
1180 return SE->getConstant(APInt::getMinValue(BitWidth) -
1181 SE->getUnsignedRange(Step).getUnsignedMax());
1182}
1183
1184namespace {
1185
1186struct ExtendOpTraitsBase {
1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1188};
1189
1190// Used to make code generic over signed and unsigned overflow.
1191template <typename ExtendOp> struct ExtendOpTraits {
1192 // Members present:
1193 //
1194 // static const SCEV::NoWrapFlags WrapType;
1195 //
1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1197 //
1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199 // ICmpInst::Predicate *Pred,
1200 // ScalarEvolution *SE);
1201};
1202
1203template <>
1204struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1206
1207 static const GetExtendExprTy GetExtendExpr;
1208
1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 return getSignedOverflowLimitForStep(Step, Pred, SE);
1213 }
1214};
1215
1216const ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExprTy ExtendOpTraits<
1217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1218
1219template <>
1220struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1222
1223 static const GetExtendExprTy GetExtendExpr;
1224
1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226 ICmpInst::Predicate *Pred,
1227 ScalarEvolution *SE) {
1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1229 }
1230};
1231
1232const ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExprTy ExtendOpTraits<
1233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1234}
1235
1236// The recurrence AR has been shown to have no signed/unsigned wrap or something
1237// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241// expression "Step + sext/zext(PreIncAR)" is congruent with
1242// "sext/zext(PostIncAR)"
1243template <typename ExtendOpTy>
1244static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245 ScalarEvolution *SE) {
1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1248
1249 const Loop *L = AR->getLoop();
1250 const SCEV *Start = AR->getStart();
1251 const SCEV *Step = AR->getStepRecurrence(*SE);
1252
1253 // Check for a simple looking step prior to loop entry.
1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1255 if (!SA)
1256 return nullptr;
1257
1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259 // subtraction is expensive. For this purpose, perform a quick and dirty
1260 // difference, by checking for Step in the operand list.
1261 SmallVector<const SCEV *, 4> DiffOps;
1262 for (const SCEV *Op : SA->operands())
1263 if (Op != Step)
1264 DiffOps.push_back(Op);
1265
1266 if (DiffOps.size() == SA->getNumOperands())
1267 return nullptr;
1268
1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1270 // `Step`:
1271
1272 // 1. NSW/NUW flags on the step increment.
1273 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1274 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1275 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1276
1277 // WARNING: FIXME: the optimization below assumes that a sign/zero-overflowing
1278 // nsw/nuw operation is undefined behavior. This is strictly more aggressive
1279 // than the interpretation of nsw in other parts of LLVM (for instance, they
1280 // may unconditionally hoist nsw/nuw arithmetic through control flow). This
1281 // logic needs to be revisited once we have a consistent semantics for poison
1282 // values.
1283 //
1284 // "{S,+,X} is <nsw>/<nuw>" and "{S,+,X} is evaluated at least once" implies
1285 // "S+X does not sign/unsign-overflow" (we'd have undefined behavior if it
1286 // did). If `L->getExitingBlock() == L->getLoopLatch()` then `PreAR` (=
1287 // {S,+,X}<nsw>/<nuw>) is evaluated every-time `AR` (= {S+X,+,X}) is
1288 // evaluated, and hence within `AR` we are safe to assume that "S+X" will not
1289 // sign/unsign-overflow.
1290 //
1291
1292 BasicBlock *ExitingBlock = L->getExitingBlock();
1293 BasicBlock *LatchBlock = L->getLoopLatch();
1294 if (PreAR && PreAR->getNoWrapFlags(WrapType) && ExitingBlock != nullptr &&
1295 ExitingBlock == LatchBlock)
1296 return PreStart;
1297
1298 // 2. Direct overflow check on the step operation's expression.
1299 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1300 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1301 const SCEV *OperandExtendedStart =
1302 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1303 (SE->*GetExtendExpr)(Step, WideTy));
1304 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1305 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1306 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1307 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1308 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1309 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1310 }
1311 return PreStart;
1312 }
1313
1314 // 3. Loop precondition.
1315 ICmpInst::Predicate Pred;
1316 const SCEV *OverflowLimit =
1317 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1318
1319 if (OverflowLimit &&
1320 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1321 return PreStart;
1322 }
1323 return nullptr;
1324}
1325
1326// Get the normalized zero or sign extended expression for this AddRec's Start.
1327template <typename ExtendOpTy>
1328static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1329 ScalarEvolution *SE) {
1330 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1331
1332 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1333 if (!PreStart)
1334 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1335
1336 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1337 (SE->*GetExtendExpr)(PreStart, Ty));
1338}
1339
Dan Gohmanaf752342009-07-07 17:06:11 +00001340const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001341 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001342 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001343 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001344 assert(isSCEVable(Ty) &&
1345 "This is not a conversion to a SCEVable type!");
1346 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001347
Dan Gohman3423e722009-06-30 20:13:32 +00001348 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001349 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1350 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001351 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001352
Dan Gohman79af8542009-04-22 16:20:48 +00001353 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001354 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001355 return getZeroExtendExpr(SZ->getOperand(), Ty);
1356
Dan Gohman74a0ba12009-07-13 20:55:53 +00001357 // Before doing any expensive analysis, check to see if we've already
1358 // computed a SCEV for this Op and Ty.
1359 FoldingSetNodeID ID;
1360 ID.AddInteger(scZeroExtend);
1361 ID.AddPointer(Op);
1362 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001363 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001364 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1365
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001366 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1367 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1368 // It's possible the bits taken off by the truncate were all zero bits. If
1369 // so, we should be able to simplify this further.
1370 const SCEV *X = ST->getOperand();
1371 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001372 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1373 unsigned NewBits = getTypeSizeInBits(Ty);
1374 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001375 CR.zextOrTrunc(NewBits)))
1376 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001377 }
1378
Dan Gohman76466372009-04-27 20:16:15 +00001379 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001380 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001381 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001382 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001383 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001384 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001385 const SCEV *Start = AR->getStart();
1386 const SCEV *Step = AR->getStepRecurrence(*this);
1387 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1388 const Loop *L = AR->getLoop();
1389
Dan Gohman62ef6a72009-07-25 01:22:26 +00001390 // If we have special knowledge that this addrec won't overflow,
1391 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001392 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Sanjoy Das4153f472015-02-18 01:47:07 +00001393 return getAddRecExpr(
1394 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1395 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001396
Dan Gohman76466372009-04-27 20:16:15 +00001397 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1398 // Note that this serves two purposes: It filters out loops that are
1399 // simply not analyzable, and it covers the case where this code is
1400 // being called from within backedge-taken count analysis, such that
1401 // attempting to ask for the backedge-taken count would likely result
1402 // in infinite recursion. In the later case, the analysis code will
1403 // cope with a conservative value, and it will take care to purge
1404 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001405 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001406 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001407 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001408 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001409
1410 // Check whether the backedge-taken count can be losslessly casted to
1411 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001412 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001413 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001414 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001415 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1416 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001417 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001418 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001419 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001420 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1421 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1422 const SCEV *WideMaxBECount =
1423 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001424 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001425 getAddExpr(WideStart,
1426 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001427 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001428 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001429 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1430 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001431 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001432 return getAddRecExpr(
1433 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1434 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001435 }
Dan Gohman76466372009-04-27 20:16:15 +00001436 // Similar to above, only this time treat the step value as signed.
1437 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001438 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001439 getAddExpr(WideStart,
1440 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001441 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001442 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001443 // Cache knowledge of AR NW, which is propagated to this AddRec.
1444 // Negative step causes unsigned wrap, but it still can't self-wrap.
1445 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001446 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001447 return getAddRecExpr(
1448 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1449 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001450 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001451 }
1452
1453 // If the backedge is guarded by a comparison with the pre-inc value
1454 // the addrec is safe. Also, if the entry is guarded by a comparison
1455 // with the start value and the backedge is guarded by a comparison
1456 // with the post-inc value, the addrec is safe.
1457 if (isKnownPositive(Step)) {
1458 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1459 getUnsignedRange(Step).getUnsignedMax());
1460 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001461 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001462 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001463 AR->getPostIncExpr(*this), N))) {
1464 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1465 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001466 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001467 return getAddRecExpr(
1468 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1469 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001470 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001471 } else if (isKnownNegative(Step)) {
1472 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1473 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001474 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1475 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001476 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001477 AR->getPostIncExpr(*this), N))) {
1478 // Cache knowledge of AR NW, which is propagated to this AddRec.
1479 // Negative step causes unsigned wrap, but it still can't self-wrap.
1480 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1481 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001482 return getAddRecExpr(
1483 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1484 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001485 }
Dan Gohman76466372009-04-27 20:16:15 +00001486 }
1487 }
1488 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001489
Dan Gohman74a0ba12009-07-13 20:55:53 +00001490 // The cast wasn't folded; create an explicit cast node.
1491 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001492 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001493 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1494 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001495 UniqueSCEVs.InsertNode(S, IP);
1496 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001497}
1498
Dan Gohmanaf752342009-07-07 17:06:11 +00001499const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001500 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001501 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001502 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001503 assert(isSCEVable(Ty) &&
1504 "This is not a conversion to a SCEVable type!");
1505 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001506
Dan Gohman3423e722009-06-30 20:13:32 +00001507 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001508 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1509 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001510 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001511
Dan Gohman79af8542009-04-22 16:20:48 +00001512 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001513 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001514 return getSignExtendExpr(SS->getOperand(), Ty);
1515
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001516 // sext(zext(x)) --> zext(x)
1517 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1518 return getZeroExtendExpr(SZ->getOperand(), Ty);
1519
Dan Gohman74a0ba12009-07-13 20:55:53 +00001520 // Before doing any expensive analysis, check to see if we've already
1521 // computed a SCEV for this Op and Ty.
1522 FoldingSetNodeID ID;
1523 ID.AddInteger(scSignExtend);
1524 ID.AddPointer(Op);
1525 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001526 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001527 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1528
Nick Lewyckyb32c8942011-01-22 22:06:21 +00001529 // If the input value is provably positive, build a zext instead.
1530 if (isKnownNonNegative(Op))
1531 return getZeroExtendExpr(Op, Ty);
1532
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001533 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1534 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1535 // It's possible the bits taken off by the truncate were all sign bits. If
1536 // so, we should be able to simplify this further.
1537 const SCEV *X = ST->getOperand();
1538 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001539 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1540 unsigned NewBits = getTypeSizeInBits(Ty);
1541 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001542 CR.sextOrTrunc(NewBits)))
1543 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001544 }
1545
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001546 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1547 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1548 if (SA->getNumOperands() == 2) {
1549 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1550 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1551 if (SMul && SC1) {
1552 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001553 const APInt &C1 = SC1->getValue()->getValue();
1554 const APInt &C2 = SC2->getValue()->getValue();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001555 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001556 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001557 return getAddExpr(getSignExtendExpr(SC1, Ty),
1558 getSignExtendExpr(SMul, Ty));
1559 }
1560 }
1561 }
1562 }
Dan Gohman76466372009-04-27 20:16:15 +00001563 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001564 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001565 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001566 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001567 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001568 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001569 const SCEV *Start = AR->getStart();
1570 const SCEV *Step = AR->getStepRecurrence(*this);
1571 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1572 const Loop *L = AR->getLoop();
1573
Dan Gohman62ef6a72009-07-25 01:22:26 +00001574 // If we have special knowledge that this addrec won't overflow,
1575 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001576 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Sanjoy Das4153f472015-02-18 01:47:07 +00001577 return getAddRecExpr(
1578 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1579 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001580
Dan Gohman76466372009-04-27 20:16:15 +00001581 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1582 // Note that this serves two purposes: It filters out loops that are
1583 // simply not analyzable, and it covers the case where this code is
1584 // being called from within backedge-taken count analysis, such that
1585 // attempting to ask for the backedge-taken count would likely result
1586 // in infinite recursion. In the later case, the analysis code will
1587 // cope with a conservative value, and it will take care to purge
1588 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001589 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001590 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001591 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001592 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001593
1594 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001595 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001596 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001597 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001598 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001599 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1600 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001601 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001602 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001603 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001604 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1605 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1606 const SCEV *WideMaxBECount =
1607 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001608 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001609 getAddExpr(WideStart,
1610 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001611 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001612 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001613 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1614 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001615 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001616 return getAddRecExpr(
1617 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1618 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001619 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001620 // Similar to above, only this time treat the step value as unsigned.
1621 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001622 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001623 getAddExpr(WideStart,
1624 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001625 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001626 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001627 // If AR wraps around then
1628 //
1629 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1630 // => SAdd != OperandExtendedAdd
1631 //
1632 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1633 // (SAdd == OperandExtendedAdd => AR is NW)
1634
1635 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1636
Dan Gohman8c129d72009-07-16 17:34:36 +00001637 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001638 return getAddRecExpr(
1639 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1640 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001641 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001642 }
1643
1644 // If the backedge is guarded by a comparison with the pre-inc value
1645 // the addrec is safe. Also, if the entry is guarded by a comparison
1646 // with the start value and the backedge is guarded by a comparison
1647 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001648 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001649 const SCEV *OverflowLimit =
1650 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001651 if (OverflowLimit &&
1652 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1653 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1654 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1655 OverflowLimit)))) {
1656 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1657 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001658 return getAddRecExpr(
1659 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1660 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001661 }
1662 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001663 // If Start and Step are constants, check if we can apply this
1664 // transformation:
1665 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1666 auto SC1 = dyn_cast<SCEVConstant>(Start);
1667 auto SC2 = dyn_cast<SCEVConstant>(Step);
1668 if (SC1 && SC2) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001669 const APInt &C1 = SC1->getValue()->getValue();
1670 const APInt &C2 = SC2->getValue()->getValue();
1671 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1672 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001673 Start = getSignExtendExpr(Start, Ty);
1674 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1675 L, AR->getNoWrapFlags());
1676 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1677 }
1678 }
Dan Gohman76466372009-04-27 20:16:15 +00001679 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001680
Dan Gohman74a0ba12009-07-13 20:55:53 +00001681 // The cast wasn't folded; create an explicit cast node.
1682 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001683 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001684 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1685 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001686 UniqueSCEVs.InsertNode(S, IP);
1687 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001688}
1689
Dan Gohman8db2edc2009-06-13 15:56:47 +00001690/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1691/// unspecified bits out to the given type.
1692///
Dan Gohmanaf752342009-07-07 17:06:11 +00001693const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001694 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001695 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1696 "This is not an extending conversion!");
1697 assert(isSCEVable(Ty) &&
1698 "This is not a conversion to a SCEVable type!");
1699 Ty = getEffectiveSCEVType(Ty);
1700
1701 // Sign-extend negative constants.
1702 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1703 if (SC->getValue()->getValue().isNegative())
1704 return getSignExtendExpr(Op, Ty);
1705
1706 // Peel off a truncate cast.
1707 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001708 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001709 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1710 return getAnyExtendExpr(NewOp, Ty);
1711 return getTruncateOrNoop(NewOp, Ty);
1712 }
1713
1714 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001715 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001716 if (!isa<SCEVZeroExtendExpr>(ZExt))
1717 return ZExt;
1718
1719 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001720 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001721 if (!isa<SCEVSignExtendExpr>(SExt))
1722 return SExt;
1723
Dan Gohman51ad99d2010-01-21 02:09:26 +00001724 // Force the cast to be folded into the operands of an addrec.
1725 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1726 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001727 for (const SCEV *Op : AR->operands())
1728 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001729 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001730 }
1731
Dan Gohman8db2edc2009-06-13 15:56:47 +00001732 // If the expression is obviously signed, use the sext cast value.
1733 if (isa<SCEVSMaxExpr>(Op))
1734 return SExt;
1735
1736 // Absent any other information, use the zext cast value.
1737 return ZExt;
1738}
1739
Dan Gohman038d02e2009-06-14 22:58:51 +00001740/// CollectAddOperandsWithScales - Process the given Ops list, which is
1741/// a list of operands to be added under the given scale, update the given
1742/// map. This is a helper function for getAddRecExpr. As an example of
1743/// what it does, given a sequence of operands that would form an add
1744/// expression like this:
1745///
Tobias Grosserba49e422014-03-05 10:37:17 +00001746/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001747///
1748/// where A and B are constants, update the map with these values:
1749///
1750/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1751///
1752/// and add 13 + A*B*29 to AccumulatedConstant.
1753/// This will allow getAddRecExpr to produce this:
1754///
1755/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1756///
1757/// This form often exposes folding opportunities that are hidden in
1758/// the original operand list.
1759///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001760/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001761/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1762/// the common case where no interesting opportunities are present, and
1763/// is also used as a check to avoid infinite recursion.
1764///
1765static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001766CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001767 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001768 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001769 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001770 const APInt &Scale,
1771 ScalarEvolution &SE) {
1772 bool Interesting = false;
1773
Dan Gohman45073042010-06-18 19:12:32 +00001774 // Iterate over the add operands. They are sorted, with constants first.
1775 unsigned i = 0;
1776 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1777 ++i;
1778 // Pull a buried constant out to the outside.
1779 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1780 Interesting = true;
1781 AccumulatedConstant += Scale * C->getValue()->getValue();
1782 }
1783
1784 // Next comes everything else. We're especially interested in multiplies
1785 // here, but they're in the middle, so just visit the rest with one loop.
1786 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001787 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1788 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1789 APInt NewScale =
1790 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1791 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1792 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001793 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001794 Interesting |=
1795 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001796 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001797 NewScale, SE);
1798 } else {
1799 // A multiplication of a constant with some other value. Update
1800 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001801 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1802 const SCEV *Key = SE.getMulExpr(MulOps);
1803 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001804 M.insert(std::make_pair(Key, NewScale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001805 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001806 NewOps.push_back(Pair.first->first);
1807 } else {
1808 Pair.first->second += NewScale;
1809 // The map already had an entry for this value, which may indicate
1810 // a folding opportunity.
1811 Interesting = true;
1812 }
1813 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001814 } else {
1815 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001816 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001817 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001818 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001819 NewOps.push_back(Pair.first->first);
1820 } else {
1821 Pair.first->second += Scale;
1822 // The map already had an entry for this value, which may indicate
1823 // a folding opportunity.
1824 Interesting = true;
1825 }
1826 }
1827 }
1828
1829 return Interesting;
1830}
1831
1832namespace {
1833 struct APIntCompare {
1834 bool operator()(const APInt &LHS, const APInt &RHS) const {
1835 return LHS.ult(RHS);
1836 }
1837 };
1838}
1839
Sanjoy Das81401d42015-01-10 23:41:24 +00001840// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1841// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1842// can't-overflow flags for the operation if possible.
1843static SCEV::NoWrapFlags
1844StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1845 const SmallVectorImpl<const SCEV *> &Ops,
1846 SCEV::NoWrapFlags OldFlags) {
1847 using namespace std::placeholders;
1848
1849 bool CanAnalyze =
1850 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1851 (void)CanAnalyze;
1852 assert(CanAnalyze && "don't call from other places!");
1853
1854 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1855 SCEV::NoWrapFlags SignOrUnsignWrap =
1856 ScalarEvolution::maskFlags(OldFlags, SignOrUnsignMask);
1857
1858 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1859 auto IsKnownNonNegative =
1860 std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1);
1861
1862 if (SignOrUnsignWrap == SCEV::FlagNSW &&
1863 std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative))
1864 return ScalarEvolution::setFlags(OldFlags,
1865 (SCEV::NoWrapFlags)SignOrUnsignMask);
1866
1867 return OldFlags;
1868}
1869
Dan Gohman4d5435d2009-05-24 23:45:28 +00001870/// getAddExpr - Get a canonical add expression, or something simpler if
1871/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001872const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00001873 SCEV::NoWrapFlags Flags) {
1874 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1875 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00001876 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00001877 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00001878#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00001879 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00001880 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00001881 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00001882 "SCEVAddExpr operand types don't match!");
1883#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00001884
Sanjoy Das81401d42015-01-10 23:41:24 +00001885 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001886
Chris Lattnerd934c702004-04-02 20:23:17 +00001887 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00001888 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00001889
1890 // If there are any constants, fold them together.
1891 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00001892 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001893 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00001894 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00001895 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001896 // We found two constants, fold them together!
Dan Gohman0652fd52009-06-14 22:47:23 +00001897 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1898 RHSC->getValue()->getValue());
Dan Gohman011cf682009-06-14 22:53:57 +00001899 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001900 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001901 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001902 }
1903
1904 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001905 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001906 Ops.erase(Ops.begin());
1907 --Idx;
1908 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001909
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001910 if (Ops.size() == 1) return Ops[0];
1911 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001912
Dan Gohman15871f22010-08-27 21:39:59 +00001913 // Okay, check to see if the same value occurs in the operand list more than
1914 // once. If so, merge them together into an multiply expression. Since we
1915 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00001916 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00001917 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00001918 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00001919 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00001920 // Scan ahead to count how many equal operands there are.
1921 unsigned Count = 2;
1922 while (i+Count != e && Ops[i+Count] == Ops[i])
1923 ++Count;
1924 // Merge the values into a multiply.
1925 const SCEV *Scale = getConstant(Ty, Count);
1926 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1927 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00001928 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00001929 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00001930 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00001931 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00001932 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00001933 }
Dan Gohmane67b2872010-08-12 14:46:54 +00001934 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00001935 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00001936
Dan Gohman2e55cc52009-05-08 21:03:19 +00001937 // Check for truncates. If all the operands are truncated from the same
1938 // type, see if factoring out the truncate would permit the result to be
1939 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1940 // if the contents of the resulting outer trunc fold to something simple.
1941 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1942 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00001943 Type *DstType = Trunc->getType();
1944 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00001945 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001946 bool Ok = true;
1947 // Check all the operands to see if they can be represented in the
1948 // source type of the truncate.
1949 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1950 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1951 if (T->getOperand()->getType() != SrcType) {
1952 Ok = false;
1953 break;
1954 }
1955 LargeOps.push_back(T->getOperand());
1956 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001957 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001958 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001959 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001960 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1961 if (const SCEVTruncateExpr *T =
1962 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1963 if (T->getOperand()->getType() != SrcType) {
1964 Ok = false;
1965 break;
1966 }
1967 LargeMulOps.push_back(T->getOperand());
1968 } else if (const SCEVConstant *C =
1969 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001970 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001971 } else {
1972 Ok = false;
1973 break;
1974 }
1975 }
1976 if (Ok)
1977 LargeOps.push_back(getMulExpr(LargeMulOps));
1978 } else {
1979 Ok = false;
1980 break;
1981 }
1982 }
1983 if (Ok) {
1984 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00001985 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00001986 // If it folds to something simple, use it. Otherwise, don't.
1987 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1988 return getTruncateExpr(Fold, DstType);
1989 }
1990 }
1991
1992 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00001993 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1994 ++Idx;
1995
1996 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00001997 if (Idx < Ops.size()) {
1998 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00001999 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002000 // If we have an add, expand the add operands onto the end of the operands
2001 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002002 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002003 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002004 DeletedAdd = true;
2005 }
2006
2007 // If we deleted at least one add, we added operands to the end of the list,
2008 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002009 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002010 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002011 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002012 }
2013
2014 // Skip over the add expression until we get to a multiply.
2015 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2016 ++Idx;
2017
Dan Gohman038d02e2009-06-14 22:58:51 +00002018 // Check to see if there are any folding opportunities present with
2019 // operands multiplied by constant values.
2020 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2021 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002022 DenseMap<const SCEV *, APInt> M;
2023 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002024 APInt AccumulatedConstant(BitWidth, 0);
2025 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002026 Ops.data(), Ops.size(),
2027 APInt(BitWidth, 1), *this)) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002028 // Some interesting folding opportunity is present, so its worthwhile to
2029 // re-generate the operands list. Group the operands by constant scale,
2030 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002031 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Craig Topper31ee5862013-07-03 15:07:05 +00002032 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002033 E = NewOps.end(); I != E; ++I)
2034 MulOpLists[M.find(*I)->second].push_back(*I);
2035 // Re-generate the operands list.
2036 Ops.clear();
2037 if (AccumulatedConstant != 0)
2038 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohmance973df2009-06-24 04:48:43 +00002039 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
2040 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman038d02e2009-06-14 22:58:51 +00002041 if (I->first != 0)
Dan Gohmance973df2009-06-24 04:48:43 +00002042 Ops.push_back(getMulExpr(getConstant(I->first),
2043 getAddExpr(I->second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002044 if (Ops.empty())
Dan Gohman1d2ded72010-05-03 22:09:21 +00002045 return getConstant(Ty, 0);
Dan Gohman038d02e2009-06-14 22:58:51 +00002046 if (Ops.size() == 1)
2047 return Ops[0];
2048 return getAddExpr(Ops);
2049 }
2050 }
2051
Chris Lattnerd934c702004-04-02 20:23:17 +00002052 // If we are adding something to a multiply expression, make sure the
2053 // something is not already an operand of the multiply. If so, merge it into
2054 // the multiply.
2055 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002056 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002057 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002058 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002059 if (isa<SCEVConstant>(MulOpSCEV))
2060 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002061 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002062 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002063 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002064 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002065 if (Mul->getNumOperands() != 2) {
2066 // If the multiply has more than two operands, we must get the
2067 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002068 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2069 Mul->op_begin()+MulOp);
2070 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002071 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002072 }
Dan Gohman1d2ded72010-05-03 22:09:21 +00002073 const SCEV *One = getConstant(Ty, 1);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002074 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002075 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002076 if (Ops.size() == 2) return OuterMul;
2077 if (AddOp < Idx) {
2078 Ops.erase(Ops.begin()+AddOp);
2079 Ops.erase(Ops.begin()+Idx-1);
2080 } else {
2081 Ops.erase(Ops.begin()+Idx);
2082 Ops.erase(Ops.begin()+AddOp-1);
2083 }
2084 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002085 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002086 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002087
Chris Lattnerd934c702004-04-02 20:23:17 +00002088 // Check this multiply against other multiplies being added together.
2089 for (unsigned OtherMulIdx = Idx+1;
2090 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2091 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002092 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002093 // If MulOp occurs in OtherMul, we can fold the two multiplies
2094 // together.
2095 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2096 OMulOp != e; ++OMulOp)
2097 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2098 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002099 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002100 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002101 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002102 Mul->op_begin()+MulOp);
2103 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002104 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002105 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002106 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002107 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002108 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002109 OtherMul->op_begin()+OMulOp);
2110 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002111 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002112 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002113 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2114 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002115 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002116 Ops.erase(Ops.begin()+Idx);
2117 Ops.erase(Ops.begin()+OtherMulIdx-1);
2118 Ops.push_back(OuterMul);
2119 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002120 }
2121 }
2122 }
2123 }
2124
2125 // If there are any add recurrences in the operands list, see if any other
2126 // added values are loop invariant. If so, we can fold them into the
2127 // recurrence.
2128 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2129 ++Idx;
2130
2131 // Scan over all recurrences, trying to fold loop invariants into them.
2132 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2133 // Scan all of the other operands to this add and add them to the vector if
2134 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002135 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002136 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002137 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002138 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002139 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002140 LIOps.push_back(Ops[i]);
2141 Ops.erase(Ops.begin()+i);
2142 --i; --e;
2143 }
2144
2145 // If we found some loop invariants, fold them into the recurrence.
2146 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002147 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002148 LIOps.push_back(AddRec->getStart());
2149
Dan Gohmanaf752342009-07-07 17:06:11 +00002150 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002151 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002152 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002153
Dan Gohman16206132010-06-30 07:16:37 +00002154 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002155 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002156 // Always propagate NW.
2157 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002158 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002159
Chris Lattnerd934c702004-04-02 20:23:17 +00002160 // If all of the other operands were loop invariant, we are done.
2161 if (Ops.size() == 1) return NewRec;
2162
Nick Lewyckydb66b822011-09-06 05:08:09 +00002163 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002164 for (unsigned i = 0;; ++i)
2165 if (Ops[i] == AddRec) {
2166 Ops[i] = NewRec;
2167 break;
2168 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002169 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002170 }
2171
2172 // Okay, if there weren't any loop invariants to be folded, check to see if
2173 // there are multiple AddRec's with the same loop induction variable being
2174 // added together. If so, we can fold them.
2175 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002176 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2177 ++OtherIdx)
2178 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2179 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2180 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2181 AddRec->op_end());
2182 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2183 ++OtherIdx)
Dan Gohman028c1812010-08-29 14:53:34 +00002184 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohmanc866bf42010-08-27 20:45:56 +00002185 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002186 if (OtherAddRec->getLoop() == AddRecLoop) {
2187 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2188 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002189 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002190 AddRecOps.append(OtherAddRec->op_begin()+i,
2191 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002192 break;
2193 }
Dan Gohman028c1812010-08-29 14:53:34 +00002194 AddRecOps[i] = getAddExpr(AddRecOps[i],
2195 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002196 }
2197 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002198 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002199 // Step size has changed, so we cannot guarantee no self-wraparound.
2200 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002201 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002202 }
2203
2204 // Otherwise couldn't fold anything into this recurrence. Move onto the
2205 // next one.
2206 }
2207
2208 // Okay, it looks like we really DO need an add expr. Check to see if we
2209 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002210 FoldingSetNodeID ID;
2211 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002212 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2213 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002214 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002215 SCEVAddExpr *S =
2216 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2217 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002218 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2219 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002220 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2221 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002222 UniqueSCEVs.InsertNode(S, IP);
2223 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002224 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002225 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002226}
2227
Nick Lewycky287682e2011-10-04 06:51:26 +00002228static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2229 uint64_t k = i*j;
2230 if (j > 1 && k / j != i) Overflow = true;
2231 return k;
2232}
2233
2234/// Compute the result of "n choose k", the binomial coefficient. If an
2235/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002236/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002237static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2238 // We use the multiplicative formula:
2239 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2240 // At each iteration, we take the n-th term of the numeral and divide by the
2241 // (k-n)th term of the denominator. This division will always produce an
2242 // integral result, and helps reduce the chance of overflow in the
2243 // intermediate computations. However, we can still overflow even when the
2244 // final result would fit.
2245
2246 if (n == 0 || n == k) return 1;
2247 if (k > n) return 0;
2248
2249 if (k > n/2)
2250 k = n-k;
2251
2252 uint64_t r = 1;
2253 for (uint64_t i = 1; i <= k; ++i) {
2254 r = umul_ov(r, n-(i-1), Overflow);
2255 r /= i;
2256 }
2257 return r;
2258}
2259
Nick Lewycky05044c22014-12-06 00:45:50 +00002260/// Determine if any of the operands in this SCEV are a constant or if
2261/// any of the add or multiply expressions in this SCEV contain a constant.
2262static bool containsConstantSomewhere(const SCEV *StartExpr) {
2263 SmallVector<const SCEV *, 4> Ops;
2264 Ops.push_back(StartExpr);
2265 while (!Ops.empty()) {
2266 const SCEV *CurrentExpr = Ops.pop_back_val();
2267 if (isa<SCEVConstant>(*CurrentExpr))
2268 return true;
2269
2270 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2271 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002272 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002273 }
2274 }
2275 return false;
2276}
2277
Dan Gohman4d5435d2009-05-24 23:45:28 +00002278/// getMulExpr - Get a canonical multiply expression, or something simpler if
2279/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002280const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002281 SCEV::NoWrapFlags Flags) {
2282 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2283 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002284 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002285 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002286#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002287 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002288 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002289 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002290 "SCEVMulExpr operand types don't match!");
2291#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002292
Sanjoy Das81401d42015-01-10 23:41:24 +00002293 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002294
Chris Lattnerd934c702004-04-02 20:23:17 +00002295 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002296 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002297
2298 // If there are any constants, fold them together.
2299 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002301
2302 // C1*(C2+V) -> C1*C2 + C1*V
2303 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002304 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2305 // If any of Add's ops are Adds or Muls with a constant,
2306 // apply this transformation as well.
2307 if (Add->getNumOperands() == 2)
2308 if (containsConstantSomewhere(Add))
2309 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2310 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002311
Chris Lattnerd934c702004-04-02 20:23:17 +00002312 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002313 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002314 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002315 ConstantInt *Fold = ConstantInt::get(getContext(),
2316 LHSC->getValue()->getValue() *
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002317 RHSC->getValue()->getValue());
2318 Ops[0] = getConstant(Fold);
2319 Ops.erase(Ops.begin()+1); // Erase the folded element
2320 if (Ops.size() == 1) return Ops[0];
2321 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002322 }
2323
2324 // If we are left with a constant one being multiplied, strip it off.
2325 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2326 Ops.erase(Ops.begin());
2327 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002328 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002329 // If we have a multiply of zero, it will always be zero.
2330 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002331 } else if (Ops[0]->isAllOnesValue()) {
2332 // If we have a mul by -1 of an add, try distributing the -1 among the
2333 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002334 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002335 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2336 SmallVector<const SCEV *, 4> NewOps;
2337 bool AnyFolded = false;
Andrew Trick8b55b732011-03-14 16:50:06 +00002338 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2339 E = Add->op_end(); I != E; ++I) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002340 const SCEV *Mul = getMulExpr(Ops[0], *I);
2341 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2342 NewOps.push_back(Mul);
2343 }
2344 if (AnyFolded)
2345 return getAddExpr(NewOps);
2346 }
Andrew Tricke92dcce2011-03-14 17:38:54 +00002347 else if (const SCEVAddRecExpr *
2348 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2349 // Negation preserves a recurrence's no self-wrap property.
2350 SmallVector<const SCEV *, 4> Operands;
2351 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2352 E = AddRec->op_end(); I != E; ++I) {
2353 Operands.push_back(getMulExpr(Ops[0], *I));
2354 }
2355 return getAddRecExpr(Operands, AddRec->getLoop(),
2356 AddRec->getNoWrapFlags(SCEV::FlagNW));
2357 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002358 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002359 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002360
2361 if (Ops.size() == 1)
2362 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002363 }
2364
2365 // Skip over the add expression until we get to a multiply.
2366 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2367 ++Idx;
2368
Chris Lattnerd934c702004-04-02 20:23:17 +00002369 // If there are mul operands inline them all into this expression.
2370 if (Idx < Ops.size()) {
2371 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002372 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002373 // If we have an mul, expand the mul operands onto the end of the operands
2374 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002375 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002376 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002377 DeletedMul = true;
2378 }
2379
2380 // If we deleted at least one mul, we added operands to the end of the list,
2381 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002382 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002383 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002384 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002385 }
2386
2387 // If there are any add recurrences in the operands list, see if any other
2388 // added values are loop invariant. If so, we can fold them into the
2389 // recurrence.
2390 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2391 ++Idx;
2392
2393 // Scan over all recurrences, trying to fold loop invariants into them.
2394 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2395 // Scan all of the other operands to this mul and add them to the vector if
2396 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002397 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002398 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002399 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002400 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002401 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002402 LIOps.push_back(Ops[i]);
2403 Ops.erase(Ops.begin()+i);
2404 --i; --e;
2405 }
2406
2407 // If we found some loop invariants, fold them into the recurrence.
2408 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002409 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002410 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002411 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002412 const SCEV *Scale = getMulExpr(LIOps);
2413 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2414 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002415
Dan Gohman16206132010-06-30 07:16:37 +00002416 // Build the new addrec. Propagate the NUW and NSW flags if both the
2417 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002418 //
2419 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002420 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002421 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2422 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002423
2424 // If all of the other operands were loop invariant, we are done.
2425 if (Ops.size() == 1) return NewRec;
2426
Nick Lewyckydb66b822011-09-06 05:08:09 +00002427 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002428 for (unsigned i = 0;; ++i)
2429 if (Ops[i] == AddRec) {
2430 Ops[i] = NewRec;
2431 break;
2432 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002433 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002434 }
2435
2436 // Okay, if there weren't any loop invariants to be folded, check to see if
2437 // there are multiple AddRec's with the same loop induction variable being
2438 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002439
2440 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2441 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2442 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2443 // ]]],+,...up to x=2n}.
2444 // Note that the arguments to choose() are always integers with values
2445 // known at compile time, never SCEV objects.
2446 //
2447 // The implementation avoids pointless extra computations when the two
2448 // addrec's are of different length (mathematically, it's equivalent to
2449 // an infinite stream of zeros on the right).
2450 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002451 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002452 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002453 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002454 const SCEVAddRecExpr *OtherAddRec =
2455 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2456 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002457 continue;
2458
Nick Lewycky97756402014-09-01 05:17:15 +00002459 bool Overflow = false;
2460 Type *Ty = AddRec->getType();
2461 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2462 SmallVector<const SCEV*, 7> AddRecOps;
2463 for (int x = 0, xe = AddRec->getNumOperands() +
2464 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2465 const SCEV *Term = getConstant(Ty, 0);
2466 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2467 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2468 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2469 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2470 z < ze && !Overflow; ++z) {
2471 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2472 uint64_t Coeff;
2473 if (LargerThan64Bits)
2474 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2475 else
2476 Coeff = Coeff1*Coeff2;
2477 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2478 const SCEV *Term1 = AddRec->getOperand(y-z);
2479 const SCEV *Term2 = OtherAddRec->getOperand(z);
2480 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002481 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002482 }
Nick Lewycky97756402014-09-01 05:17:15 +00002483 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002484 }
Nick Lewycky97756402014-09-01 05:17:15 +00002485 if (!Overflow) {
2486 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2487 SCEV::FlagAnyWrap);
2488 if (Ops.size() == 2) return NewAddRec;
2489 Ops[Idx] = NewAddRec;
2490 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2491 OpsModified = true;
2492 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2493 if (!AddRec)
2494 break;
2495 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002496 }
Nick Lewycky97756402014-09-01 05:17:15 +00002497 if (OpsModified)
2498 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002499
2500 // Otherwise couldn't fold anything into this recurrence. Move onto the
2501 // next one.
2502 }
2503
2504 // Okay, it looks like we really DO need an mul expr. Check to see if we
2505 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002506 FoldingSetNodeID ID;
2507 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002508 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2509 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002510 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002511 SCEVMulExpr *S =
2512 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2513 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002514 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2515 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002516 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2517 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002518 UniqueSCEVs.InsertNode(S, IP);
2519 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002520 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002521 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002522}
2523
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002524/// getUDivExpr - Get a canonical unsigned division expression, or something
2525/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002526const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2527 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002528 assert(getEffectiveSCEVType(LHS->getType()) ==
2529 getEffectiveSCEVType(RHS->getType()) &&
2530 "SCEVUDivExpr operand types don't match!");
2531
Dan Gohmana30370b2009-05-04 22:02:23 +00002532 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002533 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002534 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002535 // If the denominator is zero, the result of the udiv is undefined. Don't
2536 // try to analyze it, because the resolution chosen here may differ from
2537 // the resolution chosen in other parts of the compiler.
2538 if (!RHSC->getValue()->isZero()) {
2539 // Determine if the division can be folded into the operands of
2540 // its operands.
2541 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002542 Type *Ty = LHS->getType();
Dan Gohmanacd700a2010-04-22 01:35:11 +00002543 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002544 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002545 // For non-power-of-two values, effectively round the value up to the
2546 // nearest power of two.
2547 if (!RHSC->getValue()->getValue().isPowerOf2())
2548 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002549 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002550 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002551 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2552 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002553 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2554 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2555 const APInt &StepInt = Step->getValue()->getValue();
2556 const APInt &DivInt = RHSC->getValue()->getValue();
2557 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002558 getZeroExtendExpr(AR, ExtTy) ==
2559 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2560 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002561 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002562 SmallVector<const SCEV *, 4> Operands;
2563 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2564 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick8b55b732011-03-14 16:50:06 +00002565 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002566 SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002567 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002568 /// Get a canonical UDivExpr for a recurrence.
2569 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2570 // We can currently only fold X%N if X is constant.
2571 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2572 if (StartC && !DivInt.urem(StepInt) &&
2573 getZeroExtendExpr(AR, ExtTy) ==
2574 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2575 getZeroExtendExpr(Step, ExtTy),
2576 AR->getLoop(), SCEV::FlagAnyWrap)) {
2577 const APInt &StartInt = StartC->getValue()->getValue();
2578 const APInt &StartRem = StartInt.urem(StepInt);
2579 if (StartRem != 0)
2580 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2581 AR->getLoop(), SCEV::FlagNW);
2582 }
2583 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002584 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2585 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2586 SmallVector<const SCEV *, 4> Operands;
2587 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2588 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2589 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2590 // Find an operand that's safely divisible.
2591 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2592 const SCEV *Op = M->getOperand(i);
2593 const SCEV *Div = getUDivExpr(Op, RHSC);
2594 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2595 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2596 M->op_end());
2597 Operands[i] = Div;
2598 return getMulExpr(Operands);
2599 }
2600 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002601 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002602 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Andrew Trick7d1eea82011-04-27 18:17:36 +00002603 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002604 SmallVector<const SCEV *, 4> Operands;
2605 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2606 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2607 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2608 Operands.clear();
2609 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2610 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2611 if (isa<SCEVUDivExpr>(Op) ||
2612 getMulExpr(Op, RHS) != A->getOperand(i))
2613 break;
2614 Operands.push_back(Op);
2615 }
2616 if (Operands.size() == A->getNumOperands())
2617 return getAddExpr(Operands);
2618 }
2619 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002620
Dan Gohmanacd700a2010-04-22 01:35:11 +00002621 // Fold if both operands are constant.
2622 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2623 Constant *LHSCV = LHSC->getValue();
2624 Constant *RHSCV = RHSC->getValue();
2625 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2626 RHSCV)));
2627 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002628 }
2629 }
2630
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002631 FoldingSetNodeID ID;
2632 ID.AddInteger(scUDivExpr);
2633 ID.AddPointer(LHS);
2634 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002635 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002637 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2638 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002639 UniqueSCEVs.InsertNode(S, IP);
2640 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002641}
2642
Nick Lewycky31eaca52014-01-27 10:04:03 +00002643static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2644 APInt A = C1->getValue()->getValue().abs();
2645 APInt B = C2->getValue()->getValue().abs();
2646 uint32_t ABW = A.getBitWidth();
2647 uint32_t BBW = B.getBitWidth();
2648
2649 if (ABW > BBW)
2650 B = B.zext(ABW);
2651 else if (ABW < BBW)
2652 A = A.zext(BBW);
2653
2654 return APIntOps::GreatestCommonDivisor(A, B);
2655}
2656
2657/// getUDivExactExpr - Get a canonical unsigned division expression, or
2658/// something simpler if possible. There is no representation for an exact udiv
2659/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2660/// We can't do this when it's not exact because the udiv may be clearing bits.
2661const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2662 const SCEV *RHS) {
2663 // TODO: we could try to find factors in all sorts of things, but for now we
2664 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2665 // end of this file for inspiration.
2666
2667 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2668 if (!Mul)
2669 return getUDivExpr(LHS, RHS);
2670
2671 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2672 // If the mulexpr multiplies by a constant, then that constant must be the
2673 // first element of the mulexpr.
2674 if (const SCEVConstant *LHSCst =
2675 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2676 if (LHSCst == RHSCst) {
2677 SmallVector<const SCEV *, 2> Operands;
2678 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2679 return getMulExpr(Operands);
2680 }
2681
2682 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2683 // that there's a factor provided by one of the other terms. We need to
2684 // check.
2685 APInt Factor = gcd(LHSCst, RHSCst);
2686 if (!Factor.isIntN(1)) {
2687 LHSCst = cast<SCEVConstant>(
2688 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2689 RHSCst = cast<SCEVConstant>(
2690 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2691 SmallVector<const SCEV *, 2> Operands;
2692 Operands.push_back(LHSCst);
2693 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2694 LHS = getMulExpr(Operands);
2695 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002696 Mul = dyn_cast<SCEVMulExpr>(LHS);
2697 if (!Mul)
2698 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002699 }
2700 }
2701 }
2702
2703 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2704 if (Mul->getOperand(i) == RHS) {
2705 SmallVector<const SCEV *, 2> Operands;
2706 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2707 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2708 return getMulExpr(Operands);
2709 }
2710 }
2711
2712 return getUDivExpr(LHS, RHS);
2713}
Chris Lattnerd934c702004-04-02 20:23:17 +00002714
Dan Gohman4d5435d2009-05-24 23:45:28 +00002715/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2716/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002717const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2718 const Loop *L,
2719 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002720 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002721 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002722 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002723 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002724 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002725 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002726 }
2727
2728 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002729 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002730}
2731
Dan Gohman4d5435d2009-05-24 23:45:28 +00002732/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2733/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002734const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002735ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002736 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002737 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002738#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002739 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002740 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002741 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002742 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002743 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002744 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002745 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002746#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002747
Dan Gohmanbe928e32008-06-18 16:23:07 +00002748 if (Operands.back()->isZero()) {
2749 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002750 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002751 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002752
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002753 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2754 // use that information to infer NUW and NSW flags. However, computing a
2755 // BE count requires calling getAddRecExpr, so we may not yet have a
2756 // meaningful BE count at this point (and if we don't, we'd be stuck
2757 // with a SCEVCouldNotCompute as the cached BE count).
2758
Sanjoy Das81401d42015-01-10 23:41:24 +00002759 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002760
Dan Gohman223a5d22008-08-08 18:33:12 +00002761 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002762 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002763 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman63c020a2010-08-13 20:23:25 +00002764 if (L->contains(NestedLoop) ?
Dan Gohman51ad99d2010-01-21 02:09:26 +00002765 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman63c020a2010-08-13 20:23:25 +00002766 (!NestedLoop->contains(L) &&
Dan Gohman51ad99d2010-01-21 02:09:26 +00002767 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002768 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002769 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002770 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002771 // AddRecs require their operands be loop-invariant with respect to their
2772 // loops. Don't perform this transformation if it would break this
2773 // requirement.
2774 bool AllInvariant = true;
2775 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002776 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002777 AllInvariant = false;
2778 break;
2779 }
2780 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002781 // Create a recurrence for the outer loop with the same step size.
2782 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002783 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2784 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002785 SCEV::NoWrapFlags OuterFlags =
2786 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002787
2788 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohmancc030b72009-06-26 22:36:20 +00002789 AllInvariant = true;
2790 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002791 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002792 AllInvariant = false;
2793 break;
2794 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002795 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002796 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002797 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002798 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2799 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002800 SCEV::NoWrapFlags InnerFlags =
2801 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002802 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2803 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002804 }
2805 // Reset Operands to its original state.
2806 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002807 }
2808 }
2809
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002810 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2811 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002812 FoldingSetNodeID ID;
2813 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002814 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2815 ID.AddPointer(Operands[i]);
2816 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002817 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002818 SCEVAddRecExpr *S =
2819 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2820 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002821 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2822 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002823 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2824 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002825 UniqueSCEVs.InsertNode(S, IP);
2826 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002827 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002828 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002829}
2830
Dan Gohmanabd17092009-06-24 14:49:00 +00002831const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2832 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002833 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002834 Ops.push_back(LHS);
2835 Ops.push_back(RHS);
2836 return getSMaxExpr(Ops);
2837}
2838
Dan Gohmanaf752342009-07-07 17:06:11 +00002839const SCEV *
2840ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002841 assert(!Ops.empty() && "Cannot get empty smax!");
2842 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002843#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002844 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002845 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002846 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002847 "SCEVSMaxExpr operand types don't match!");
2848#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002849
2850 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002851 GroupByComplexity(Ops, LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002852
2853 // If there are any constants, fold them together.
2854 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002855 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002856 ++Idx;
2857 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002858 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002859 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002860 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002861 APIntOps::smax(LHSC->getValue()->getValue(),
2862 RHSC->getValue()->getValue()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002863 Ops[0] = getConstant(Fold);
2864 Ops.erase(Ops.begin()+1); // Erase the folded element
2865 if (Ops.size() == 1) return Ops[0];
2866 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002867 }
2868
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002869 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002870 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2871 Ops.erase(Ops.begin());
2872 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002873 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2874 // If we have an smax with a constant maximum-int, it will always be
2875 // maximum-int.
2876 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002877 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002878
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002879 if (Ops.size() == 1) return Ops[0];
2880 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002881
2882 // Find the first SMax
2883 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2884 ++Idx;
2885
2886 // Check to see if one of the operands is an SMax. If so, expand its operands
2887 // onto our operand list, and recurse to simplify.
2888 if (Idx < Ops.size()) {
2889 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002890 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002891 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002892 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002893 DeletedSMax = true;
2894 }
2895
2896 if (DeletedSMax)
2897 return getSMaxExpr(Ops);
2898 }
2899
2900 // Okay, check to see if the same value occurs in the operand list twice. If
2901 // so, delete one. Since we sorted the list, these values are required to
2902 // be adjacent.
2903 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00002904 // X smax Y smax Y --> X smax Y
2905 // X smax Y --> X, if X is always greater than Y
2906 if (Ops[i] == Ops[i+1] ||
2907 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2908 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2909 --i; --e;
2910 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002911 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2912 --i; --e;
2913 }
2914
2915 if (Ops.size() == 1) return Ops[0];
2916
2917 assert(!Ops.empty() && "Reduced smax down to nothing!");
2918
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002919 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002920 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002921 FoldingSetNodeID ID;
2922 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002923 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2924 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002925 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00002927 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2928 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002929 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2930 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002931 UniqueSCEVs.InsertNode(S, IP);
2932 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002933}
2934
Dan Gohmanabd17092009-06-24 14:49:00 +00002935const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2936 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002937 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002938 Ops.push_back(LHS);
2939 Ops.push_back(RHS);
2940 return getUMaxExpr(Ops);
2941}
2942
Dan Gohmanaf752342009-07-07 17:06:11 +00002943const SCEV *
2944ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002945 assert(!Ops.empty() && "Cannot get empty umax!");
2946 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002947#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002948 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002949 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002950 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002951 "SCEVUMaxExpr operand types don't match!");
2952#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002953
2954 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002955 GroupByComplexity(Ops, LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002956
2957 // If there are any constants, fold them together.
2958 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002959 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002960 ++Idx;
2961 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002962 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002963 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002964 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002965 APIntOps::umax(LHSC->getValue()->getValue(),
2966 RHSC->getValue()->getValue()));
2967 Ops[0] = getConstant(Fold);
2968 Ops.erase(Ops.begin()+1); // Erase the folded element
2969 if (Ops.size() == 1) return Ops[0];
2970 LHSC = cast<SCEVConstant>(Ops[0]);
2971 }
2972
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002973 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002974 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2975 Ops.erase(Ops.begin());
2976 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002977 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2978 // If we have an umax with a constant maximum-int, it will always be
2979 // maximum-int.
2980 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002981 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002982
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002983 if (Ops.size() == 1) return Ops[0];
2984 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002985
2986 // Find the first UMax
2987 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2988 ++Idx;
2989
2990 // Check to see if one of the operands is a UMax. If so, expand its operands
2991 // onto our operand list, and recurse to simplify.
2992 if (Idx < Ops.size()) {
2993 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002994 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002995 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002996 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002997 DeletedUMax = true;
2998 }
2999
3000 if (DeletedUMax)
3001 return getUMaxExpr(Ops);
3002 }
3003
3004 // Okay, check to see if the same value occurs in the operand list twice. If
3005 // so, delete one. Since we sorted the list, these values are required to
3006 // be adjacent.
3007 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003008 // X umax Y umax Y --> X umax Y
3009 // X umax Y --> X, if X is always greater than Y
3010 if (Ops[i] == Ops[i+1] ||
3011 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3012 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3013 --i; --e;
3014 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003015 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3016 --i; --e;
3017 }
3018
3019 if (Ops.size() == 1) return Ops[0];
3020
3021 assert(!Ops.empty() && "Reduced umax down to nothing!");
3022
3023 // Okay, it looks like we really DO need a umax expr. Check to see if we
3024 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003025 FoldingSetNodeID ID;
3026 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003027 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3028 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003029 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003031 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3032 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003033 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3034 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003035 UniqueSCEVs.InsertNode(S, IP);
3036 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003037}
3038
Dan Gohmanabd17092009-06-24 14:49:00 +00003039const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3040 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003041 // ~smax(~x, ~y) == smin(x, y).
3042 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3043}
3044
Dan Gohmanabd17092009-06-24 14:49:00 +00003045const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3046 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003047 // ~umax(~x, ~y) == umin(x, y)
3048 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3049}
3050
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003051const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003052 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003053 // constant expression and then folding it back into a ConstantInt.
3054 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003055 if (DL)
3056 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
Dan Gohman11862a62010-04-12 23:03:26 +00003057
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003058 Constant *C = ConstantExpr::getSizeOf(AllocTy);
3059 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003060 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00003061 C = Folded;
Chris Lattner229907c2011-07-18 04:54:35 +00003062 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003063 assert(Ty == IntTy && "Effective SCEV type doesn't match");
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003064 return getTruncateOrZeroExtend(getSCEV(C), Ty);
3065}
3066
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003067const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3068 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003069 unsigned FieldNo) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003070 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003071 // constant expression and then folding it back into a ConstantInt.
3072 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003073 if (DL) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003074 return getConstant(IntTy,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003075 DL->getStructLayout(STy)->getElementOffset(FieldNo));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003076 }
Dan Gohman11862a62010-04-12 23:03:26 +00003077
Dan Gohmancf913832010-01-28 02:15:55 +00003078 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
3079 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003080 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00003081 C = Folded;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003082
Matt Arsenault4ed49b52013-10-21 18:08:09 +00003083 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohmancf913832010-01-28 02:15:55 +00003084 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003085}
3086
Dan Gohmanaf752342009-07-07 17:06:11 +00003087const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003088 // Don't attempt to do anything other than create a SCEVUnknown object
3089 // here. createSCEV only calls getUnknown after checking for all other
3090 // interesting possibilities, and any other code that calls getUnknown
3091 // is doing so in order to hide a value from SCEV canonicalization.
3092
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003093 FoldingSetNodeID ID;
3094 ID.AddInteger(scUnknown);
3095 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003096 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003097 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3098 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3099 "Stale SCEVUnknown in uniquing map!");
3100 return S;
3101 }
3102 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3103 FirstUnknown);
3104 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003105 UniqueSCEVs.InsertNode(S, IP);
3106 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003107}
3108
Chris Lattnerd934c702004-04-02 20:23:17 +00003109//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003110// Basic SCEV Analysis and PHI Idiom Recognition Code
3111//
3112
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003113/// isSCEVable - Test if values of the given type are analyzable within
3114/// the SCEV framework. This primarily includes integer types, and it
3115/// can optionally include pointer types if the ScalarEvolution class
3116/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003117bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003118 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003119 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003120}
3121
3122/// getTypeSizeInBits - Return the size in bits of the specified type,
3123/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003124uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003125 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3126
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003127 // If we have a DataLayout, use it!
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003128 if (DL)
3129 return DL->getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003130
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003131 // Integer types have fixed sizes.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003132 if (Ty->isIntegerTy())
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003133 return Ty->getPrimitiveSizeInBits();
3134
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003135 // The only other support type is pointer. Without DataLayout, conservatively
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003136 // assume pointers are 64-bit.
Duncan Sands19d0b472010-02-16 11:11:14 +00003137 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003138 return 64;
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003139}
3140
3141/// getEffectiveSCEVType - Return a type with the same bitwidth as
3142/// the given type and which represents how SCEV will treat the given
3143/// type, for which isSCEVable must return true. For pointer types,
3144/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003145Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003146 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3147
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003148 if (Ty->isIntegerTy()) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003149 return Ty;
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003150 }
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003151
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003152 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003153 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003154
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003155 if (DL)
3156 return DL->getIntPtrType(Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003157
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003158 // Without DataLayout, conservatively assume pointers are 64-bit.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003159 return Type::getInt64Ty(getContext());
Dan Gohman0a40ad92009-04-16 03:18:22 +00003160}
Chris Lattnerd934c702004-04-02 20:23:17 +00003161
Dan Gohmanaf752342009-07-07 17:06:11 +00003162const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003163 return &CouldNotCompute;
Dan Gohman31efa302009-04-18 17:58:19 +00003164}
3165
Shuxin Yangefc4c012013-07-08 17:33:13 +00003166namespace {
3167 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3168 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3169 // is set iff if find such SCEVUnknown.
3170 //
3171 struct FindInvalidSCEVUnknown {
3172 bool FindOne;
3173 FindInvalidSCEVUnknown() { FindOne = false; }
3174 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003175 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003176 case scConstant:
3177 return false;
3178 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003179 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003180 FindOne = true;
3181 return false;
3182 default:
3183 return true;
3184 }
3185 }
3186 bool isDone() const { return FindOne; }
3187 };
3188}
3189
3190bool ScalarEvolution::checkValidity(const SCEV *S) const {
3191 FindInvalidSCEVUnknown F;
3192 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3193 ST.visitAll(S);
3194
3195 return !F.FindOne;
3196}
3197
Chris Lattnerd934c702004-04-02 20:23:17 +00003198/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3199/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003200const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003201 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003202
Shuxin Yangefc4c012013-07-08 17:33:13 +00003203 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3204 if (I != ValueExprMap.end()) {
3205 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003206 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003207 return S;
3208 else
3209 ValueExprMap.erase(I);
3210 }
Dan Gohmanaf752342009-07-07 17:06:11 +00003211 const SCEV *S = createSCEV(V);
Dan Gohmanc29eeae2010-08-16 16:31:39 +00003212
3213 // The process of creating a SCEV for V may have caused other SCEVs
3214 // to have been created, so it's necessary to insert the new entry
3215 // from scratch, rather than trying to remember the insert position
3216 // above.
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003217 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattnerd934c702004-04-02 20:23:17 +00003218 return S;
3219}
3220
Dan Gohman0a40ad92009-04-16 03:18:22 +00003221/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3222///
Dan Gohmanaf752342009-07-07 17:06:11 +00003223const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003224 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003225 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003226 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003227
Chris Lattner229907c2011-07-18 04:54:35 +00003228 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003229 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003230 return getMulExpr(V,
Owen Anderson5a1acd92009-07-31 20:28:14 +00003231 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003232}
3233
3234/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003235const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003236 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003237 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003238 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003239
Chris Lattner229907c2011-07-18 04:54:35 +00003240 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003241 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003242 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003243 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003244 return getMinusSCEV(AllOnes, V);
3245}
3246
Andrew Trick8b55b732011-03-14 16:50:06 +00003247/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003248const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003249 SCEV::NoWrapFlags Flags) {
Andrew Tricka34f1b12011-03-15 01:16:14 +00003250 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3251
Dan Gohman46f00a22010-07-20 16:53:00 +00003252 // Fast path: X - X --> 0.
3253 if (LHS == RHS)
3254 return getConstant(LHS->getType(), 0);
3255
Sanjoy Dascb473662015-01-22 00:48:47 +00003256 // X - Y --> X + -Y.
3257 // X -(nsw || nuw) Y --> X + -Y.
3258 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003259}
3260
3261/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3262/// input value to the specified type. If the type must be extended, it is zero
3263/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003264const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003265ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3266 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003267 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3268 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003269 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003270 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003271 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003272 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003273 return getTruncateExpr(V, Ty);
3274 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003275}
3276
3277/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3278/// input value to the specified type. If the type must be extended, it is sign
3279/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003280const SCEV *
3281ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003282 Type *Ty) {
3283 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003284 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3285 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003286 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003287 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003288 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003289 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003290 return getTruncateExpr(V, Ty);
3291 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003292}
3293
Dan Gohmane712a2f2009-05-13 03:46:30 +00003294/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3295/// input value to the specified type. If the type must be extended, it is zero
3296/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003297const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003298ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3299 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003300 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3301 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003302 "Cannot noop or zero extend with non-integer arguments!");
3303 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3304 "getNoopOrZeroExtend cannot truncate!");
3305 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3306 return V; // No conversion
3307 return getZeroExtendExpr(V, Ty);
3308}
3309
3310/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3311/// input value to the specified type. If the type must be extended, it is sign
3312/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003313const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003314ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3315 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003316 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3317 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003318 "Cannot noop or sign extend with non-integer arguments!");
3319 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3320 "getNoopOrSignExtend cannot truncate!");
3321 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3322 return V; // No conversion
3323 return getSignExtendExpr(V, Ty);
3324}
3325
Dan Gohman8db2edc2009-06-13 15:56:47 +00003326/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3327/// the input value to the specified type. If the type must be extended,
3328/// it is extended with unspecified bits. The conversion must not be
3329/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003330const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003331ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3332 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003333 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3334 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003335 "Cannot noop or any extend with non-integer arguments!");
3336 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3337 "getNoopOrAnyExtend cannot truncate!");
3338 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3339 return V; // No conversion
3340 return getAnyExtendExpr(V, Ty);
3341}
3342
Dan Gohmane712a2f2009-05-13 03:46:30 +00003343/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3344/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003345const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003346ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3347 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003348 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3349 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003350 "Cannot truncate or noop with non-integer arguments!");
3351 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3352 "getTruncateOrNoop cannot extend!");
3353 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3354 return V; // No conversion
3355 return getTruncateExpr(V, Ty);
3356}
3357
Dan Gohman96212b62009-06-22 00:31:57 +00003358/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3359/// the types using zero-extension, and then perform a umax operation
3360/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003361const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3362 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003363 const SCEV *PromotedLHS = LHS;
3364 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003365
3366 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3367 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3368 else
3369 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3370
3371 return getUMaxExpr(PromotedLHS, PromotedRHS);
3372}
3373
Dan Gohman2bc22302009-06-22 15:03:27 +00003374/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3375/// the types using zero-extension, and then perform a umin operation
3376/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003377const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3378 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003379 const SCEV *PromotedLHS = LHS;
3380 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003381
3382 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3383 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3384 else
3385 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3386
3387 return getUMinExpr(PromotedLHS, PromotedRHS);
3388}
3389
Andrew Trick87716c92011-03-17 23:51:11 +00003390/// getPointerBase - Transitively follow the chain of pointer-type operands
3391/// until reaching a SCEV that does not have a single pointer operand. This
3392/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3393/// but corner cases do exist.
3394const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3395 // A pointer operand may evaluate to a nonpointer expression, such as null.
3396 if (!V->getType()->isPointerTy())
3397 return V;
3398
3399 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3400 return getPointerBase(Cast->getOperand());
3401 }
3402 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003403 const SCEV *PtrOp = nullptr;
Andrew Trick87716c92011-03-17 23:51:11 +00003404 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3405 I != E; ++I) {
3406 if ((*I)->getType()->isPointerTy()) {
3407 // Cannot find the base of an expression with multiple pointer operands.
3408 if (PtrOp)
3409 return V;
3410 PtrOp = *I;
3411 }
3412 }
3413 if (!PtrOp)
3414 return V;
3415 return getPointerBase(PtrOp);
3416 }
3417 return V;
3418}
3419
Dan Gohman0b89dff2009-07-25 01:13:03 +00003420/// PushDefUseChildren - Push users of the given Instruction
3421/// onto the given Worklist.
3422static void
3423PushDefUseChildren(Instruction *I,
3424 SmallVectorImpl<Instruction *> &Worklist) {
3425 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003426 for (User *U : I->users())
3427 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003428}
3429
3430/// ForgetSymbolicValue - This looks up computed SCEV values for all
3431/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003432/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003433/// resolution.
Dan Gohmance973df2009-06-24 04:48:43 +00003434void
Dan Gohmana9c205c2010-02-25 06:57:05 +00003435ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003436 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003437 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003438
Dan Gohman0b89dff2009-07-25 01:13:03 +00003439 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003440 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003441 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003442 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003443 if (!Visited.insert(I).second)
3444 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003445
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003446 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003447 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003448 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003449 const SCEV *Old = It->second;
3450
Dan Gohman0b89dff2009-07-25 01:13:03 +00003451 // Short-circuit the def-use traversal if the symbolic name
3452 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003453 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003454 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003455
Dan Gohman0b89dff2009-07-25 01:13:03 +00003456 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003457 // structure, it's a PHI that's in the progress of being computed
3458 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3459 // additional loop trip count information isn't going to change anything.
3460 // In the second case, createNodeForPHI will perform the necessary
3461 // updates on its own when it gets to that point. In the third, we do
3462 // want to forget the SCEVUnknown.
3463 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003464 !isa<SCEVUnknown>(Old) ||
3465 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003466 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003467 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003468 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003469 }
3470
3471 PushDefUseChildren(I, Worklist);
3472 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003473}
Chris Lattnerd934c702004-04-02 20:23:17 +00003474
3475/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3476/// a loop header, making it a potential recurrence, or it doesn't.
3477///
Dan Gohmanaf752342009-07-07 17:06:11 +00003478const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003479 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3480 if (L->getHeader() == PN->getParent()) {
3481 // The loop may have multiple entrances or multiple exits; we can analyze
3482 // this phi as an addrec if it has a unique entry value and a unique
3483 // backedge value.
Craig Topper9f008862014-04-15 04:59:12 +00003484 Value *BEValueV = nullptr, *StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003485 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3486 Value *V = PN->getIncomingValue(i);
3487 if (L->contains(PN->getIncomingBlock(i))) {
3488 if (!BEValueV) {
3489 BEValueV = V;
3490 } else if (BEValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003491 BEValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003492 break;
3493 }
3494 } else if (!StartValueV) {
3495 StartValueV = V;
3496 } else if (StartValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003497 StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003498 break;
3499 }
3500 }
3501 if (BEValueV && StartValueV) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003502 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanaf752342009-07-07 17:06:11 +00003503 const SCEV *SymbolicName = getUnknown(PN);
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003504 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
Chris Lattnerd934c702004-04-02 20:23:17 +00003505 "PHI node already processed?");
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003506 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattnerd934c702004-04-02 20:23:17 +00003507
3508 // Using this symbolic name for the PHI, analyze the value coming around
3509 // the back-edge.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003510 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattnerd934c702004-04-02 20:23:17 +00003511
3512 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3513 // has a special value for the first iteration of the loop.
3514
3515 // If the value coming around the backedge is an add with the symbolic
3516 // value we just inserted, then we found a simple induction variable!
Dan Gohmana30370b2009-05-04 22:02:23 +00003517 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003518 // If there is a single occurrence of the symbolic value, replace it
3519 // with a recurrence.
3520 unsigned FoundIndex = Add->getNumOperands();
3521 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3522 if (Add->getOperand(i) == SymbolicName)
3523 if (FoundIndex == e) {
3524 FoundIndex = i;
3525 break;
3526 }
3527
3528 if (FoundIndex != Add->getNumOperands()) {
3529 // Create an add with everything but the specified operand.
Dan Gohmanaf752342009-07-07 17:06:11 +00003530 SmallVector<const SCEV *, 8> Ops;
Chris Lattnerd934c702004-04-02 20:23:17 +00003531 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3532 if (i != FoundIndex)
3533 Ops.push_back(Add->getOperand(i));
Dan Gohmanaf752342009-07-07 17:06:11 +00003534 const SCEV *Accum = getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00003535
3536 // This is not a valid addrec if the step amount is varying each
3537 // loop iteration, but is not itself an addrec in this loop.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003538 if (isLoopInvariant(Accum, L) ||
Chris Lattnerd934c702004-04-02 20:23:17 +00003539 (isa<SCEVAddRecExpr>(Accum) &&
3540 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003541 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003542
3543 // If the increment doesn't overflow, then neither the addrec nor
3544 // the post-increment will overflow.
3545 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3546 if (OBO->hasNoUnsignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003547 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003548 if (OBO->hasNoSignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003549 Flags = setFlags(Flags, SCEV::FlagNSW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003550 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003551 // If the increment is an inbounds GEP, then we know the address
3552 // space cannot be wrapped around. We cannot make any guarantee
3553 // about signed or unsigned overflow because pointers are
3554 // unsigned but we may have a negative index from the base
Benjamin Kramer6094f302013-10-28 07:30:06 +00003555 // pointer. We can guarantee that no unsigned wrap occurs if the
3556 // indices form a positive value.
3557 if (GEP->isInBounds()) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003558 Flags = setFlags(Flags, SCEV::FlagNW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003559
3560 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3561 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3562 Flags = setFlags(Flags, SCEV::FlagNUW);
3563 }
Sanjoy Dascb473662015-01-22 00:48:47 +00003564
3565 // We cannot transfer nuw and nsw flags from subtraction
3566 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3567 // for instance.
Dan Gohman51ad99d2010-01-21 02:09:26 +00003568 }
3569
Dan Gohman6635bb22010-04-12 07:49:36 +00003570 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick8b55b732011-03-14 16:50:06 +00003571 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohman62ef6a72009-07-25 01:22:26 +00003572
Dan Gohman51ad99d2010-01-21 02:09:26 +00003573 // Since the no-wrap flags are on the increment, they apply to the
3574 // post-incremented value as well.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003575 if (isLoopInvariant(Accum, L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003576 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick8b55b732011-03-14 16:50:06 +00003577 Accum, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00003578
3579 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003580 // to be symbolic. We now need to go back and purge all of the
3581 // entries for the scalars that use the symbolic expression.
3582 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003583 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00003584 return PHISCEV;
3585 }
3586 }
Dan Gohmana30370b2009-05-04 22:02:23 +00003587 } else if (const SCEVAddRecExpr *AddRec =
3588 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003589 // Otherwise, this could be a loop like this:
3590 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3591 // In this case, j = {1,+,1} and BEValue is j.
3592 // Because the other in-value of i (0) fits the evolution of BEValue
3593 // i really is an addrec evolution.
3594 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003595 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003596
3597 // If StartVal = j.start - j.stride, we can use StartVal as the
3598 // initial step of the addrec evolution.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003599 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman068b7932010-04-11 23:44:58 +00003600 AddRec->getOperand(1))) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003601 // FIXME: For constant StartVal, we should be able to infer
3602 // no-wrap flags.
Dan Gohmanaf752342009-07-07 17:06:11 +00003603 const SCEV *PHISCEV =
Andrew Trick8b55b732011-03-14 16:50:06 +00003604 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3605 SCEV::FlagAnyWrap);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003606
3607 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003608 // to be symbolic. We now need to go back and purge all of the
3609 // entries for the scalars that use the symbolic expression.
3610 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003611 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003612 return PHISCEV;
3613 }
3614 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003615 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003616 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003617 }
Misha Brukman01808ca2005-04-21 21:13:18 +00003618
Dan Gohmana9c205c2010-02-25 06:57:05 +00003619 // If the PHI has a single incoming value, follow that value, unless the
3620 // PHI's incoming blocks are in a different loop, in which case doing so
3621 // risks breaking LCSSA form. Instcombine would normally zap these, but
3622 // it doesn't have DominatorTree information, so it may miss cases.
Chandler Carruth66b31302015-01-04 12:03:27 +00003623 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AC))
Duncan Sandsaef146b2010-11-18 19:59:41 +00003624 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00003625 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00003626
Chris Lattnerd934c702004-04-02 20:23:17 +00003627 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003628 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00003629}
3630
Dan Gohmanee750d12009-05-08 20:26:55 +00003631/// createNodeForGEP - Expand GEP instructions into add and multiply
3632/// operations. This allows them to be analyzed by regular SCEV code.
3633///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00003634const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Chris Lattner229907c2011-07-18 04:54:35 +00003635 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohman2173bd32009-05-08 20:36:47 +00003636 Value *Base = GEP->getOperand(0);
Dan Gohman30f24fe2009-05-09 00:14:52 +00003637 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenault404c60a2013-10-21 19:43:56 +00003638 if (!Base->getType()->getPointerElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00003639 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00003640
3641 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3642 // Add expression, because the Instruction may be guarded by control flow
3643 // and the no-overflow bits may not be valid for the expression in any
3644 // context.
3645 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3646
Dan Gohman1d2ded72010-05-03 22:09:21 +00003647 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohman2173bd32009-05-08 20:36:47 +00003648 gep_type_iterator GTI = gep_type_begin(GEP);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003649 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
Dan Gohman2173bd32009-05-08 20:36:47 +00003650 E = GEP->op_end();
Dan Gohmanee750d12009-05-08 20:26:55 +00003651 I != E; ++I) {
3652 Value *Index = *I;
3653 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +00003654 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Dan Gohmanee750d12009-05-08 20:26:55 +00003655 // For a struct, add the member offset.
Dan Gohmanee750d12009-05-08 20:26:55 +00003656 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003657 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
Dan Gohman16206132010-06-30 07:16:37 +00003658
Dan Gohman16206132010-06-30 07:16:37 +00003659 // Add the field offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003660 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003661 } else {
3662 // For an array, add the element offset, explicitly scaled.
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003663 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
Dan Gohman16206132010-06-30 07:16:37 +00003664 const SCEV *IndexS = getSCEV(Index);
Dan Gohman8b0a4192010-03-01 17:49:51 +00003665 // Getelementptr indices are signed.
Dan Gohman16206132010-06-30 07:16:37 +00003666 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3667
Dan Gohman16206132010-06-30 07:16:37 +00003668 // Multiply the index by the element size to compute the element offset.
Matt Arsenault4c265902013-09-27 22:38:23 +00003669 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
Dan Gohman16206132010-06-30 07:16:37 +00003670
3671 // Add the element offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003672 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003673 }
3674 }
Dan Gohman16206132010-06-30 07:16:37 +00003675
3676 // Get the SCEV for the GEP base.
3677 const SCEV *BaseS = getSCEV(Base);
3678
Dan Gohman16206132010-06-30 07:16:37 +00003679 // Add the total offset from all the GEP indices to the base.
Matt Arsenault4c265902013-09-27 22:38:23 +00003680 return getAddExpr(BaseS, TotalOffset, Wrap);
Dan Gohmanee750d12009-05-08 20:26:55 +00003681}
3682
Nick Lewycky3783b462007-11-22 07:59:40 +00003683/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3684/// guaranteed to end in (at every loop iteration). It is, at the same time,
3685/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3686/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003687uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00003688ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003689 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner69ec1ec2007-11-23 22:36:49 +00003690 return C->getValue()->getValue().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00003691
Dan Gohmana30370b2009-05-04 22:02:23 +00003692 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00003693 return std::min(GetMinTrailingZeros(T->getOperand()),
3694 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00003695
Dan Gohmana30370b2009-05-04 22:02:23 +00003696 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003697 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3698 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3699 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003700 }
3701
Dan Gohmana30370b2009-05-04 22:02:23 +00003702 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003703 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3704 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3705 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003706 }
3707
Dan Gohmana30370b2009-05-04 22:02:23 +00003708 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003709 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003710 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003711 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003712 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003713 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003714 }
3715
Dan Gohmana30370b2009-05-04 22:02:23 +00003716 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003717 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003718 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3719 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00003720 for (unsigned i = 1, e = M->getNumOperands();
3721 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003722 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00003723 BitWidth);
3724 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003725 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003726
Dan Gohmana30370b2009-05-04 22:02:23 +00003727 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003728 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003729 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003730 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003731 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003732 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003733 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003734
Dan Gohmana30370b2009-05-04 22:02:23 +00003735 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003736 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003737 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003738 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003739 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003740 return MinOpRes;
3741 }
3742
Dan Gohmana30370b2009-05-04 22:02:23 +00003743 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003744 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003745 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003746 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003747 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003748 return MinOpRes;
3749 }
3750
Dan Gohmanc702fc02009-06-19 23:29:04 +00003751 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3752 // For a SCEVUnknown, ask ValueTracking.
3753 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00003754 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003755 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AC, nullptr, DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003756 return Zeros.countTrailingOnes();
3757 }
3758
3759 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00003760 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00003761}
Chris Lattnerd934c702004-04-02 20:23:17 +00003762
Sanjoy Das1f05c512014-10-10 21:22:34 +00003763/// GetRangeFromMetadata - Helper method to assign a range to V from
3764/// metadata present in the IR.
3765static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3766 if (Instruction *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003767 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003768 ConstantRange TotalRange(
3769 cast<IntegerType>(I->getType())->getBitWidth(), false);
3770
3771 unsigned NumRanges = MD->getNumOperands() / 2;
3772 assert(NumRanges >= 1);
3773
3774 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003775 ConstantInt *Lower =
3776 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0));
3777 ConstantInt *Upper =
3778 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1));
Sanjoy Das1f05c512014-10-10 21:22:34 +00003779 ConstantRange Range(Lower->getValue(), Upper->getValue());
3780 TotalRange = TotalRange.unionWith(Range);
3781 }
3782
3783 return TotalRange;
3784 }
3785 }
3786
3787 return None;
3788}
3789
Dan Gohmane65c9172009-07-13 21:35:55 +00003790/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3791///
3792ConstantRange
3793ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman761065e2010-11-17 02:44:44 +00003794 // See if we've computed this range already.
3795 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3796 if (I != UnsignedRanges.end())
3797 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003798
3799 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003800 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003801
Dan Gohman85be4332010-01-26 19:19:05 +00003802 unsigned BitWidth = getTypeSizeInBits(S->getType());
3803 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3804
3805 // If the value has known zeros, the maximum unsigned value will have those
3806 // known zeros as well.
3807 uint32_t TZ = GetMinTrailingZeros(S);
3808 if (TZ != 0)
3809 ConservativeResult =
3810 ConstantRange(APInt::getMinValue(BitWidth),
3811 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3812
Dan Gohmane65c9172009-07-13 21:35:55 +00003813 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3814 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3815 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3816 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003817 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003818 }
3819
3820 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3821 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3822 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3823 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003824 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003825 }
3826
3827 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3828 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3829 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3830 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003831 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003832 }
3833
3834 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3835 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3836 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3837 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003838 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003839 }
3840
3841 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3842 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3843 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003844 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003845 }
3846
3847 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3848 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003849 return setUnsignedRange(ZExt,
3850 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003851 }
3852
3853 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3854 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003855 return setUnsignedRange(SExt,
3856 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003857 }
3858
3859 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3860 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003861 return setUnsignedRange(Trunc,
3862 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003863 }
3864
Dan Gohmane65c9172009-07-13 21:35:55 +00003865 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003866 // If there's no unsigned wrap, the value will never be less than its
3867 // initial value.
Andrew Trick8b55b732011-03-14 16:50:06 +00003868 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003869 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00003870 if (!C->getValue()->isZero())
Dan Gohmanae4a4142010-04-11 22:12:18 +00003871 ConservativeResult =
Dan Gohman9396b422010-06-30 06:58:35 +00003872 ConservativeResult.intersectWith(
3873 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003874
3875 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00003876 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003877 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00003878 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00003879 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3880 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00003881 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3882
3883 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00003884 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00003885
3886 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003887 ConstantRange StepRange = getSignedRange(Step);
3888 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3889 ConstantRange EndRange =
3890 StartRange.add(MaxBECountRange.multiply(StepRange));
3891
3892 // Check for overflow. This must be done with ConstantRange arithmetic
3893 // because we could be called from within the ScalarEvolution overflow
3894 // checking code.
3895 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3896 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3897 ConstantRange ExtMaxBECountRange =
3898 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3899 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3900 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3901 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00003902 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003903
Dan Gohmane65c9172009-07-13 21:35:55 +00003904 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3905 EndRange.getUnsignedMin());
3906 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3907 EndRange.getUnsignedMax());
3908 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmaned756312010-11-17 20:23:08 +00003909 return setUnsignedRange(AddRec, ConservativeResult);
3910 return setUnsignedRange(AddRec,
3911 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003912 }
3913 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003914
Dan Gohmaned756312010-11-17 20:23:08 +00003915 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003916 }
3917
3918 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003919 // Check if the IR explicitly contains !range metadata.
3920 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3921 if (MDRange.hasValue())
3922 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3923
Dan Gohmanc702fc02009-06-19 23:29:04 +00003924 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003925 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003926 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AC, nullptr, DT);
Dan Gohman1a7ab942009-07-20 22:34:18 +00003927 if (Ones == ~Zeros + 1)
Dan Gohmaned756312010-11-17 20:23:08 +00003928 return setUnsignedRange(U, ConservativeResult);
3929 return setUnsignedRange(U,
3930 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003931 }
3932
Dan Gohmaned756312010-11-17 20:23:08 +00003933 return setUnsignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003934}
3935
Dan Gohmane65c9172009-07-13 21:35:55 +00003936/// getSignedRange - Determine the signed range for a particular SCEV.
3937///
3938ConstantRange
3939ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman3ac8cd62011-01-24 17:54:18 +00003940 // See if we've computed this range already.
Dan Gohman761065e2010-11-17 02:44:44 +00003941 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3942 if (I != SignedRanges.end())
3943 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003944
Dan Gohmane65c9172009-07-13 21:35:55 +00003945 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003946 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmane65c9172009-07-13 21:35:55 +00003947
Dan Gohman51aaf022010-01-26 04:40:18 +00003948 unsigned BitWidth = getTypeSizeInBits(S->getType());
3949 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3950
3951 // If the value has known zeros, the maximum signed value will have those
3952 // known zeros as well.
3953 uint32_t TZ = GetMinTrailingZeros(S);
3954 if (TZ != 0)
3955 ConservativeResult =
3956 ConstantRange(APInt::getSignedMinValue(BitWidth),
3957 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3958
Dan Gohmane65c9172009-07-13 21:35:55 +00003959 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3960 ConstantRange X = getSignedRange(Add->getOperand(0));
3961 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3962 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003963 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003964 }
3965
Dan Gohmane65c9172009-07-13 21:35:55 +00003966 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3967 ConstantRange X = getSignedRange(Mul->getOperand(0));
3968 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3969 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003970 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003971 }
3972
Dan Gohmane65c9172009-07-13 21:35:55 +00003973 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3974 ConstantRange X = getSignedRange(SMax->getOperand(0));
3975 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3976 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003977 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003978 }
Dan Gohmand261d272009-06-24 01:05:09 +00003979
Dan Gohmane65c9172009-07-13 21:35:55 +00003980 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3981 ConstantRange X = getSignedRange(UMax->getOperand(0));
3982 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3983 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003984 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003985 }
Dan Gohmand261d272009-06-24 01:05:09 +00003986
Dan Gohmane65c9172009-07-13 21:35:55 +00003987 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3988 ConstantRange X = getSignedRange(UDiv->getLHS());
3989 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003990 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003991 }
Dan Gohmand261d272009-06-24 01:05:09 +00003992
Dan Gohmane65c9172009-07-13 21:35:55 +00003993 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3994 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003995 return setSignedRange(ZExt,
3996 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003997 }
3998
3999 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4000 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00004001 return setSignedRange(SExt,
4002 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004003 }
4004
4005 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4006 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00004007 return setSignedRange(Trunc,
4008 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004009 }
4010
Dan Gohmane65c9172009-07-13 21:35:55 +00004011 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004012 // If there's no signed wrap, and all the operands have the same sign or
4013 // zero, the value won't ever change sign.
Andrew Trick8b55b732011-03-14 16:50:06 +00004014 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004015 bool AllNonNeg = true;
4016 bool AllNonPos = true;
4017 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4018 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4019 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4020 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004021 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004022 ConservativeResult = ConservativeResult.intersectWith(
4023 ConstantRange(APInt(BitWidth, 0),
4024 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004025 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004026 ConservativeResult = ConservativeResult.intersectWith(
4027 ConstantRange(APInt::getSignedMinValue(BitWidth),
4028 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004029 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004030
4031 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004032 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00004033 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00004034 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004035 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4036 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004037 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
4038
4039 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00004040 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00004041
4042 ConstantRange StartRange = getSignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00004043 ConstantRange StepRange = getSignedRange(Step);
4044 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4045 ConstantRange EndRange =
4046 StartRange.add(MaxBECountRange.multiply(StepRange));
4047
4048 // Check for overflow. This must be done with ConstantRange arithmetic
4049 // because we could be called from within the ScalarEvolution overflow
4050 // checking code.
4051 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
4052 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
4053 ConstantRange ExtMaxBECountRange =
4054 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
4055 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
4056 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
4057 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00004058 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00004059
Dan Gohmane65c9172009-07-13 21:35:55 +00004060 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
4061 EndRange.getSignedMin());
4062 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
4063 EndRange.getSignedMax());
4064 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmaned756312010-11-17 20:23:08 +00004065 return setSignedRange(AddRec, ConservativeResult);
4066 return setSignedRange(AddRec,
4067 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmand261d272009-06-24 01:05:09 +00004068 }
Dan Gohmand261d272009-06-24 01:05:09 +00004069 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004070
Dan Gohmaned756312010-11-17 20:23:08 +00004071 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004072 }
4073
Dan Gohmanc702fc02009-06-19 23:29:04 +00004074 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004075 // Check if the IR explicitly contains !range metadata.
4076 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4077 if (MDRange.hasValue())
4078 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4079
Dan Gohmanc702fc02009-06-19 23:29:04 +00004080 // For a SCEVUnknown, ask ValueTracking.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00004081 if (!U->getValue()->getType()->isIntegerTy() && !DL)
Dan Gohmaned756312010-11-17 20:23:08 +00004082 return setSignedRange(U, ConservativeResult);
Chandler Carruth66b31302015-01-04 12:03:27 +00004083 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AC, nullptr, DT);
Hal Finkelff666bd2013-07-09 18:16:16 +00004084 if (NS <= 1)
Dan Gohmaned756312010-11-17 20:23:08 +00004085 return setSignedRange(U, ConservativeResult);
4086 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohmane65c9172009-07-13 21:35:55 +00004087 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohmaned756312010-11-17 20:23:08 +00004088 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004089 }
4090
Dan Gohmaned756312010-11-17 20:23:08 +00004091 return setSignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004092}
4093
Chris Lattnerd934c702004-04-02 20:23:17 +00004094/// createSCEV - We know that there is no SCEV for the specified value.
4095/// Analyze the expression.
4096///
Dan Gohmanaf752342009-07-07 17:06:11 +00004097const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004098 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004099 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004100
Dan Gohman05e89732008-06-22 19:56:46 +00004101 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004102 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004103 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004104
4105 // Don't attempt to analyze instructions in blocks that aren't
4106 // reachable. Such instructions don't matter, and they aren't required
4107 // to obey basic rules for definitions dominating uses which this
4108 // analysis depends on.
4109 if (!DT->isReachableFromEntry(I->getParent()))
4110 return getUnknown(V);
4111 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004112 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004113 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4114 return getConstant(CI);
4115 else if (isa<ConstantPointerNull>(V))
Dan Gohman1d2ded72010-05-03 22:09:21 +00004116 return getConstant(V->getType(), 0);
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004117 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4118 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004119 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004120 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004121
Dan Gohman80ca01c2009-07-17 20:47:02 +00004122 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004123 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004124 case Instruction::Add: {
4125 // The simple thing to do would be to just call getSCEV on both operands
4126 // and call getAddExpr with the result. However if we're looking at a
4127 // bunch of things all added together, this can be quite inefficient,
4128 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4129 // Instead, gather up all the operands and make a single getAddExpr call.
4130 // LLVM IR canonical form means we need only traverse the left operands.
Andrew Trickd25089f2011-11-29 02:16:38 +00004131 //
4132 // Don't apply this instruction's NSW or NUW flags to the new
4133 // expression. The instruction may be guarded by control flow that the
4134 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4135 // mapped to the same SCEV expression, and it would be incorrect to transfer
4136 // NSW/NUW semantics to those operations.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004137 SmallVector<const SCEV *, 4> AddOps;
4138 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman47308d52010-08-31 22:53:17 +00004139 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4140 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4141 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4142 break;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004143 U = cast<Operator>(Op);
Dan Gohman47308d52010-08-31 22:53:17 +00004144 const SCEV *Op1 = getSCEV(U->getOperand(1));
4145 if (Opcode == Instruction::Sub)
4146 AddOps.push_back(getNegativeSCEV(Op1));
4147 else
4148 AddOps.push_back(Op1);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004149 }
4150 AddOps.push_back(getSCEV(U->getOperand(0)));
Andrew Trickd25089f2011-11-29 02:16:38 +00004151 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004152 }
4153 case Instruction::Mul: {
Andrew Trickd25089f2011-11-29 02:16:38 +00004154 // Don't transfer NSW/NUW for the same reason as AddExpr.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004155 SmallVector<const SCEV *, 4> MulOps;
4156 MulOps.push_back(getSCEV(U->getOperand(1)));
4157 for (Value *Op = U->getOperand(0);
Andrew Trick2a3b7162011-03-09 17:23:39 +00004158 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004159 Op = U->getOperand(0)) {
4160 U = cast<Operator>(Op);
4161 MulOps.push_back(getSCEV(U->getOperand(1)));
4162 }
4163 MulOps.push_back(getSCEV(U->getOperand(0)));
4164 return getMulExpr(MulOps);
4165 }
Dan Gohman05e89732008-06-22 19:56:46 +00004166 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004167 return getUDivExpr(getSCEV(U->getOperand(0)),
4168 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004169 case Instruction::Sub:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004170 return getMinusSCEV(getSCEV(U->getOperand(0)),
4171 getSCEV(U->getOperand(1)));
Dan Gohman0ec05372009-04-21 02:26:00 +00004172 case Instruction::And:
4173 // For an expression like x&255 that merely masks off the high bits,
4174 // use zext(trunc(x)) as the SCEV expression.
4175 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004176 if (CI->isNullValue())
4177 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004178 if (CI->isAllOnesValue())
4179 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004180 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004181
4182 // Instcombine's ShrinkDemandedConstant may strip bits out of
4183 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004184 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004185 // knew about to reconstruct a low-bits mask value.
4186 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004187 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004188 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004189 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00004190 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, 0, AC,
4191 nullptr, DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004192
Nick Lewycky31eaca52014-01-27 10:04:03 +00004193 APInt EffectiveMask =
4194 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4195 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4196 const SCEV *MulCount = getConstant(
4197 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4198 return getMulExpr(
4199 getZeroExtendExpr(
4200 getTruncateExpr(
4201 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4202 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4203 U->getType()),
4204 MulCount);
4205 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004206 }
4207 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004208
Dan Gohman05e89732008-06-22 19:56:46 +00004209 case Instruction::Or:
4210 // If the RHS of the Or is a constant, we may have something like:
4211 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4212 // optimizations will transparently handle this case.
4213 //
4214 // In order for this transformation to be safe, the LHS must be of the
4215 // form X*(2^n) and the Or constant must be less than 2^n.
4216 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004217 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004218 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004219 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004220 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4221 // Build a plain add SCEV.
4222 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4223 // If the LHS of the add was an addrec and it has no-wrap flags,
4224 // transfer the no-wrap flags, since an or won't introduce a wrap.
4225 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4226 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004227 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4228 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004229 }
4230 return S;
4231 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004232 }
Dan Gohman05e89732008-06-22 19:56:46 +00004233 break;
4234 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004235 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004236 // If the RHS of the xor is a signbit, then this is just an add.
4237 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004238 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004239 return getAddExpr(getSCEV(U->getOperand(0)),
4240 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004241
4242 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004243 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004244 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004245
4246 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4247 // This is a variant of the check for xor with -1, and it handles
4248 // the case where instcombine has trimmed non-demanded bits out
4249 // of an xor with -1.
4250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4251 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4252 if (BO->getOpcode() == Instruction::And &&
4253 LCI->getValue() == CI->getValue())
4254 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004255 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004256 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004257 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004258 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004259 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4260
Dan Gohman8b0a4192010-03-01 17:49:51 +00004261 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004262 // mask off the high bits. Complement the operand and
4263 // re-apply the zext.
4264 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4265 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4266
4267 // If C is a single bit, it may be in the sign-bit position
4268 // before the zero-extend. In this case, represent the xor
4269 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004270 APInt Trunc = CI->getValue().trunc(Z0TySize);
4271 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004272 Trunc.isSignBit())
4273 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4274 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004275 }
Dan Gohman05e89732008-06-22 19:56:46 +00004276 }
4277 break;
4278
4279 case Instruction::Shl:
4280 // Turn shift left of a constant amount into a multiply.
4281 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004282 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004283
4284 // If the shift count is not less than the bitwidth, the result of
4285 // the shift is undefined. Don't try to analyze it, because the
4286 // resolution chosen here may differ from the resolution chosen in
4287 // other parts of the compiler.
4288 if (SA->getValue().uge(BitWidth))
4289 break;
4290
Owen Andersonedb4a702009-07-24 23:12:02 +00004291 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004292 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004293 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman05e89732008-06-22 19:56:46 +00004294 }
4295 break;
4296
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004297 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004298 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004299 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004300 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004301
4302 // If the shift count is not less than the bitwidth, the result of
4303 // the shift is undefined. Don't try to analyze it, because the
4304 // resolution chosen here may differ from the resolution chosen in
4305 // other parts of the compiler.
4306 if (SA->getValue().uge(BitWidth))
4307 break;
4308
Owen Andersonedb4a702009-07-24 23:12:02 +00004309 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004310 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004311 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004312 }
4313 break;
4314
Dan Gohman0ec05372009-04-21 02:26:00 +00004315 case Instruction::AShr:
4316 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4317 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004318 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004319 if (L->getOpcode() == Instruction::Shl &&
4320 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004321 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4322
4323 // If the shift count is not less than the bitwidth, the result of
4324 // the shift is undefined. Don't try to analyze it, because the
4325 // resolution chosen here may differ from the resolution chosen in
4326 // other parts of the compiler.
4327 if (CI->getValue().uge(BitWidth))
4328 break;
4329
Dan Gohmandf199482009-04-25 17:05:40 +00004330 uint64_t Amt = BitWidth - CI->getZExtValue();
4331 if (Amt == BitWidth)
4332 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004333 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004334 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004335 IntegerType::get(getContext(),
4336 Amt)),
4337 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004338 }
4339 break;
4340
Dan Gohman05e89732008-06-22 19:56:46 +00004341 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004342 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004343
4344 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004345 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004346
4347 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004348 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004349
4350 case Instruction::BitCast:
4351 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004352 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004353 return getSCEV(U->getOperand(0));
4354 break;
4355
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004356 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4357 // lead to pointer expressions which cannot safely be expanded to GEPs,
4358 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4359 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004360
Dan Gohmanee750d12009-05-08 20:26:55 +00004361 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004362 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004363
Dan Gohman05e89732008-06-22 19:56:46 +00004364 case Instruction::PHI:
4365 return createNodeForPHI(cast<PHINode>(U));
4366
4367 case Instruction::Select:
4368 // This could be a smax or umax that was lowered earlier.
4369 // Try to recover it.
4370 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4371 Value *LHS = ICI->getOperand(0);
4372 Value *RHS = ICI->getOperand(1);
4373 switch (ICI->getPredicate()) {
4374 case ICmpInst::ICMP_SLT:
4375 case ICmpInst::ICMP_SLE:
4376 std::swap(LHS, RHS);
4377 // fall through
4378 case ICmpInst::ICMP_SGT:
4379 case ICmpInst::ICMP_SGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004380 // a >s b ? a+x : b+x -> smax(a, b)+x
4381 // a >s b ? b+x : a+x -> smin(a, b)+x
Johannes Doerfert2683e562015-02-09 12:34:23 +00004382 if (getTypeSizeInBits(LHS->getType()) <=
4383 getTypeSizeInBits(U->getType())) {
4384 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), U->getType());
4385 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), U->getType());
Dan Gohmanf33bac32010-04-24 03:09:42 +00004386 const SCEV *LA = getSCEV(U->getOperand(1));
4387 const SCEV *RA = getSCEV(U->getOperand(2));
4388 const SCEV *LDiff = getMinusSCEV(LA, LS);
4389 const SCEV *RDiff = getMinusSCEV(RA, RS);
4390 if (LDiff == RDiff)
4391 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4392 LDiff = getMinusSCEV(LA, RS);
4393 RDiff = getMinusSCEV(RA, LS);
4394 if (LDiff == RDiff)
4395 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4396 }
Dan Gohman05e89732008-06-22 19:56:46 +00004397 break;
4398 case ICmpInst::ICMP_ULT:
4399 case ICmpInst::ICMP_ULE:
4400 std::swap(LHS, RHS);
4401 // fall through
4402 case ICmpInst::ICMP_UGT:
4403 case ICmpInst::ICMP_UGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004404 // a >u b ? a+x : b+x -> umax(a, b)+x
4405 // a >u b ? b+x : a+x -> umin(a, b)+x
Johannes Doerfert2683e562015-02-09 12:34:23 +00004406 if (getTypeSizeInBits(LHS->getType()) <=
4407 getTypeSizeInBits(U->getType())) {
4408 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
4409 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), U->getType());
Dan Gohmanf33bac32010-04-24 03:09:42 +00004410 const SCEV *LA = getSCEV(U->getOperand(1));
4411 const SCEV *RA = getSCEV(U->getOperand(2));
4412 const SCEV *LDiff = getMinusSCEV(LA, LS);
4413 const SCEV *RDiff = getMinusSCEV(RA, RS);
4414 if (LDiff == RDiff)
4415 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4416 LDiff = getMinusSCEV(LA, RS);
4417 RDiff = getMinusSCEV(RA, LS);
4418 if (LDiff == RDiff)
4419 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4420 }
Dan Gohman05e89732008-06-22 19:56:46 +00004421 break;
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004422 case ICmpInst::ICMP_NE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004423 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
Johannes Doerfert2683e562015-02-09 12:34:23 +00004424 if (getTypeSizeInBits(LHS->getType()) <=
4425 getTypeSizeInBits(U->getType()) &&
4426 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4427 const SCEV *One = getConstant(U->getType(), 1);
4428 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
Dan Gohmanf33bac32010-04-24 03:09:42 +00004429 const SCEV *LA = getSCEV(U->getOperand(1));
4430 const SCEV *RA = getSCEV(U->getOperand(2));
4431 const SCEV *LDiff = getMinusSCEV(LA, LS);
4432 const SCEV *RDiff = getMinusSCEV(RA, One);
4433 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004434 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004435 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004436 break;
4437 case ICmpInst::ICMP_EQ:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004438 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
Johannes Doerfert2683e562015-02-09 12:34:23 +00004439 if (getTypeSizeInBits(LHS->getType()) <=
4440 getTypeSizeInBits(U->getType()) &&
4441 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4442 const SCEV *One = getConstant(U->getType(), 1);
4443 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
Dan Gohmanf33bac32010-04-24 03:09:42 +00004444 const SCEV *LA = getSCEV(U->getOperand(1));
4445 const SCEV *RA = getSCEV(U->getOperand(2));
4446 const SCEV *LDiff = getMinusSCEV(LA, One);
4447 const SCEV *RDiff = getMinusSCEV(RA, LS);
4448 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004449 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004450 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004451 break;
Dan Gohman05e89732008-06-22 19:56:46 +00004452 default:
4453 break;
4454 }
4455 }
4456
4457 default: // We cannot analyze this expression.
4458 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004459 }
4460
Dan Gohmanc8e23622009-04-21 23:15:49 +00004461 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004462}
4463
4464
4465
4466//===----------------------------------------------------------------------===//
4467// Iteration Count Computation Code
4468//
4469
Chandler Carruth6666c272014-10-11 00:12:11 +00004470unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4471 if (BasicBlock *ExitingBB = L->getExitingBlock())
4472 return getSmallConstantTripCount(L, ExitingBB);
4473
4474 // No trip count information for multiple exits.
4475 return 0;
4476}
4477
Andrew Trick2b6860f2011-08-11 23:36:16 +00004478/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004479/// normal unsigned value. Returns 0 if the trip count is unknown or not
4480/// constant. Will also return 0 if the maximum trip count is very large (>=
4481/// 2^32).
4482///
4483/// This "trip count" assumes that control exits via ExitingBlock. More
4484/// precisely, it is the number of times that control may reach ExitingBlock
4485/// before taking the branch. For loops with multiple exits, it may not be the
4486/// number times that the loop header executes because the loop may exit
4487/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004488unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4489 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004490 assert(ExitingBlock && "Must pass a non-null exiting block!");
4491 assert(L->isLoopExiting(ExitingBlock) &&
4492 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00004493 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004494 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004495 if (!ExitCount)
4496 return 0;
4497
4498 ConstantInt *ExitConst = ExitCount->getValue();
4499
4500 // Guard against huge trip counts.
4501 if (ExitConst->getValue().getActiveBits() > 32)
4502 return 0;
4503
4504 // In case of integer overflow, this returns 0, which is correct.
4505 return ((unsigned)ExitConst->getZExtValue()) + 1;
4506}
4507
Chandler Carruth6666c272014-10-11 00:12:11 +00004508unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4509 if (BasicBlock *ExitingBB = L->getExitingBlock())
4510 return getSmallConstantTripMultiple(L, ExitingBB);
4511
4512 // No trip multiple information for multiple exits.
4513 return 0;
4514}
4515
Andrew Trick2b6860f2011-08-11 23:36:16 +00004516/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4517/// trip count of this loop as a normal unsigned value, if possible. This
4518/// means that the actual trip count is always a multiple of the returned
4519/// value (don't forget the trip count could very well be zero as well!).
4520///
4521/// Returns 1 if the trip count is unknown or not guaranteed to be the
4522/// multiple of a constant (which is also the case if the trip count is simply
4523/// constant, use getSmallConstantTripCount for that case), Will also return 1
4524/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004525///
4526/// As explained in the comments for getSmallConstantTripCount, this assumes
4527/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004528unsigned
4529ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4530 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004531 assert(ExitingBlock && "Must pass a non-null exiting block!");
4532 assert(L->isLoopExiting(ExitingBlock) &&
4533 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004534 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004535 if (ExitCount == getCouldNotCompute())
4536 return 1;
4537
4538 // Get the trip count from the BE count by adding 1.
4539 const SCEV *TCMul = getAddExpr(ExitCount,
4540 getConstant(ExitCount->getType(), 1));
4541 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4542 // to factor simple cases.
4543 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4544 TCMul = Mul->getOperand(0);
4545
4546 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4547 if (!MulC)
4548 return 1;
4549
4550 ConstantInt *Result = MulC->getValue();
4551
Hal Finkel30bd9342012-10-24 19:46:44 +00004552 // Guard against huge trip counts (this requires checking
4553 // for zero to handle the case where the trip count == -1 and the
4554 // addition wraps).
4555 if (!Result || Result->getValue().getActiveBits() > 32 ||
4556 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004557 return 1;
4558
4559 return (unsigned)Result->getZExtValue();
4560}
4561
Andrew Trick3ca3f982011-07-26 17:19:55 +00004562// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004563// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004564// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004565const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4566 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004567}
4568
Dan Gohman0bddac12009-02-24 18:55:53 +00004569/// getBackedgeTakenCount - If the specified loop has a predictable
4570/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4571/// object. The backedge-taken count is the number of times the loop header
4572/// will be branched to from within the loop. This is one less than the
4573/// trip count of the loop, since it doesn't count the first iteration,
4574/// when the header is branched to from outside the loop.
4575///
4576/// Note that it is not valid to call this method on a loop without a
4577/// loop-invariant backedge-taken count (see
4578/// hasLoopInvariantBackedgeTakenCount).
4579///
Dan Gohmanaf752342009-07-07 17:06:11 +00004580const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004581 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004582}
4583
4584/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4585/// return the least SCEV value that is known never to be less than the
4586/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00004587const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004588 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004589}
4590
Dan Gohmandc191042009-07-08 19:23:34 +00004591/// PushLoopPHIs - Push PHI nodes in the header of the given loop
4592/// onto the given Worklist.
4593static void
4594PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4595 BasicBlock *Header = L->getHeader();
4596
4597 // Push all Loop-header PHIs onto the Worklist stack.
4598 for (BasicBlock::iterator I = Header->begin();
4599 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4600 Worklist.push_back(PN);
4601}
4602
Dan Gohman2b8da352009-04-30 20:47:05 +00004603const ScalarEvolution::BackedgeTakenInfo &
4604ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004605 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00004606 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00004607 // update the value. The temporary CouldNotCompute value tells SCEV
4608 // code elsewhere that it shouldn't attempt to request a new
4609 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00004610 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick3ca3f982011-07-26 17:19:55 +00004611 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004612 if (!Pair.second)
4613 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00004614
Andrew Trick3ca3f982011-07-26 17:19:55 +00004615 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4616 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4617 // must be cleared in this scope.
4618 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4619
4620 if (Result.getExact(this) != getCouldNotCompute()) {
4621 assert(isLoopInvariant(Result.getExact(this), L) &&
4622 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00004623 "Computed backedge-taken count isn't loop invariant for loop!");
4624 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004625 }
4626 else if (Result.getMax(this) == getCouldNotCompute() &&
4627 isa<PHINode>(L->getHeader()->begin())) {
4628 // Only count loops that have phi nodes as not being computable.
4629 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00004630 }
Dan Gohman2b8da352009-04-30 20:47:05 +00004631
Chris Lattnera337f5e2011-01-09 02:16:18 +00004632 // Now that we know more about the trip count for this loop, forget any
4633 // existing SCEV values for PHI nodes in this loop since they are only
4634 // conservative estimates made without the benefit of trip count
4635 // information. This is similar to the code in forgetLoop, except that
4636 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004637 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00004638 SmallVector<Instruction *, 16> Worklist;
4639 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004640
Chris Lattnera337f5e2011-01-09 02:16:18 +00004641 SmallPtrSet<Instruction *, 8> Visited;
4642 while (!Worklist.empty()) {
4643 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00004644 if (!Visited.insert(I).second)
4645 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00004646
Chris Lattnera337f5e2011-01-09 02:16:18 +00004647 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004648 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004649 if (It != ValueExprMap.end()) {
4650 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00004651
Chris Lattnera337f5e2011-01-09 02:16:18 +00004652 // SCEVUnknown for a PHI either means that it has an unrecognized
4653 // structure, or it's a PHI that's in the progress of being computed
4654 // by createNodeForPHI. In the former case, additional loop trip
4655 // count information isn't going to change anything. In the later
4656 // case, createNodeForPHI will perform the necessary updates on its
4657 // own when it gets to that point.
4658 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4659 forgetMemoizedResults(Old);
4660 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004661 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004662 if (PHINode *PN = dyn_cast<PHINode>(I))
4663 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00004664 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004665
4666 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004667 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004668 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00004669
4670 // Re-lookup the insert position, since the call to
4671 // ComputeBackedgeTakenCount above could result in a
4672 // recusive call to getBackedgeTakenInfo (on a different
4673 // loop), which would invalidate the iterator computed
4674 // earlier.
4675 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00004676}
4677
Dan Gohman880c92a2009-10-31 15:04:55 +00004678/// forgetLoop - This method should be called by the client when it has
4679/// changed a loop in a way that may effect ScalarEvolution's ability to
4680/// compute a trip count, or if the loop is deleted.
4681void ScalarEvolution::forgetLoop(const Loop *L) {
4682 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004683 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4684 BackedgeTakenCounts.find(L);
4685 if (BTCPos != BackedgeTakenCounts.end()) {
4686 BTCPos->second.clear();
4687 BackedgeTakenCounts.erase(BTCPos);
4688 }
Dan Gohmanf1505722009-05-02 17:43:35 +00004689
Dan Gohman880c92a2009-10-31 15:04:55 +00004690 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00004691 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00004692 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004693
Dan Gohmandc191042009-07-08 19:23:34 +00004694 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00004695 while (!Worklist.empty()) {
4696 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00004697 if (!Visited.insert(I).second)
4698 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00004699
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004700 ValueExprMapType::iterator It =
4701 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004702 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004703 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004704 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004705 if (PHINode *PN = dyn_cast<PHINode>(I))
4706 ConstantEvolutionLoopExitValue.erase(PN);
4707 }
4708
4709 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004710 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00004711
4712 // Forget all contained loops too, to avoid dangling entries in the
4713 // ValuesAtScopes map.
4714 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4715 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00004716}
4717
Eric Christopheref6d5932010-07-29 01:25:38 +00004718/// forgetValue - This method should be called by the client when it has
4719/// changed a value in a way that may effect its value, or which may
4720/// disconnect it from a def-use chain linking it to a loop.
4721void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004722 Instruction *I = dyn_cast<Instruction>(V);
4723 if (!I) return;
4724
4725 // Drop information about expressions based on loop-header PHIs.
4726 SmallVector<Instruction *, 16> Worklist;
4727 Worklist.push_back(I);
4728
4729 SmallPtrSet<Instruction *, 8> Visited;
4730 while (!Worklist.empty()) {
4731 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00004732 if (!Visited.insert(I).second)
4733 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004734
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004735 ValueExprMapType::iterator It =
4736 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004737 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004738 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004739 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004740 if (PHINode *PN = dyn_cast<PHINode>(I))
4741 ConstantEvolutionLoopExitValue.erase(PN);
4742 }
4743
4744 PushDefUseChildren(I, Worklist);
4745 }
4746}
4747
Andrew Trick3ca3f982011-07-26 17:19:55 +00004748/// getExact - Get the exact loop backedge taken count considering all loop
Andrew Trick90c7a102011-11-16 00:52:40 +00004749/// exits. A computable result can only be return for loops with a single exit.
4750/// Returning the minimum taken count among all exits is incorrect because one
4751/// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4752/// the limit of each loop test is never skipped. This is a valid assumption as
4753/// long as the loop exits via that test. For precise results, it is the
4754/// caller's responsibility to specify the relevant loop exit using
4755/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00004756const SCEV *
4757ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4758 // If any exits were not computable, the loop is not computable.
4759 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4760
Andrew Trick90c7a102011-11-16 00:52:40 +00004761 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00004762 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004763 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4764
Craig Topper9f008862014-04-15 04:59:12 +00004765 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004766 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004767 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004768
4769 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4770
4771 if (!BECount)
4772 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00004773 else if (BECount != ENT->ExactNotTaken)
4774 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004775 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00004776 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004777 return BECount;
4778}
4779
4780/// getExact - Get the exact not taken count for this loop exit.
4781const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00004782ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00004783 ScalarEvolution *SE) const {
4784 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004785 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004786
Andrew Trick77c55422011-08-02 04:23:35 +00004787 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00004788 return ENT->ExactNotTaken;
4789 }
4790 return SE->getCouldNotCompute();
4791}
4792
4793/// getMax - Get the max backedge taken count for the loop.
4794const SCEV *
4795ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4796 return Max ? Max : SE->getCouldNotCompute();
4797}
4798
Andrew Trick9093e152013-03-26 03:14:53 +00004799bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4800 ScalarEvolution *SE) const {
4801 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4802 return true;
4803
4804 if (!ExitNotTaken.ExitingBlock)
4805 return false;
4806
4807 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004808 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00004809
4810 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4811 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4812 return true;
4813 }
4814 }
4815 return false;
4816}
4817
Andrew Trick3ca3f982011-07-26 17:19:55 +00004818/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4819/// computable exit into a persistent ExitNotTakenInfo array.
4820ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4821 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4822 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4823
4824 if (!Complete)
4825 ExitNotTaken.setIncomplete();
4826
4827 unsigned NumExits = ExitCounts.size();
4828 if (NumExits == 0) return;
4829
Andrew Trick77c55422011-08-02 04:23:35 +00004830 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004831 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4832 if (NumExits == 1) return;
4833
4834 // Handle the rare case of multiple computable exits.
4835 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4836
4837 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4838 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4839 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00004840 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004841 ENT->ExactNotTaken = ExitCounts[i].second;
4842 }
4843}
4844
4845/// clear - Invalidate this result and free the ExitNotTakenInfo array.
4846void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00004847 ExitNotTaken.ExitingBlock = nullptr;
4848 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004849 delete[] ExitNotTaken.getNextExit();
4850}
4851
Dan Gohman0bddac12009-02-24 18:55:53 +00004852/// ComputeBackedgeTakenCount - Compute the number of times the backedge
4853/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00004854ScalarEvolution::BackedgeTakenInfo
4855ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00004856 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00004857 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00004858
Andrew Trick839e30b2014-05-23 19:47:13 +00004859 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004860 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00004861 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00004862 const SCEV *MustExitMaxBECount = nullptr;
4863 const SCEV *MayExitMaxBECount = nullptr;
4864
4865 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4866 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00004867 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00004868 BasicBlock *ExitBB = ExitingBlocks[i];
4869 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4870
4871 // 1. For each exit that can be computed, add an entry to ExitCounts.
4872 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004873 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00004874 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00004875 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004876 CouldComputeBECount = false;
4877 else
Andrew Trick839e30b2014-05-23 19:47:13 +00004878 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
Andrew Trick3ca3f982011-07-26 17:19:55 +00004879
Andrew Trick839e30b2014-05-23 19:47:13 +00004880 // 2. Derive the loop's MaxBECount from each exit's max number of
4881 // non-exiting iterations. Partition the loop exits into two kinds:
4882 // LoopMustExits and LoopMayExits.
4883 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004884 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4885 // is a LoopMayExit. If any computable LoopMustExit is found, then
4886 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4887 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4888 // considered greater than any computable EL.Max.
4889 if (EL.Max != getCouldNotCompute() && Latch &&
Andrew Trick839e30b2014-05-23 19:47:13 +00004890 DT->dominates(ExitBB, Latch)) {
4891 if (!MustExitMaxBECount)
4892 MustExitMaxBECount = EL.Max;
4893 else {
4894 MustExitMaxBECount =
4895 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00004896 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004897 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4898 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4899 MayExitMaxBECount = EL.Max;
4900 else {
4901 MayExitMaxBECount =
4902 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4903 }
Andrew Trick90c7a102011-11-16 00:52:40 +00004904 }
Dan Gohman96212b62009-06-22 00:31:57 +00004905 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004906 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4907 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00004908 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004909}
4910
Andrew Trick3ca3f982011-07-26 17:19:55 +00004911/// ComputeExitLimit - Compute the number of times the backedge of the specified
4912/// loop will execute if it exits via the specified block.
4913ScalarEvolution::ExitLimit
4914ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00004915
4916 // Okay, we've chosen an exiting block. See what condition causes us to
Benjamin Kramer5a188542014-02-11 15:44:32 +00004917 // exit at this block and remember the exit block and whether all other targets
4918 // lead to the loop header.
4919 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00004920 BasicBlock *Exit = nullptr;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004921 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4922 SI != SE; ++SI)
4923 if (!L->contains(*SI)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004924 if (Exit) // Multiple exit successors.
4925 return getCouldNotCompute();
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004926 Exit = *SI;
4927 } else if (*SI != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004928 MustExecuteLoopHeader = false;
4929 }
Dan Gohmance973df2009-06-24 04:48:43 +00004930
Chris Lattner18954852007-01-07 02:24:26 +00004931 // At this point, we know we have a conditional branch that determines whether
4932 // the loop is exited. However, we don't know if the branch is executed each
4933 // time through the loop. If not, then the execution count of the branch will
4934 // not be equal to the trip count of the loop.
4935 //
4936 // Currently we check for this by checking to see if the Exit branch goes to
4937 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00004938 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00004939 // loop header. This is common for un-rotated loops.
4940 //
4941 // If both of those tests fail, walk up the unique predecessor chain to the
4942 // header, stopping if there is an edge that doesn't exit the loop. If the
4943 // header is reached, the execution count of the branch will be equal to the
4944 // trip count of the loop.
4945 //
4946 // More extensive analysis could be done to handle more cases here.
4947 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00004948 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00004949 // The simple checks failed, try climbing the unique predecessor chain
4950 // up to the header.
4951 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00004952 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00004953 BasicBlock *Pred = BB->getUniquePredecessor();
4954 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004955 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004956 TerminatorInst *PredTerm = Pred->getTerminator();
4957 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4958 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4959 if (PredSucc == BB)
4960 continue;
4961 // If the predecessor has a successor that isn't BB and isn't
4962 // outside the loop, assume the worst.
4963 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004964 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004965 }
4966 if (Pred == L->getHeader()) {
4967 Ok = true;
4968 break;
4969 }
4970 BB = Pred;
4971 }
4972 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004973 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004974 }
4975
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004976 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004977 TerminatorInst *Term = ExitingBlock->getTerminator();
4978 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4979 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4980 // Proceed to the next level to examine the exit condition expression.
4981 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4982 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004983 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004984 }
4985
4986 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4987 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004988 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004989
4990 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004991}
4992
Andrew Trick3ca3f982011-07-26 17:19:55 +00004993/// ComputeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00004994/// backedge of the specified loop will execute if its exit condition
4995/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00004996///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004997/// @param ControlsExit is true if ExitCond directly controls the exit
4998/// branch. In this case, we can assume that the loop exits only if the
4999/// condition is true and can infer that failing to meet the condition prior to
5000/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005001ScalarEvolution::ExitLimit
5002ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
5003 Value *ExitCond,
5004 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005005 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005006 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005007 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5009 if (BO->getOpcode() == Instruction::And) {
5010 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005011 bool EitherMayExit = L->contains(TBB);
5012 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005013 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00005014 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005015 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005016 const SCEV *BECount = getCouldNotCompute();
5017 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005018 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005019 // Both conditions must be true for the loop to continue executing.
5020 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005021 if (EL0.Exact == getCouldNotCompute() ||
5022 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005023 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005024 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005025 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5026 if (EL0.Max == getCouldNotCompute())
5027 MaxBECount = EL1.Max;
5028 else if (EL1.Max == getCouldNotCompute())
5029 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005030 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005031 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005032 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005033 // Both conditions must be true at the same time for the loop to exit.
5034 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005035 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005036 if (EL0.Max == EL1.Max)
5037 MaxBECount = EL0.Max;
5038 if (EL0.Exact == EL1.Exact)
5039 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005040 }
5041
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005042 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005043 }
5044 if (BO->getOpcode() == Instruction::Or) {
5045 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005046 bool EitherMayExit = L->contains(FBB);
5047 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005048 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00005049 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005050 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005051 const SCEV *BECount = getCouldNotCompute();
5052 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005053 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005054 // Both conditions must be false for the loop to continue executing.
5055 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005056 if (EL0.Exact == getCouldNotCompute() ||
5057 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005058 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005059 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005060 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5061 if (EL0.Max == getCouldNotCompute())
5062 MaxBECount = EL1.Max;
5063 else if (EL1.Max == getCouldNotCompute())
5064 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005065 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005066 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005067 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005068 // Both conditions must be false at the same time for the loop to exit.
5069 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005070 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005071 if (EL0.Max == EL1.Max)
5072 MaxBECount = EL0.Max;
5073 if (EL0.Exact == EL1.Exact)
5074 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005075 }
5076
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005077 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005078 }
5079 }
5080
5081 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005082 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00005083 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005084 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00005085
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005086 // Check for a constant condition. These are normally stripped out by
5087 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5088 // preserve the CFG and is temporarily leaving constant conditions
5089 // in place.
5090 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5091 if (L->contains(FBB) == !CI->getZExtValue())
5092 // The backedge is always taken.
5093 return getCouldNotCompute();
5094 else
5095 // The backedge is never taken.
Dan Gohman1d2ded72010-05-03 22:09:21 +00005096 return getConstant(CI->getType(), 0);
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005097 }
5098
Eli Friedmanebf98b02009-05-09 12:32:42 +00005099 // If it's not an integer or pointer comparison then compute it the hard way.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005100 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005101}
5102
Andrew Trick3ca3f982011-07-26 17:19:55 +00005103/// ComputeExitLimitFromICmp - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005104/// backedge of the specified loop will execute if its exit condition
5105/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005106ScalarEvolution::ExitLimit
5107ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
5108 ICmpInst *ExitCond,
5109 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005110 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005111 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005112
Reid Spencer266e42b2006-12-23 06:05:41 +00005113 // If the condition was exit on true, convert the condition to exit on false
5114 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005115 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005116 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005117 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005118 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005119
5120 // Handle common loops like: for (X = "string"; *X; ++X)
5121 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5122 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005123 ExitLimit ItCnt =
5124 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005125 if (ItCnt.hasAnyInfo())
5126 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005127 }
5128
Dan Gohmanaf752342009-07-07 17:06:11 +00005129 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5130 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005131
5132 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005133 LHS = getSCEVAtScope(LHS, L);
5134 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005135
Dan Gohmance973df2009-06-24 04:48:43 +00005136 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005137 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005138 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005139 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005140 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005141 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005142 }
5143
Dan Gohman81585c12010-05-03 16:35:17 +00005144 // Simplify the operands before analyzing them.
5145 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5146
Chris Lattnerd934c702004-04-02 20:23:17 +00005147 // If we have a comparison of a chrec against a constant, try to use value
5148 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005149 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5150 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005151 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005152 // Form the constant range.
5153 ConstantRange CompRange(
5154 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005155
Dan Gohmanaf752342009-07-07 17:06:11 +00005156 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005157 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005158 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005159
Chris Lattnerd934c702004-04-02 20:23:17 +00005160 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005161 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005162 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005163 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005164 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005165 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005166 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005167 case ICmpInst::ICMP_EQ: { // while (X == Y)
5168 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005169 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5170 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005171 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005172 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005173 case ICmpInst::ICMP_SLT:
5174 case ICmpInst::ICMP_ULT: { // while (X < Y)
5175 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005176 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005177 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005178 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005179 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005180 case ICmpInst::ICMP_SGT:
5181 case ICmpInst::ICMP_UGT: { // while (X > Y)
5182 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005183 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005184 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005185 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005186 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005187 default:
Chris Lattner09169212004-04-02 20:26:46 +00005188#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005189 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattnerd934c702004-04-02 20:23:17 +00005190 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greenedf1c4972009-12-23 22:18:14 +00005191 dbgs() << "[unsigned] ";
5192 dbgs() << *LHS << " "
Dan Gohmance973df2009-06-24 04:48:43 +00005193 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencer266e42b2006-12-23 06:05:41 +00005194 << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00005195#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00005196 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005197 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005198 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005199}
5200
Benjamin Kramer5a188542014-02-11 15:44:32 +00005201ScalarEvolution::ExitLimit
5202ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5203 SwitchInst *Switch,
5204 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005205 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005206 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5207
5208 // Give up if the exit is the default dest of a switch.
5209 if (Switch->getDefaultDest() == ExitingBlock)
5210 return getCouldNotCompute();
5211
5212 assert(L->contains(Switch->getDefaultDest()) &&
5213 "Default case must not exit the loop!");
5214 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5215 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5216
5217 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005218 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005219 if (EL.hasAnyInfo())
5220 return EL;
5221
5222 return getCouldNotCompute();
5223}
5224
Chris Lattnerec901cc2004-10-12 01:49:27 +00005225static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005226EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5227 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005228 const SCEV *InVal = SE.getConstant(C);
5229 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005230 assert(isa<SCEVConstant>(Val) &&
5231 "Evaluation of SCEV at constant didn't fold correctly?");
5232 return cast<SCEVConstant>(Val)->getValue();
5233}
5234
Andrew Trick3ca3f982011-07-26 17:19:55 +00005235/// ComputeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005236/// 'icmp op load X, cst', try to see if we can compute the backedge
5237/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005238ScalarEvolution::ExitLimit
5239ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5240 LoadInst *LI,
5241 Constant *RHS,
5242 const Loop *L,
5243 ICmpInst::Predicate predicate) {
5244
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005245 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005246
5247 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005248 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005249 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005250 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005251
5252 // Make sure that it is really a constant global we are gepping, with an
5253 // initializer, and make sure the first IDX is really 0.
5254 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005255 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005256 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5257 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005258 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005259
5260 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005261 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005262 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005263 unsigned VarIdxNum = 0;
5264 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5265 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5266 Indexes.push_back(CI);
5267 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005268 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005269 VarIdx = GEP->getOperand(i);
5270 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005271 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005272 }
5273
Andrew Trick7004e4b2012-03-26 22:33:59 +00005274 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5275 if (!VarIdx)
5276 return getCouldNotCompute();
5277
Chris Lattnerec901cc2004-10-12 01:49:27 +00005278 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5279 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005280 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005281 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005282
5283 // We can only recognize very limited forms of loop index expressions, in
5284 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005285 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005286 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005287 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5288 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005289 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005290
5291 unsigned MaxSteps = MaxBruteForceIterations;
5292 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005293 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005294 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005295 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005296
5297 // Form the GEP offset.
5298 Indexes[VarIdxNum] = Val;
5299
Chris Lattnere166a852012-01-24 05:49:24 +00005300 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5301 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005302 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005303
5304 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005305 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005306 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005307 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005308#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005309 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmane20f8242009-04-21 00:47:46 +00005310 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5311 << "***\n";
Chris Lattnerec901cc2004-10-12 01:49:27 +00005312#endif
5313 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005314 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005315 }
5316 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005317 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005318}
5319
5320
Chris Lattnerdd730472004-04-17 22:58:41 +00005321/// CanConstantFold - Return true if we can constant fold an instruction of the
5322/// specified type, assuming that all operands were constants.
5323static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005324 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005325 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5326 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005327 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005328
Chris Lattnerdd730472004-04-17 22:58:41 +00005329 if (const CallInst *CI = dyn_cast<CallInst>(I))
5330 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005331 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005332 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005333}
5334
Andrew Trick3a86ba72011-10-05 03:25:31 +00005335/// Determine whether this instruction can constant evolve within this loop
5336/// assuming its operands can all constant evolve.
5337static bool canConstantEvolve(Instruction *I, const Loop *L) {
5338 // An instruction outside of the loop can't be derived from a loop PHI.
5339 if (!L->contains(I)) return false;
5340
5341 if (isa<PHINode>(I)) {
5342 if (L->getHeader() == I->getParent())
5343 return true;
5344 else
5345 // We don't currently keep track of the control flow needed to evaluate
5346 // PHIs, so we cannot handle PHIs inside of loops.
5347 return false;
5348 }
5349
5350 // If we won't be able to constant fold this expression even if the operands
5351 // are constants, bail early.
5352 return CanConstantFold(I);
5353}
5354
5355/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5356/// recursing through each instruction operand until reaching a loop header phi.
5357static PHINode *
5358getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005359 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005360
5361 // Otherwise, we can evaluate this instruction if all of its operands are
5362 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005363 PHINode *PHI = nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005364 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5365 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5366
5367 if (isa<Constant>(*OpI)) continue;
5368
5369 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
Craig Topper9f008862014-04-15 04:59:12 +00005370 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005371
5372 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005373 if (!P)
5374 // If this operand is already visited, reuse the prior result.
5375 // We may have P != PHI if this is the deepest point at which the
5376 // inconsistent paths meet.
5377 P = PHIMap.lookup(OpInst);
5378 if (!P) {
5379 // Recurse and memoize the results, whether a phi is found or not.
5380 // This recursive call invalidates pointers into PHIMap.
5381 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5382 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005383 }
Craig Topper9f008862014-04-15 04:59:12 +00005384 if (!P)
5385 return nullptr; // Not evolving from PHI
5386 if (PHI && PHI != P)
5387 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005388 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005389 }
5390 // This is a expression evolving from a constant PHI!
5391 return PHI;
5392}
5393
Chris Lattnerdd730472004-04-17 22:58:41 +00005394/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5395/// in the loop that V is derived from. We allow arbitrary operations along the
5396/// way, but the operands of an operation must either be constants or a value
5397/// derived from a constant PHI. If this expression does not fit with these
5398/// constraints, return null.
5399static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005400 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005401 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005402
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005403 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005404 return PN;
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005405 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005406
Andrew Trick3a86ba72011-10-05 03:25:31 +00005407 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005408 DenseMap<Instruction *, PHINode *> PHIMap;
5409 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005410}
5411
5412/// EvaluateExpression - Given an expression that passes the
5413/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5414/// in the loop has the value PHIVal. If we can't fold this expression for some
5415/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005416static Constant *EvaluateExpression(Value *V, const Loop *L,
5417 DenseMap<Instruction *, Constant *> &Vals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005418 const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005419 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005420 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005421 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005422 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005423 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005424
Andrew Trick3a86ba72011-10-05 03:25:31 +00005425 if (Constant *C = Vals.lookup(I)) return C;
5426
Nick Lewyckya6674c72011-10-22 19:58:20 +00005427 // An instruction inside the loop depends on a value outside the loop that we
5428 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005429 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005430
5431 // An unmapped PHI can be due to a branch or another loop inside this loop,
5432 // or due to this not being the initial iteration through a loop where we
5433 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005434 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005435
Dan Gohmanf820bd32010-06-22 13:15:46 +00005436 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005437
5438 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005439 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5440 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005441 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005442 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005443 continue;
5444 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005445 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005446 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005447 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005448 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005449 }
5450
Nick Lewyckya6674c72011-10-22 19:58:20 +00005451 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005452 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005453 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005454 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5455 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005456 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005457 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005458 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005459 TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00005460}
5461
5462/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5463/// in the header of its containing loop, we know the loop executes a
5464/// constant number of times, and the PHI node is just a recurrence
5465/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00005466Constant *
5467ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00005468 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00005469 const Loop *L) {
Dan Gohman0daf6872011-05-09 18:44:09 +00005470 DenseMap<PHINode*, Constant*>::const_iterator I =
Chris Lattnerdd730472004-04-17 22:58:41 +00005471 ConstantEvolutionLoopExitValue.find(PN);
5472 if (I != ConstantEvolutionLoopExitValue.end())
5473 return I->second;
5474
Dan Gohman4ce1fb12010-04-08 23:03:40 +00005475 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00005476 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00005477
5478 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5479
Andrew Trick3a86ba72011-10-05 03:25:31 +00005480 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005481 BasicBlock *Header = L->getHeader();
5482 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00005483
Chris Lattnerdd730472004-04-17 22:58:41 +00005484 // Since the loop is canonicalized, the PHI node must have two entries. One
5485 // entry must be a constant (coming in from outside of the loop), and the
5486 // second must be derived from the same PHI.
5487 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005488 PHINode *PHI = nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005489 for (BasicBlock::iterator I = Header->begin();
5490 (PHI = dyn_cast<PHINode>(I)); ++I) {
5491 Constant *StartCST =
5492 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005493 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005494 CurrentIterVals[PHI] = StartCST;
5495 }
5496 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00005497 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005498
5499 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Chris Lattnerdd730472004-04-17 22:58:41 +00005500
5501 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00005502 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00005503 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00005504
Dan Gohman0bddac12009-02-24 18:55:53 +00005505 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00005506 unsigned IterationNum = 0;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005507 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005508 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00005509 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00005510
Nick Lewyckya6674c72011-10-22 19:58:20 +00005511 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005512 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005513 DenseMap<Instruction *, Constant *> NextIterVals;
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005514 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005515 TLI);
Craig Topper9f008862014-04-15 04:59:12 +00005516 if (!NextPHI)
5517 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00005518 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005519
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005520 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5521
Nick Lewyckya6674c72011-10-22 19:58:20 +00005522 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5523 // cease to be able to evaluate one of them or if they stop evolving,
5524 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005525 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005526 for (DenseMap<Instruction *, Constant *>::const_iterator
5527 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5528 PHINode *PHI = dyn_cast<PHINode>(I->first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00005529 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005530 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5531 }
5532 // We use two distinct loops because EvaluateExpression may invalidate any
5533 // iterators into CurrentIterVals.
5534 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5535 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5536 PHINode *PHI = I->first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005537 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005538 if (!NextPHI) { // Not already computed.
5539 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005540 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005541 }
5542 if (NextPHI != I->second)
5543 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005544 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005545
5546 // If all entries in CurrentIterVals == NextIterVals then we can stop
5547 // iterating, the loop can't continue to change.
5548 if (StoppedEvolving)
5549 return RetVal = CurrentIterVals[PN];
5550
Andrew Trick3a86ba72011-10-05 03:25:31 +00005551 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00005552 }
5553}
5554
Andrew Trick3ca3f982011-07-26 17:19:55 +00005555/// ComputeExitCountExhaustively - If the loop is known to execute a
Chris Lattner4021d1a2004-04-17 18:36:24 +00005556/// constant number of times (the condition evolves only from constants),
5557/// try to evaluate a few iterations of the loop until we get the exit
5558/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005559/// evaluate the trip count of the loop, return getCouldNotCompute().
Nick Lewyckya6674c72011-10-22 19:58:20 +00005560const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5561 Value *Cond,
5562 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005563 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00005564 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005565
Dan Gohman866971e2010-06-19 14:17:24 +00005566 // If the loop is canonicalized, the PHI will have exactly two entries.
5567 // That's the only form we support here.
5568 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5569
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005570 DenseMap<Instruction *, Constant *> CurrentIterVals;
5571 BasicBlock *Header = L->getHeader();
5572 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5573
Dan Gohman866971e2010-06-19 14:17:24 +00005574 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner4021d1a2004-04-17 18:36:24 +00005575 // second must be derived from the same PHI.
5576 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005577 PHINode *PHI = nullptr;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005578 for (BasicBlock::iterator I = Header->begin();
5579 (PHI = dyn_cast<PHINode>(I)); ++I) {
5580 Constant *StartCST =
5581 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005582 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005583 CurrentIterVals[PHI] = StartCST;
5584 }
5585 if (!CurrentIterVals.count(PN))
5586 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005587
5588 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5589 // the loop symbolically to determine when the condition gets a value of
5590 // "ExitWhen".
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005591
Andrew Trick90c7a102011-11-16 00:52:40 +00005592 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005593 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Zhou Sheng75b871f2007-01-11 12:24:14 +00005594 ConstantInt *CondVal =
Chad Rosiere6de63d2011-12-01 21:29:16 +00005595 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005596 DL, TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00005597
Zhou Sheng75b871f2007-01-11 12:24:14 +00005598 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005599 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00005600
Reid Spencer983e3b32007-03-01 07:25:48 +00005601 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005602 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00005603 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005604 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005605
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005606 // Update all the PHI nodes for the next iteration.
5607 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005608
5609 // Create a list of which PHIs we need to compute. We want to do this before
5610 // calling EvaluateExpression on them because that may invalidate iterators
5611 // into CurrentIterVals.
5612 SmallVector<PHINode *, 8> PHIsToCompute;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005613 for (DenseMap<Instruction *, Constant *>::const_iterator
5614 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5615 PHINode *PHI = dyn_cast<PHINode>(I->first);
5616 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005617 PHIsToCompute.push_back(PHI);
5618 }
5619 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5620 E = PHIsToCompute.end(); I != E; ++I) {
5621 PHINode *PHI = *I;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005622 Constant *&NextPHI = NextIterVals[PHI];
5623 if (NextPHI) continue; // Already computed!
5624
5625 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005626 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005627 }
5628 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005629 }
5630
5631 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005632 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005633}
5634
Dan Gohman237d9e52009-09-03 15:00:26 +00005635/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005636/// at the specified scope in the program. The L value specifies a loop
5637/// nest to evaluate the expression at, where null is the top-level or a
5638/// specified loop is immediately inside of the loop.
5639///
5640/// This method can be used to compute the exit value for a variable defined
5641/// in a loop by querying what the value will hold in the parent loop.
5642///
Dan Gohman8ca08852009-05-24 23:25:42 +00005643/// In the case that a relevant loop exit value cannot be computed, the
5644/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005645const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005646 // Check to see if we've folded this expression at this loop before.
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005647 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5648 for (unsigned u = 0; u < Values.size(); u++) {
5649 if (Values[u].first == L)
5650 return Values[u].second ? Values[u].second : V;
5651 }
Craig Topper9f008862014-04-15 04:59:12 +00005652 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005653 // Otherwise compute it.
5654 const SCEV *C = computeSCEVAtScope(V, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005655 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5656 for (unsigned u = Values2.size(); u > 0; u--) {
5657 if (Values2[u - 1].first == L) {
5658 Values2[u - 1].second = C;
5659 break;
5660 }
5661 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005662 return C;
5663}
5664
Nick Lewyckya6674c72011-10-22 19:58:20 +00005665/// This builds up a Constant using the ConstantExpr interface. That way, we
5666/// will return Constants for objects which aren't represented by a
5667/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5668/// Returns NULL if the SCEV isn't representable as a Constant.
5669static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00005670 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00005671 case scCouldNotCompute:
5672 case scAddRecExpr:
5673 break;
5674 case scConstant:
5675 return cast<SCEVConstant>(V)->getValue();
5676 case scUnknown:
5677 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5678 case scSignExtend: {
5679 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5680 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5681 return ConstantExpr::getSExt(CastOp, SS->getType());
5682 break;
5683 }
5684 case scZeroExtend: {
5685 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5686 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5687 return ConstantExpr::getZExt(CastOp, SZ->getType());
5688 break;
5689 }
5690 case scTruncate: {
5691 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5692 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5693 return ConstantExpr::getTrunc(CastOp, ST->getType());
5694 break;
5695 }
5696 case scAddExpr: {
5697 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5698 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005699 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5700 unsigned AS = PTy->getAddressSpace();
5701 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5702 C = ConstantExpr::getBitCast(C, DestPtrTy);
5703 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00005704 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5705 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005706 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005707
5708 // First pointer!
5709 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005710 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00005711 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005712 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005713 // The offsets have been converted to bytes. We can add bytes to an
5714 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005715 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005716 }
5717
5718 // Don't bother trying to sum two pointers. We probably can't
5719 // statically compute a load that results from it anyway.
5720 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00005721 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005722
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005723 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5724 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00005725 C2 = ConstantExpr::getIntegerCast(
5726 C2, Type::getInt32Ty(C->getContext()), true);
5727 C = ConstantExpr::getGetElementPtr(C, C2);
5728 } else
5729 C = ConstantExpr::getAdd(C, C2);
5730 }
5731 return C;
5732 }
5733 break;
5734 }
5735 case scMulExpr: {
5736 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5737 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5738 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00005739 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005740 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5741 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005742 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005743 C = ConstantExpr::getMul(C, C2);
5744 }
5745 return C;
5746 }
5747 break;
5748 }
5749 case scUDivExpr: {
5750 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5751 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5752 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5753 if (LHS->getType() == RHS->getType())
5754 return ConstantExpr::getUDiv(LHS, RHS);
5755 break;
5756 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00005757 case scSMaxExpr:
5758 case scUMaxExpr:
5759 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005760 }
Craig Topper9f008862014-04-15 04:59:12 +00005761 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005762}
5763
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005764const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005765 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00005766
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005767 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00005768 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00005769 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005770 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005771 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00005772 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5773 if (PHINode *PN = dyn_cast<PHINode>(I))
5774 if (PN->getParent() == LI->getHeader()) {
5775 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00005776 // to see if the loop that contains it has a known backedge-taken
5777 // count. If so, we may be able to force computation of the exit
5778 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00005779 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00005780 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00005781 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005782 // Okay, we know how many times the containing loop executes. If
5783 // this is a constant evolving PHI node, get the final value at
5784 // the specified iteration number.
5785 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman0bddac12009-02-24 18:55:53 +00005786 BTCC->getValue()->getValue(),
Chris Lattnerdd730472004-04-17 22:58:41 +00005787 LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00005788 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00005789 }
5790 }
5791
Reid Spencere6328ca2006-12-04 21:33:23 +00005792 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00005793 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00005794 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00005795 // result. This is particularly useful for computing loop exit values.
5796 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005797 SmallVector<Constant *, 4> Operands;
5798 bool MadeImprovement = false;
Chris Lattnerdd730472004-04-17 22:58:41 +00005799 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5800 Value *Op = I->getOperand(i);
5801 if (Constant *C = dyn_cast<Constant>(Op)) {
5802 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005803 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00005804 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005805
5806 // If any of the operands is non-constant and if they are
5807 // non-integer and non-pointer, don't even try to analyze them
5808 // with scev techniques.
5809 if (!isSCEVable(Op->getType()))
5810 return V;
5811
5812 const SCEV *OrigV = getSCEV(Op);
5813 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5814 MadeImprovement |= OrigV != OpV;
5815
Nick Lewyckya6674c72011-10-22 19:58:20 +00005816 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005817 if (!C) return V;
5818 if (C->getType() != Op->getType())
5819 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5820 Op->getType(),
5821 false),
5822 C, Op->getType());
5823 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00005824 }
Dan Gohmance973df2009-06-24 04:48:43 +00005825
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005826 // Check to see if getSCEVAtScope actually made an improvement.
5827 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00005828 Constant *C = nullptr;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005829 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5830 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005831 Operands[0], Operands[1], DL,
Chad Rosier43a33062011-12-02 01:26:24 +00005832 TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005833 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5834 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005835 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005836 } else
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005837 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005838 Operands, DL, TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005839 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00005840 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005841 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005842 }
5843 }
5844
5845 // This is some other type of SCEVUnknown, just return it.
5846 return V;
5847 }
5848
Dan Gohmana30370b2009-05-04 22:02:23 +00005849 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005850 // Avoid performing the look-up in the common case where the specified
5851 // expression has no loop-variant portions.
5852 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005853 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005854 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005855 // Okay, at least one of these operands is loop variant but might be
5856 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00005857 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5858 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00005859 NewOps.push_back(OpAtScope);
5860
5861 for (++i; i != e; ++i) {
5862 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005863 NewOps.push_back(OpAtScope);
5864 }
5865 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005866 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005867 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005868 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005869 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005870 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005871 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005872 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00005873 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005874 }
5875 }
5876 // If we got here, all operands are loop invariant.
5877 return Comm;
5878 }
5879
Dan Gohmana30370b2009-05-04 22:02:23 +00005880 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005881 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5882 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00005883 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5884 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00005885 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00005886 }
5887
5888 // If this is a loop recurrence for a loop that does not contain L, then we
5889 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00005890 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005891 // First, attempt to evaluate each operand.
5892 // Avoid performing the look-up in the common case where the specified
5893 // expression has no loop-variant portions.
5894 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5895 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5896 if (OpAtScope == AddRec->getOperand(i))
5897 continue;
5898
5899 // Okay, at least one of these operands is loop variant but might be
5900 // foldable. Build a new instance of the folded commutative expression.
5901 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5902 AddRec->op_begin()+i);
5903 NewOps.push_back(OpAtScope);
5904 for (++i; i != e; ++i)
5905 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5906
Andrew Trick759ba082011-04-27 01:21:25 +00005907 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00005908 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00005909 AddRec->getNoWrapFlags(SCEV::FlagNW));
5910 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00005911 // The addrec may be folded to a nonrecurrence, for example, if the
5912 // induction variable is multiplied by zero after constant folding. Go
5913 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00005914 if (!AddRec)
5915 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005916 break;
5917 }
5918
5919 // If the scope is outside the addrec's loop, evaluate it by using the
5920 // loop exit value of the addrec.
5921 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005922 // To evaluate this recurrence, we need to know how many times the AddRec
5923 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005924 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005925 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00005926
Eli Friedman61f67622008-08-04 23:49:06 +00005927 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00005928 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00005929 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005930
Dan Gohman8ca08852009-05-24 23:25:42 +00005931 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00005932 }
5933
Dan Gohmana30370b2009-05-04 22:02:23 +00005934 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005935 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005936 if (Op == Cast->getOperand())
5937 return Cast; // must be loop invariant
5938 return getZeroExtendExpr(Op, Cast->getType());
5939 }
5940
Dan Gohmana30370b2009-05-04 22:02:23 +00005941 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005942 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005943 if (Op == Cast->getOperand())
5944 return Cast; // must be loop invariant
5945 return getSignExtendExpr(Op, Cast->getType());
5946 }
5947
Dan Gohmana30370b2009-05-04 22:02:23 +00005948 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005949 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005950 if (Op == Cast->getOperand())
5951 return Cast; // must be loop invariant
5952 return getTruncateExpr(Op, Cast->getType());
5953 }
5954
Torok Edwinfbcc6632009-07-14 16:55:14 +00005955 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005956}
5957
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005958/// getSCEVAtScope - This is a convenience function which does
5959/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00005960const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005961 return getSCEVAtScope(getSCEV(V), L);
5962}
5963
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005964/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5965/// following equation:
5966///
5967/// A * X = B (mod N)
5968///
5969/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5970/// A and B isn't important.
5971///
5972/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005973static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005974 ScalarEvolution &SE) {
5975 uint32_t BW = A.getBitWidth();
5976 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5977 assert(A != 0 && "A must be non-zero.");
5978
5979 // 1. D = gcd(A, N)
5980 //
5981 // The gcd of A and N may have only one prime factor: 2. The number of
5982 // trailing zeros in A is its multiplicity
5983 uint32_t Mult2 = A.countTrailingZeros();
5984 // D = 2^Mult2
5985
5986 // 2. Check if B is divisible by D.
5987 //
5988 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5989 // is not less than multiplicity of this prime factor for D.
5990 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00005991 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005992
5993 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5994 // modulo (N / D).
5995 //
5996 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5997 // bit width during computations.
5998 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5999 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006000 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006001 APInt I = AD.multiplicativeInverse(Mod);
6002
6003 // 4. Compute the minimum unsigned root of the equation:
6004 // I * (B / D) mod (N / D)
6005 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6006
6007 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6008 // bits.
6009 return SE.getConstant(Result.trunc(BW));
6010}
Chris Lattnerd934c702004-04-02 20:23:17 +00006011
6012/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6013/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6014/// might be the same) or two SCEVCouldNotCompute objects.
6015///
Dan Gohmanaf752342009-07-07 17:06:11 +00006016static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006017SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006018 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006019 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6020 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6021 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006022
Chris Lattnerd934c702004-04-02 20:23:17 +00006023 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00006024 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00006025 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006026 return std::make_pair(CNC, CNC);
6027 }
6028
Reid Spencer983e3b32007-03-01 07:25:48 +00006029 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnercad61e82007-04-15 19:52:49 +00006030 const APInt &L = LC->getValue()->getValue();
6031 const APInt &M = MC->getValue()->getValue();
6032 const APInt &N = NC->getValue()->getValue();
Reid Spencer983e3b32007-03-01 07:25:48 +00006033 APInt Two(BitWidth, 2);
6034 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006035
Dan Gohmance973df2009-06-24 04:48:43 +00006036 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006037 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006038 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006039 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6040 // The B coefficient is M-N/2
6041 APInt B(M);
6042 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006043
Reid Spencer983e3b32007-03-01 07:25:48 +00006044 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006045 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006046
Reid Spencer983e3b32007-03-01 07:25:48 +00006047 // Compute the B^2-4ac term.
6048 APInt SqrtTerm(B);
6049 SqrtTerm *= B;
6050 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006051
Nick Lewyckyfb780832012-08-01 09:14:36 +00006052 if (SqrtTerm.isNegative()) {
6053 // The loop is provably infinite.
6054 const SCEV *CNC = SE.getCouldNotCompute();
6055 return std::make_pair(CNC, CNC);
6056 }
6057
Reid Spencer983e3b32007-03-01 07:25:48 +00006058 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6059 // integer value or else APInt::sqrt() will assert.
6060 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006061
Dan Gohmance973df2009-06-24 04:48:43 +00006062 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00006063 // The divisions must be performed as signed divisions.
6064 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00006065 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00006066 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00006067 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky7b14e202008-11-03 02:43:49 +00006068 return std::make_pair(CNC, CNC);
6069 }
6070
Owen Anderson47db9412009-07-22 00:24:57 +00006071 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00006072
6073 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006074 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00006075 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006076 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00006077
Dan Gohmance973df2009-06-24 04:48:43 +00006078 return std::make_pair(SE.getConstant(Solution1),
Dan Gohmana37eaf22007-10-22 18:31:58 +00006079 SE.getConstant(Solution2));
Nick Lewycky31555522011-10-03 07:10:45 +00006080 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00006081}
6082
6083/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00006084/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00006085///
6086/// This is only used for loops with a "x != y" exit test. The exit condition is
6087/// now expressed as a single expression, V = x-y. So the exit test is
6088/// effectively V != 0. We know and take advantage of the fact that this
6089/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006090ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006091ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006092 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00006093 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006094 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00006095 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006096 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006097 }
6098
Dan Gohman48f82222009-05-04 22:30:44 +00006099 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00006100 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006101 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006102
Chris Lattnerdff679f2011-01-09 22:39:48 +00006103 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6104 // the quadratic equation to solve it.
6105 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6106 std::pair<const SCEV *,const SCEV *> Roots =
6107 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00006108 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6109 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00006110 if (R1 && R2) {
Chris Lattner09169212004-04-02 20:26:46 +00006111#if 0
David Greenedf1c4972009-12-23 22:18:14 +00006112 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmane20f8242009-04-21 00:47:46 +00006113 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00006114#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00006115 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006116 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00006117 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6118 R1->getValue(),
6119 R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006120 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00006121 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00006122
Chris Lattnerd934c702004-04-02 20:23:17 +00006123 // We can only use this value if the chrec ends up with an exact zero
6124 // value at this index. When solving for "X*X != 5", for example, we
6125 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006126 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006127 if (Val->isZero())
6128 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006129 }
6130 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006131 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006132 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006133
Chris Lattnerdff679f2011-01-09 22:39:48 +00006134 // Otherwise we can only handle this if it is affine.
6135 if (!AddRec->isAffine())
6136 return getCouldNotCompute();
6137
6138 // If this is an affine expression, the execution count of this branch is
6139 // the minimum unsigned root of the following equation:
6140 //
6141 // Start + Step*N = 0 (mod 2^BW)
6142 //
6143 // equivalent to:
6144 //
6145 // Step*N = -Start (mod 2^BW)
6146 //
6147 // where BW is the common bit width of Start and Step.
6148
6149 // Get the initial value for the loop.
6150 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6151 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6152
6153 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006154 //
6155 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6156 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6157 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6158 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006159 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006160 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006161 return getCouldNotCompute();
6162
Andrew Trick8b55b732011-03-14 16:50:06 +00006163 // For positive steps (counting up until unsigned overflow):
6164 // N = -Start/Step (as unsigned)
6165 // For negative steps (counting down to zero):
6166 // N = Start/-Step
6167 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickf1781db2011-03-14 17:28:02 +00006168 bool CountDown = StepC->getValue()->getValue().isNegative();
6169 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006170
6171 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006172 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6173 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006174 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6175 ConstantRange CR = getUnsignedRange(Start);
6176 const SCEV *MaxBECount;
6177 if (!CountDown && CR.getUnsignedMin().isMinValue())
6178 // When counting up, the worst starting value is 1, not 0.
6179 MaxBECount = CR.getUnsignedMax().isMinValue()
6180 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6181 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6182 else
6183 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6184 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006185 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006186 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006187
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006188 // As a special case, handle the instance where Step is a positive power of
6189 // two. In this case, determining whether Step divides Distance evenly can be
6190 // done by counting and comparing the number of trailing zeros of Step and
6191 // Distance.
6192 if (!CountDown) {
6193 const APInt &StepV = StepC->getValue()->getValue();
6194 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
6195 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6196 // case is not handled as this code is guarded by !CountDown.
6197 if (StepV.isPowerOf2() &&
6198 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros())
6199 return getUDivExactExpr(Distance, Step);
6200 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006201
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006202 // If the condition controls loop exit (the loop exits only if the expression
6203 // is true) and the addition is no-wrap we can use unsigned divide to
6204 // compute the backedge count. In this case, the step may not divide the
6205 // distance, but we don't care because if the condition is "missed" the loop
6206 // will have undefined behavior due to wrapping.
6207 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6208 const SCEV *Exact =
6209 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6210 return ExitLimit(Exact, Exact);
6211 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006212
Chris Lattnerdff679f2011-01-09 22:39:48 +00006213 // Then, try to solve the above equation provided that Start is constant.
6214 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6215 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6216 -StartC->getValue()->getValue(),
6217 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006218 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006219}
6220
6221/// HowFarToNonZero - Return the number of times a backedge checking the
6222/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006223/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006224ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006225ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006226 // Loops that look like: while (X == 0) are very strange indeed. We don't
6227 // handle them yet except for the trivial case. This could be expanded in the
6228 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006229
Chris Lattnerd934c702004-04-02 20:23:17 +00006230 // If the value is a constant, check to see if it is known to be non-zero
6231 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006232 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006233 if (!C->getValue()->isNullValue())
Dan Gohman1d2ded72010-05-03 22:09:21 +00006234 return getConstant(C->getType(), 0);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006235 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006236 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006237
Chris Lattnerd934c702004-04-02 20:23:17 +00006238 // We could implement others, but I really doubt anyone writes loops like
6239 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006240 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006241}
6242
Dan Gohmanf9081a22008-09-15 22:18:04 +00006243/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6244/// (which may not be an immediate predecessor) which has exactly one
6245/// successor from which BB is reachable, or null if no such block is
6246/// found.
6247///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006248std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006249ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006250 // If the block has a unique predecessor, then there is no path from the
6251 // predecessor to the block that does not go through the direct edge
6252 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006253 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman4e3c1132010-04-15 16:19:08 +00006254 return std::make_pair(Pred, BB);
Dan Gohmanf9081a22008-09-15 22:18:04 +00006255
6256 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006257 // If the header has a unique predecessor outside the loop, it must be
6258 // a block that has exactly one successor that can reach the loop.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006259 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006260 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanf9081a22008-09-15 22:18:04 +00006261
Dan Gohman4e3c1132010-04-15 16:19:08 +00006262 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanf9081a22008-09-15 22:18:04 +00006263}
6264
Dan Gohman450f4e02009-06-20 00:35:32 +00006265/// HasSameValue - SCEV structural equivalence is usually sufficient for
6266/// testing whether two expressions are equal, however for the purposes of
6267/// looking for a condition guarding a loop, it can be useful to be a little
6268/// more general, since a front-end may have replicated the controlling
6269/// expression.
6270///
Dan Gohmanaf752342009-07-07 17:06:11 +00006271static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006272 // Quick check to see if they are the same SCEV.
6273 if (A == B) return true;
6274
6275 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6276 // two different instructions with the same value. Check for this case.
6277 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6278 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6279 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6280 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman2d085562009-08-25 17:56:57 +00006281 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman450f4e02009-06-20 00:35:32 +00006282 return true;
6283
6284 // Otherwise assume they may have a different value.
6285 return false;
6286}
6287
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006288/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006289/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006290///
6291bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006292 const SCEV *&LHS, const SCEV *&RHS,
6293 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006294 bool Changed = false;
6295
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006296 // If we hit the max recursion limit bail out.
6297 if (Depth >= 3)
6298 return false;
6299
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006300 // Canonicalize a constant to the right side.
6301 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6302 // Check for both operands constant.
6303 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6304 if (ConstantExpr::getICmp(Pred,
6305 LHSC->getValue(),
6306 RHSC->getValue())->isNullValue())
6307 goto trivially_false;
6308 else
6309 goto trivially_true;
6310 }
6311 // Otherwise swap the operands to put the constant on the right.
6312 std::swap(LHS, RHS);
6313 Pred = ICmpInst::getSwappedPredicate(Pred);
6314 Changed = true;
6315 }
6316
6317 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006318 // addrec's loop, put the addrec on the left. Also make a dominance check,
6319 // as both operands could be addrecs loop-invariant in each other's loop.
6320 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6321 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006322 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006323 std::swap(LHS, RHS);
6324 Pred = ICmpInst::getSwappedPredicate(Pred);
6325 Changed = true;
6326 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006327 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006328
6329 // If there's a constant operand, canonicalize comparisons with boundary
6330 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6331 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6332 const APInt &RA = RC->getValue()->getValue();
6333 switch (Pred) {
6334 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6335 case ICmpInst::ICMP_EQ:
6336 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006337 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6338 if (!RA)
6339 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6340 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006341 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6342 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006343 RHS = AE->getOperand(1);
6344 LHS = ME->getOperand(1);
6345 Changed = true;
6346 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006347 break;
6348 case ICmpInst::ICMP_UGE:
6349 if ((RA - 1).isMinValue()) {
6350 Pred = ICmpInst::ICMP_NE;
6351 RHS = getConstant(RA - 1);
6352 Changed = true;
6353 break;
6354 }
6355 if (RA.isMaxValue()) {
6356 Pred = ICmpInst::ICMP_EQ;
6357 Changed = true;
6358 break;
6359 }
6360 if (RA.isMinValue()) goto trivially_true;
6361
6362 Pred = ICmpInst::ICMP_UGT;
6363 RHS = getConstant(RA - 1);
6364 Changed = true;
6365 break;
6366 case ICmpInst::ICMP_ULE:
6367 if ((RA + 1).isMaxValue()) {
6368 Pred = ICmpInst::ICMP_NE;
6369 RHS = getConstant(RA + 1);
6370 Changed = true;
6371 break;
6372 }
6373 if (RA.isMinValue()) {
6374 Pred = ICmpInst::ICMP_EQ;
6375 Changed = true;
6376 break;
6377 }
6378 if (RA.isMaxValue()) goto trivially_true;
6379
6380 Pred = ICmpInst::ICMP_ULT;
6381 RHS = getConstant(RA + 1);
6382 Changed = true;
6383 break;
6384 case ICmpInst::ICMP_SGE:
6385 if ((RA - 1).isMinSignedValue()) {
6386 Pred = ICmpInst::ICMP_NE;
6387 RHS = getConstant(RA - 1);
6388 Changed = true;
6389 break;
6390 }
6391 if (RA.isMaxSignedValue()) {
6392 Pred = ICmpInst::ICMP_EQ;
6393 Changed = true;
6394 break;
6395 }
6396 if (RA.isMinSignedValue()) goto trivially_true;
6397
6398 Pred = ICmpInst::ICMP_SGT;
6399 RHS = getConstant(RA - 1);
6400 Changed = true;
6401 break;
6402 case ICmpInst::ICMP_SLE:
6403 if ((RA + 1).isMaxSignedValue()) {
6404 Pred = ICmpInst::ICMP_NE;
6405 RHS = getConstant(RA + 1);
6406 Changed = true;
6407 break;
6408 }
6409 if (RA.isMinSignedValue()) {
6410 Pred = ICmpInst::ICMP_EQ;
6411 Changed = true;
6412 break;
6413 }
6414 if (RA.isMaxSignedValue()) goto trivially_true;
6415
6416 Pred = ICmpInst::ICMP_SLT;
6417 RHS = getConstant(RA + 1);
6418 Changed = true;
6419 break;
6420 case ICmpInst::ICMP_UGT:
6421 if (RA.isMinValue()) {
6422 Pred = ICmpInst::ICMP_NE;
6423 Changed = true;
6424 break;
6425 }
6426 if ((RA + 1).isMaxValue()) {
6427 Pred = ICmpInst::ICMP_EQ;
6428 RHS = getConstant(RA + 1);
6429 Changed = true;
6430 break;
6431 }
6432 if (RA.isMaxValue()) goto trivially_false;
6433 break;
6434 case ICmpInst::ICMP_ULT:
6435 if (RA.isMaxValue()) {
6436 Pred = ICmpInst::ICMP_NE;
6437 Changed = true;
6438 break;
6439 }
6440 if ((RA - 1).isMinValue()) {
6441 Pred = ICmpInst::ICMP_EQ;
6442 RHS = getConstant(RA - 1);
6443 Changed = true;
6444 break;
6445 }
6446 if (RA.isMinValue()) goto trivially_false;
6447 break;
6448 case ICmpInst::ICMP_SGT:
6449 if (RA.isMinSignedValue()) {
6450 Pred = ICmpInst::ICMP_NE;
6451 Changed = true;
6452 break;
6453 }
6454 if ((RA + 1).isMaxSignedValue()) {
6455 Pred = ICmpInst::ICMP_EQ;
6456 RHS = getConstant(RA + 1);
6457 Changed = true;
6458 break;
6459 }
6460 if (RA.isMaxSignedValue()) goto trivially_false;
6461 break;
6462 case ICmpInst::ICMP_SLT:
6463 if (RA.isMaxSignedValue()) {
6464 Pred = ICmpInst::ICMP_NE;
6465 Changed = true;
6466 break;
6467 }
6468 if ((RA - 1).isMinSignedValue()) {
6469 Pred = ICmpInst::ICMP_EQ;
6470 RHS = getConstant(RA - 1);
6471 Changed = true;
6472 break;
6473 }
6474 if (RA.isMinSignedValue()) goto trivially_false;
6475 break;
6476 }
6477 }
6478
6479 // Check for obvious equality.
6480 if (HasSameValue(LHS, RHS)) {
6481 if (ICmpInst::isTrueWhenEqual(Pred))
6482 goto trivially_true;
6483 if (ICmpInst::isFalseWhenEqual(Pred))
6484 goto trivially_false;
6485 }
6486
Dan Gohman81585c12010-05-03 16:35:17 +00006487 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6488 // adding or subtracting 1 from one of the operands.
6489 switch (Pred) {
6490 case ICmpInst::ICMP_SLE:
6491 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6492 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006493 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006494 Pred = ICmpInst::ICMP_SLT;
6495 Changed = true;
6496 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006497 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006498 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006499 Pred = ICmpInst::ICMP_SLT;
6500 Changed = true;
6501 }
6502 break;
6503 case ICmpInst::ICMP_SGE:
6504 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006505 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006506 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006507 Pred = ICmpInst::ICMP_SGT;
6508 Changed = true;
6509 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6510 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006511 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006512 Pred = ICmpInst::ICMP_SGT;
6513 Changed = true;
6514 }
6515 break;
6516 case ICmpInst::ICMP_ULE:
6517 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006518 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006519 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006520 Pred = ICmpInst::ICMP_ULT;
6521 Changed = true;
6522 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006523 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006524 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006525 Pred = ICmpInst::ICMP_ULT;
6526 Changed = true;
6527 }
6528 break;
6529 case ICmpInst::ICMP_UGE:
6530 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006531 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006532 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006533 Pred = ICmpInst::ICMP_UGT;
6534 Changed = true;
6535 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006536 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006537 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006538 Pred = ICmpInst::ICMP_UGT;
6539 Changed = true;
6540 }
6541 break;
6542 default:
6543 break;
6544 }
6545
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006546 // TODO: More simplifications are possible here.
6547
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006548 // Recursively simplify until we either hit a recursion limit or nothing
6549 // changes.
6550 if (Changed)
6551 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6552
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006553 return Changed;
6554
6555trivially_true:
6556 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006557 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006558 Pred = ICmpInst::ICMP_EQ;
6559 return true;
6560
6561trivially_false:
6562 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006563 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006564 Pred = ICmpInst::ICMP_NE;
6565 return true;
6566}
6567
Dan Gohmane65c9172009-07-13 21:35:55 +00006568bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6569 return getSignedRange(S).getSignedMax().isNegative();
6570}
6571
6572bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6573 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6574}
6575
6576bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6577 return !getSignedRange(S).getSignedMin().isNegative();
6578}
6579
6580bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6581 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6582}
6583
6584bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6585 return isKnownNegative(S) || isKnownPositive(S);
6586}
6587
6588bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6589 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00006590 // Canonicalize the inputs first.
6591 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6592
Dan Gohman07591692010-04-11 22:16:48 +00006593 // If LHS or RHS is an addrec, check to see if the condition is true in
6594 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00006595 // If LHS and RHS are both addrec, both conditions must be true in
6596 // every iteration of the loop.
6597 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6598 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6599 bool LeftGuarded = false;
6600 bool RightGuarded = false;
6601 if (LAR) {
6602 const Loop *L = LAR->getLoop();
6603 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6604 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6605 if (!RAR) return true;
6606 LeftGuarded = true;
6607 }
6608 }
6609 if (RAR) {
6610 const Loop *L = RAR->getLoop();
6611 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6612 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6613 if (!LAR) return true;
6614 RightGuarded = true;
6615 }
6616 }
6617 if (LeftGuarded && RightGuarded)
6618 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006619
Dan Gohman07591692010-04-11 22:16:48 +00006620 // Otherwise see what can be done with known constant ranges.
6621 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6622}
6623
6624bool
6625ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6626 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006627 if (HasSameValue(LHS, RHS))
6628 return ICmpInst::isTrueWhenEqual(Pred);
6629
Dan Gohman07591692010-04-11 22:16:48 +00006630 // This code is split out from isKnownPredicate because it is called from
6631 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00006632 switch (Pred) {
6633 default:
Dan Gohman8c129d72009-07-16 17:34:36 +00006634 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohmane65c9172009-07-13 21:35:55 +00006635 case ICmpInst::ICMP_SGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006636 std::swap(LHS, RHS);
6637 case ICmpInst::ICMP_SLT: {
6638 ConstantRange LHSRange = getSignedRange(LHS);
6639 ConstantRange RHSRange = getSignedRange(RHS);
6640 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6641 return true;
6642 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6643 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006644 break;
6645 }
6646 case ICmpInst::ICMP_SGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006647 std::swap(LHS, RHS);
6648 case ICmpInst::ICMP_SLE: {
6649 ConstantRange LHSRange = getSignedRange(LHS);
6650 ConstantRange RHSRange = getSignedRange(RHS);
6651 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6652 return true;
6653 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6654 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006655 break;
6656 }
6657 case ICmpInst::ICMP_UGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006658 std::swap(LHS, RHS);
6659 case ICmpInst::ICMP_ULT: {
6660 ConstantRange LHSRange = getUnsignedRange(LHS);
6661 ConstantRange RHSRange = getUnsignedRange(RHS);
6662 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6663 return true;
6664 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6665 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006666 break;
6667 }
6668 case ICmpInst::ICMP_UGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006669 std::swap(LHS, RHS);
6670 case ICmpInst::ICMP_ULE: {
6671 ConstantRange LHSRange = getUnsignedRange(LHS);
6672 ConstantRange RHSRange = getUnsignedRange(RHS);
6673 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6674 return true;
6675 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6676 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006677 break;
6678 }
6679 case ICmpInst::ICMP_NE: {
6680 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6681 return true;
6682 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6683 return true;
6684
6685 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6686 if (isKnownNonZero(Diff))
6687 return true;
6688 break;
6689 }
6690 case ICmpInst::ICMP_EQ:
Dan Gohman34392622009-07-20 23:54:43 +00006691 // The check at the top of the function catches the case where
6692 // the values are known to be equal.
Dan Gohmane65c9172009-07-13 21:35:55 +00006693 break;
6694 }
6695 return false;
6696}
6697
6698/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6699/// protected by a conditional between LHS and RHS. This is used to
6700/// to eliminate casts.
6701bool
6702ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6703 ICmpInst::Predicate Pred,
6704 const SCEV *LHS, const SCEV *RHS) {
6705 // Interpret a null as meaning no loop, where there is obviously no guard
6706 // (interprocedural conditions notwithstanding).
6707 if (!L) return true;
6708
Sanjoy Das1f05c512014-10-10 21:22:34 +00006709 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6710
Dan Gohmane65c9172009-07-13 21:35:55 +00006711 BasicBlock *Latch = L->getLoopLatch();
6712 if (!Latch)
6713 return false;
6714
6715 BranchInst *LoopContinuePredicate =
6716 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006717 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6718 isImpliedCond(Pred, LHS, RHS,
6719 LoopContinuePredicate->getCondition(),
6720 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6721 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006722
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006723 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth66b31302015-01-04 12:03:27 +00006724 for (auto &AssumeVH : AC->assumptions()) {
6725 if (!AssumeVH)
6726 continue;
6727 auto *CI = cast<CallInst>(AssumeVH);
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006728 if (!DT->dominates(CI, Latch->getTerminator()))
6729 continue;
6730
6731 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6732 return true;
6733 }
6734
6735 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006736}
6737
Dan Gohmanb50349a2010-04-11 19:27:13 +00006738/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00006739/// by a conditional between LHS and RHS. This is used to help avoid max
6740/// expressions in loop trip counts, and to eliminate casts.
6741bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00006742ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6743 ICmpInst::Predicate Pred,
6744 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00006745 // Interpret a null as meaning no loop, where there is obviously no guard
6746 // (interprocedural conditions notwithstanding).
6747 if (!L) return false;
6748
Sanjoy Das1f05c512014-10-10 21:22:34 +00006749 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6750
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006751 // Starting at the loop predecessor, climb up the predecessor chain, as long
6752 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00006753 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00006754 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006755 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00006756 Pair.first;
6757 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00006758
6759 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00006760 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00006761 if (!LoopEntryPredicate ||
6762 LoopEntryPredicate->isUnconditional())
6763 continue;
6764
Dan Gohmane18c2d62010-08-10 23:46:30 +00006765 if (isImpliedCond(Pred, LHS, RHS,
6766 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00006767 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00006768 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006769 }
6770
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006771 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth66b31302015-01-04 12:03:27 +00006772 for (auto &AssumeVH : AC->assumptions()) {
6773 if (!AssumeVH)
6774 continue;
6775 auto *CI = cast<CallInst>(AssumeVH);
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006776 if (!DT->dominates(CI, L->getHeader()))
6777 continue;
6778
6779 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6780 return true;
6781 }
6782
Dan Gohman2a62fd92008-08-12 20:17:31 +00006783 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006784}
6785
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006786/// RAII wrapper to prevent recursive application of isImpliedCond.
6787/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6788/// currently evaluating isImpliedCond.
6789struct MarkPendingLoopPredicate {
6790 Value *Cond;
6791 DenseSet<Value*> &LoopPreds;
6792 bool Pending;
6793
6794 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6795 : Cond(C), LoopPreds(LP) {
6796 Pending = !LoopPreds.insert(Cond).second;
6797 }
6798 ~MarkPendingLoopPredicate() {
6799 if (!Pending)
6800 LoopPreds.erase(Cond);
6801 }
6802};
6803
Dan Gohman430f0cc2009-07-21 23:03:19 +00006804/// isImpliedCond - Test whether the condition described by Pred, LHS,
6805/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006806bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006807 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00006808 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006809 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006810 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6811 if (Mark.Pending)
6812 return false;
6813
Dan Gohman8b0a4192010-03-01 17:49:51 +00006814 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006815 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006816 if (BO->getOpcode() == Instruction::And) {
6817 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006818 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6819 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006820 } else if (BO->getOpcode() == Instruction::Or) {
6821 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006822 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6823 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006824 }
6825 }
6826
Dan Gohmane18c2d62010-08-10 23:46:30 +00006827 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006828 if (!ICI) return false;
6829
Dan Gohmane65c9172009-07-13 21:35:55 +00006830 // Bail if the ICmp's operands' types are wider than the needed type
6831 // before attempting to call getSCEV on them. This avoids infinite
6832 // recursion, since the analysis of widening casts can require loop
6833 // exit condition information for overflow checking, which would
6834 // lead back here.
6835 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman430f0cc2009-07-21 23:03:19 +00006836 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohmane65c9172009-07-13 21:35:55 +00006837 return false;
6838
Andrew Trickfa594032012-11-29 18:35:13 +00006839 // Now that we found a conditional branch that dominates the loop or controls
6840 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00006841 ICmpInst::Predicate FoundPred;
6842 if (Inverse)
6843 FoundPred = ICI->getInversePredicate();
6844 else
6845 FoundPred = ICI->getPredicate();
6846
6847 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6848 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00006849
6850 // Balance the types. The case where FoundLHS' type is wider than
6851 // LHS' type is checked for above.
6852 if (getTypeSizeInBits(LHS->getType()) >
6853 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00006854 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006855 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6856 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6857 } else {
6858 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6859 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6860 }
6861 }
6862
Dan Gohman430f0cc2009-07-21 23:03:19 +00006863 // Canonicalize the query to match the way instcombine will have
6864 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00006865 if (SimplifyICmpOperands(Pred, LHS, RHS))
6866 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00006867 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00006868 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6869 if (FoundLHS == FoundRHS)
6870 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00006871
6872 // Check to see if we can make the LHS or RHS match.
6873 if (LHS == FoundRHS || RHS == FoundLHS) {
6874 if (isa<SCEVConstant>(RHS)) {
6875 std::swap(FoundLHS, FoundRHS);
6876 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6877 } else {
6878 std::swap(LHS, RHS);
6879 Pred = ICmpInst::getSwappedPredicate(Pred);
6880 }
6881 }
6882
6883 // Check whether the found predicate is the same as the desired predicate.
6884 if (FoundPred == Pred)
6885 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6886
6887 // Check whether swapping the found predicate makes it the same as the
6888 // desired predicate.
6889 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6890 if (isa<SCEVConstant>(RHS))
6891 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6892 else
6893 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6894 RHS, LHS, FoundLHS, FoundRHS);
6895 }
6896
Sanjoy Dasc5676df2014-11-13 00:00:58 +00006897 // Check if we can make progress by sharpening ranges.
6898 if (FoundPred == ICmpInst::ICMP_NE &&
6899 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
6900
6901 const SCEVConstant *C = nullptr;
6902 const SCEV *V = nullptr;
6903
6904 if (isa<SCEVConstant>(FoundLHS)) {
6905 C = cast<SCEVConstant>(FoundLHS);
6906 V = FoundRHS;
6907 } else {
6908 C = cast<SCEVConstant>(FoundRHS);
6909 V = FoundLHS;
6910 }
6911
6912 // The guarding predicate tells us that C != V. If the known range
6913 // of V is [C, t), we can sharpen the range to [C + 1, t). The
6914 // range we consider has to correspond to same signedness as the
6915 // predicate we're interested in folding.
6916
6917 APInt Min = ICmpInst::isSigned(Pred) ?
6918 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
6919
6920 if (Min == C->getValue()->getValue()) {
6921 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
6922 // This is true even if (Min + 1) wraps around -- in case of
6923 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
6924
6925 APInt SharperMin = Min + 1;
6926
6927 switch (Pred) {
6928 case ICmpInst::ICMP_SGE:
6929 case ICmpInst::ICMP_UGE:
6930 // We know V `Pred` SharperMin. If this implies LHS `Pred`
6931 // RHS, we're done.
6932 if (isImpliedCondOperands(Pred, LHS, RHS, V,
6933 getConstant(SharperMin)))
6934 return true;
6935
6936 case ICmpInst::ICMP_SGT:
6937 case ICmpInst::ICMP_UGT:
6938 // We know from the range information that (V `Pred` Min ||
6939 // V == Min). We know from the guarding condition that !(V
6940 // == Min). This gives us
6941 //
6942 // V `Pred` Min || V == Min && !(V == Min)
6943 // => V `Pred` Min
6944 //
6945 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
6946
6947 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
6948 return true;
6949
6950 default:
6951 // No change
6952 break;
6953 }
6954 }
6955 }
6956
Dan Gohman430f0cc2009-07-21 23:03:19 +00006957 // Check whether the actual condition is beyond sufficient.
6958 if (FoundPred == ICmpInst::ICMP_EQ)
6959 if (ICmpInst::isTrueWhenEqual(Pred))
6960 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6961 return true;
6962 if (Pred == ICmpInst::ICMP_NE)
6963 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6964 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6965 return true;
6966
6967 // Otherwise assume the worst.
6968 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006969}
6970
Dan Gohman430f0cc2009-07-21 23:03:19 +00006971/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00006972/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006973/// and FoundRHS is true.
6974bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6975 const SCEV *LHS, const SCEV *RHS,
6976 const SCEV *FoundLHS,
6977 const SCEV *FoundRHS) {
6978 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6979 FoundLHS, FoundRHS) ||
6980 // ~x < ~y --> x > y
6981 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6982 getNotSCEV(FoundRHS),
6983 getNotSCEV(FoundLHS));
6984}
6985
Sanjoy Das4555b6d2014-12-15 22:50:15 +00006986
6987/// If Expr computes ~A, return A else return nullptr
6988static const SCEV *MatchNotExpr(const SCEV *Expr) {
6989 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
6990 if (!Add || Add->getNumOperands() != 2) return nullptr;
6991
6992 const SCEVConstant *AddLHS = dyn_cast<SCEVConstant>(Add->getOperand(0));
6993 if (!(AddLHS && AddLHS->getValue()->getValue().isAllOnesValue()))
6994 return nullptr;
6995
6996 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
6997 if (!AddRHS || AddRHS->getNumOperands() != 2) return nullptr;
6998
6999 const SCEVConstant *MulLHS = dyn_cast<SCEVConstant>(AddRHS->getOperand(0));
7000 if (!(MulLHS && MulLHS->getValue()->getValue().isAllOnesValue()))
7001 return nullptr;
7002
7003 return AddRHS->getOperand(1);
7004}
7005
7006
7007/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7008template<typename MaxExprType>
7009static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7010 const SCEV *Candidate) {
7011 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7012 if (!MaxExpr) return false;
7013
7014 auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate);
7015 return It != MaxExpr->op_end();
7016}
7017
7018
7019/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7020template<typename MaxExprType>
7021static bool IsMinConsistingOf(ScalarEvolution &SE,
7022 const SCEV *MaybeMinExpr,
7023 const SCEV *Candidate) {
7024 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
7025 if (!MaybeMaxExpr)
7026 return false;
7027
7028 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
7029}
7030
7031
7032/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
7033/// expression?
7034static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
7035 ICmpInst::Predicate Pred,
7036 const SCEV *LHS, const SCEV *RHS) {
7037 switch (Pred) {
7038 default:
7039 return false;
7040
7041 case ICmpInst::ICMP_SGE:
7042 std::swap(LHS, RHS);
7043 // fall through
7044 case ICmpInst::ICMP_SLE:
7045 return
7046 // min(A, ...) <= A
7047 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
7048 // A <= max(A, ...)
7049 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
7050
7051 case ICmpInst::ICMP_UGE:
7052 std::swap(LHS, RHS);
7053 // fall through
7054 case ICmpInst::ICMP_ULE:
7055 return
7056 // min(A, ...) <= A
7057 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
7058 // A <= max(A, ...)
7059 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
7060 }
7061
7062 llvm_unreachable("covered switch fell through?!");
7063}
7064
Dan Gohman430f0cc2009-07-21 23:03:19 +00007065/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00007066/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007067/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00007068bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00007069ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
7070 const SCEV *LHS, const SCEV *RHS,
7071 const SCEV *FoundLHS,
7072 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007073 auto IsKnownPredicateFull =
7074 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7075 return isKnownPredicateWithRanges(Pred, LHS, RHS) ||
7076 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS);
7077 };
7078
Dan Gohmane65c9172009-07-13 21:35:55 +00007079 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00007080 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7081 case ICmpInst::ICMP_EQ:
7082 case ICmpInst::ICMP_NE:
7083 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
7084 return true;
7085 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00007086 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007087 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007088 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
7089 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007090 return true;
7091 break;
7092 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007093 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007094 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
7095 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007096 return true;
7097 break;
7098 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007099 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007100 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
7101 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007102 return true;
7103 break;
7104 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007105 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007106 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
7107 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007108 return true;
7109 break;
7110 }
7111
7112 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007113}
7114
Johannes Doerfert2683e562015-02-09 12:34:23 +00007115// Verify if an linear IV with positive stride can overflow when in a
7116// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007117// stride and the knowledge of NSW/NUW flags on the recurrence.
7118bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
7119 bool IsSigned, bool NoWrap) {
7120 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00007121
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007122 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7123 const SCEV *One = getConstant(Stride->getType(), 1);
Andrew Trick2afa3252011-03-09 17:29:58 +00007124
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007125 if (IsSigned) {
7126 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
7127 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
7128 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7129 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00007130
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007131 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
7132 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00007133 }
Dan Gohman01048422009-06-21 23:46:38 +00007134
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007135 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
7136 APInt MaxValue = APInt::getMaxValue(BitWidth);
7137 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7138 .getUnsignedMax();
7139
7140 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
7141 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
7142}
7143
Johannes Doerfert2683e562015-02-09 12:34:23 +00007144// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007145// greater-than comparison, knowing the invariant term of the comparison,
7146// the stride and the knowledge of NSW/NUW flags on the recurrence.
7147bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
7148 bool IsSigned, bool NoWrap) {
7149 if (NoWrap) return false;
7150
7151 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7152 const SCEV *One = getConstant(Stride->getType(), 1);
7153
7154 if (IsSigned) {
7155 APInt MinRHS = getSignedRange(RHS).getSignedMin();
7156 APInt MinValue = APInt::getSignedMinValue(BitWidth);
7157 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7158 .getSignedMax();
7159
7160 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
7161 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
7162 }
7163
7164 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
7165 APInt MinValue = APInt::getMinValue(BitWidth);
7166 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7167 .getUnsignedMax();
7168
7169 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
7170 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
7171}
7172
7173// Compute the backedge taken count knowing the interval difference, the
7174// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00007175const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007176 bool Equality) {
7177 const SCEV *One = getConstant(Step->getType(), 1);
7178 Delta = Equality ? getAddExpr(Delta, Step)
7179 : getAddExpr(Delta, getMinusSCEV(Step, One));
7180 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00007181}
7182
Chris Lattner587a75b2005-08-15 23:33:51 +00007183/// HowManyLessThans - Return the number of times a backedge containing the
7184/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00007185/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00007186///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007187/// @param ControlsExit is true when the LHS < RHS condition directly controls
7188/// the branch (loops exits only if condition is true). In this case, we can use
7189/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00007190ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00007191ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007192 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007193 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007194 // We handle only IV < Invariant
7195 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007196 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00007197
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007198 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00007199
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007200 // Avoid weird loops
7201 if (!IV || IV->getLoop() != L || !IV->isAffine())
7202 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00007203
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007204 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007205 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00007206
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007207 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00007208
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007209 // Avoid negative or zero stride values
7210 if (!isKnownPositive(Stride))
7211 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00007212
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007213 // Avoid proven overflow cases: this will ensure that the backedge taken count
7214 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00007215 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007216 // behaviors like the case of C language.
7217 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
7218 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00007219
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007220 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
7221 : ICmpInst::ICMP_ULT;
7222 const SCEV *Start = IV->getStart();
7223 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00007224 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
7225 const SCEV *Diff = getMinusSCEV(RHS, Start);
7226 // If we have NoWrap set, then we can assume that the increment won't
7227 // overflow, in which case if RHS - Start is a constant, we don't need to
7228 // do a max operation since we can just figure it out statically
7229 if (NoWrap && isa<SCEVConstant>(Diff)) {
7230 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7231 if (D.isNegative())
7232 End = Start;
7233 } else
7234 End = IsSigned ? getSMaxExpr(RHS, Start)
7235 : getUMaxExpr(RHS, Start);
7236 }
Dan Gohman51aaf022010-01-26 04:40:18 +00007237
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007238 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00007239
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007240 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
7241 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00007242
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007243 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7244 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00007245
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007246 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7247 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
7248 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00007249
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007250 // Although End can be a MAX expression we estimate MaxEnd considering only
7251 // the case End = RHS. This is safe because in the other case (End - Start)
7252 // is zero, leading to a zero maximum backedge taken count.
7253 APInt MaxEnd =
7254 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
7255 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
7256
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00007257 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007258 if (isa<SCEVConstant>(BECount))
7259 MaxBECount = BECount;
7260 else
7261 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
7262 getConstant(MinStride), false);
7263
7264 if (isa<SCEVCouldNotCompute>(MaxBECount))
7265 MaxBECount = BECount;
7266
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007267 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007268}
7269
7270ScalarEvolution::ExitLimit
7271ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
7272 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007273 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007274 // We handle only IV > Invariant
7275 if (!isLoopInvariant(RHS, L))
7276 return getCouldNotCompute();
7277
7278 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7279
7280 // Avoid weird loops
7281 if (!IV || IV->getLoop() != L || !IV->isAffine())
7282 return getCouldNotCompute();
7283
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007284 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007285 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7286
7287 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
7288
7289 // Avoid negative or zero stride values
7290 if (!isKnownPositive(Stride))
7291 return getCouldNotCompute();
7292
7293 // Avoid proven overflow cases: this will ensure that the backedge taken count
7294 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00007295 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007296 // behaviors like the case of C language.
7297 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7298 return getCouldNotCompute();
7299
7300 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7301 : ICmpInst::ICMP_UGT;
7302
7303 const SCEV *Start = IV->getStart();
7304 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00007305 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
7306 const SCEV *Diff = getMinusSCEV(RHS, Start);
7307 // If we have NoWrap set, then we can assume that the increment won't
7308 // overflow, in which case if RHS - Start is a constant, we don't need to
7309 // do a max operation since we can just figure it out statically
7310 if (NoWrap && isa<SCEVConstant>(Diff)) {
7311 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7312 if (!D.isNegative())
7313 End = Start;
7314 } else
7315 End = IsSigned ? getSMinExpr(RHS, Start)
7316 : getUMinExpr(RHS, Start);
7317 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007318
7319 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7320
7321 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7322 : getUnsignedRange(Start).getUnsignedMax();
7323
7324 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7325 : getUnsignedRange(Stride).getUnsignedMin();
7326
7327 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7328 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7329 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7330
7331 // Although End can be a MIN expression we estimate MinEnd considering only
7332 // the case End = RHS. This is safe because in the other case (Start - End)
7333 // is zero, leading to a zero maximum backedge taken count.
7334 APInt MinEnd =
7335 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7336 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7337
7338
7339 const SCEV *MaxBECount = getCouldNotCompute();
7340 if (isa<SCEVConstant>(BECount))
7341 MaxBECount = BECount;
7342 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00007343 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007344 getConstant(MinStride), false);
7345
7346 if (isa<SCEVCouldNotCompute>(MaxBECount))
7347 MaxBECount = BECount;
7348
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007349 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00007350}
7351
Chris Lattnerd934c702004-04-02 20:23:17 +00007352/// getNumIterationsInRange - Return the number of iterations of this loop that
7353/// produce values in the specified constant range. Another way of looking at
7354/// this is that it returns the first iteration number where the value is not in
7355/// the condition, thus computing the exit count. If the iteration count can't
7356/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007357const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00007358 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00007359 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00007360 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007361
7362 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00007363 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00007364 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007365 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00007366 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00007367 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00007368 getNoWrapFlags(FlagNW));
Dan Gohmana30370b2009-05-04 22:02:23 +00007369 if (const SCEVAddRecExpr *ShiftedAddRec =
7370 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00007371 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohmana37eaf22007-10-22 18:31:58 +00007372 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00007373 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00007374 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007375 }
7376
7377 // The only time we can solve this is when we have all constant indices.
7378 // Otherwise, we cannot determine the overflow conditions.
7379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7380 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman31efa302009-04-18 17:58:19 +00007381 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007382
7383
7384 // Okay at this point we know that all elements of the chrec are constants and
7385 // that the start element is zero.
7386
7387 // First check to see if the range contains zero. If not, the first
7388 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00007389 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00007390 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman1d2ded72010-05-03 22:09:21 +00007391 return SE.getConstant(getType(), 0);
Misha Brukman01808ca2005-04-21 21:13:18 +00007392
Chris Lattnerd934c702004-04-02 20:23:17 +00007393 if (isAffine()) {
7394 // If this is an affine expression then we have this situation:
7395 // Solve {0,+,A} in Range === Ax in Range
7396
Nick Lewycky52460262007-07-16 02:08:00 +00007397 // We know that zero is in the range. If A is positive then we know that
7398 // the upper value of the range must be the first possible exit value.
7399 // If A is negative then the lower of the range is the last possible loop
7400 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00007401 APInt One(BitWidth,1);
Nick Lewycky52460262007-07-16 02:08:00 +00007402 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7403 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00007404
Nick Lewycky52460262007-07-16 02:08:00 +00007405 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00007406 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00007407 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00007408
7409 // Evaluate at the exit value. If we really did fall out of the valid
7410 // range, then we computed our trip count, otherwise wrap around or other
7411 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00007412 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007413 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00007414 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007415
7416 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00007417 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00007418 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00007419 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00007420 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00007421 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00007422 } else if (isQuadratic()) {
7423 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7424 // quadratic equation to solve it. To do this, we must frame our problem in
7425 // terms of figuring out when zero is crossed, instead of when
7426 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00007427 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00007428 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00007429 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7430 // getNoWrapFlags(FlagNW)
7431 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00007432
7433 // Next, solve the constructed addrec
Dan Gohmanaf752342009-07-07 17:06:11 +00007434 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohmana37eaf22007-10-22 18:31:58 +00007435 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00007436 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7437 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00007438 if (R1) {
7439 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007440 if (ConstantInt *CB =
Owen Anderson487375e2009-07-29 18:55:55 +00007441 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Andersonf1f17432009-07-06 22:37:39 +00007442 R1->getValue(), R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007443 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00007444 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00007445
Chris Lattnerd934c702004-04-02 20:23:17 +00007446 // Make sure the root is not off by one. The returned iteration should
7447 // not be in the range, but the previous one should be. When solving
7448 // for "X*X < 5", for example, we should not return a root of 2.
7449 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00007450 R1->getValue(),
7451 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007452 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007453 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00007454 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007455 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman01808ca2005-04-21 21:13:18 +00007456
Dan Gohmana37eaf22007-10-22 18:31:58 +00007457 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007458 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00007459 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00007460 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007461 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007462
Chris Lattnerd934c702004-04-02 20:23:17 +00007463 // If R1 was not in the range, then it is a good return value. Make
7464 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00007465 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007466 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00007467 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007468 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00007469 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00007470 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007471 }
7472 }
7473 }
7474
Dan Gohman31efa302009-04-18 17:58:19 +00007475 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007476}
7477
Sebastian Pop448712b2014-05-07 18:01:20 +00007478namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007479struct FindUndefs {
7480 bool Found;
7481 FindUndefs() : Found(false) {}
7482
7483 bool follow(const SCEV *S) {
7484 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7485 if (isa<UndefValue>(C->getValue()))
7486 Found = true;
7487 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7488 if (isa<UndefValue>(C->getValue()))
7489 Found = true;
7490 }
7491
7492 // Keep looking if we haven't found it yet.
7493 return !Found;
7494 }
7495 bool isDone() const {
7496 // Stop recursion if we have found an undef.
7497 return Found;
7498 }
7499};
7500}
7501
7502// Return true when S contains at least an undef value.
7503static inline bool
7504containsUndefs(const SCEV *S) {
7505 FindUndefs F;
7506 SCEVTraversal<FindUndefs> ST(F);
7507 ST.visitAll(S);
7508
7509 return F.Found;
7510}
7511
7512namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00007513// Collect all steps of SCEV expressions.
7514struct SCEVCollectStrides {
7515 ScalarEvolution &SE;
7516 SmallVectorImpl<const SCEV *> &Strides;
7517
7518 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7519 : SE(SE), Strides(S) {}
7520
7521 bool follow(const SCEV *S) {
7522 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7523 Strides.push_back(AR->getStepRecurrence(SE));
7524 return true;
7525 }
7526 bool isDone() const { return false; }
7527};
7528
7529// Collect all SCEVUnknown and SCEVMulExpr expressions.
7530struct SCEVCollectTerms {
7531 SmallVectorImpl<const SCEV *> &Terms;
7532
7533 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7534 : Terms(T) {}
7535
7536 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007537 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007538 if (!containsUndefs(S))
7539 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00007540
7541 // Stop recursion: once we collected a term, do not walk its operands.
7542 return false;
7543 }
7544
7545 // Keep looking.
7546 return true;
7547 }
7548 bool isDone() const { return false; }
7549};
7550}
7551
7552/// Find parametric terms in this SCEVAddRecExpr.
7553void SCEVAddRecExpr::collectParametricTerms(
7554 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7555 SmallVector<const SCEV *, 4> Strides;
7556 SCEVCollectStrides StrideCollector(SE, Strides);
7557 visitAll(this, StrideCollector);
7558
7559 DEBUG({
7560 dbgs() << "Strides:\n";
7561 for (const SCEV *S : Strides)
7562 dbgs() << *S << "\n";
7563 });
7564
7565 for (const SCEV *S : Strides) {
7566 SCEVCollectTerms TermCollector(Terms);
7567 visitAll(S, TermCollector);
7568 }
7569
7570 DEBUG({
7571 dbgs() << "Terms:\n";
7572 for (const SCEV *T : Terms)
7573 dbgs() << *T << "\n";
7574 });
7575}
7576
Sebastian Popb1a548f2014-05-12 19:01:53 +00007577static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00007578 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00007579 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00007580 int Last = Terms.size() - 1;
7581 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00007582
Sebastian Pop448712b2014-05-07 18:01:20 +00007583 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00007584 if (Last == 0) {
7585 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007586 SmallVector<const SCEV *, 2> Qs;
7587 for (const SCEV *Op : M->operands())
7588 if (!isa<SCEVConstant>(Op))
7589 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00007590
Sebastian Pope30bd352014-05-27 22:41:56 +00007591 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00007592 }
7593
Sebastian Pope30bd352014-05-27 22:41:56 +00007594 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007595 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007596 }
7597
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007598 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007599 // Normalize the terms before the next call to findArrayDimensionsRec.
7600 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00007601 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007602
7603 // Bail out when GCD does not evenly divide one of the terms.
7604 if (!R->isZero())
7605 return false;
7606
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007607 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00007608 }
7609
Tobias Grosser3080cf12014-05-08 07:55:34 +00007610 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00007611 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7612 return isa<SCEVConstant>(E);
7613 }),
7614 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00007615
Sebastian Pop448712b2014-05-07 18:01:20 +00007616 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00007617 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7618 return false;
7619
Sebastian Pope30bd352014-05-27 22:41:56 +00007620 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007621 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00007622}
Sebastian Popc62c6792013-11-12 22:47:20 +00007623
Sebastian Pop448712b2014-05-07 18:01:20 +00007624namespace {
7625struct FindParameter {
7626 bool FoundParameter;
7627 FindParameter() : FoundParameter(false) {}
Sebastian Popc62c6792013-11-12 22:47:20 +00007628
Sebastian Pop448712b2014-05-07 18:01:20 +00007629 bool follow(const SCEV *S) {
7630 if (isa<SCEVUnknown>(S)) {
7631 FoundParameter = true;
7632 // Stop recursion: we found a parameter.
7633 return false;
7634 }
7635 // Keep looking.
7636 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007637 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007638 bool isDone() const {
7639 // Stop recursion if we have found a parameter.
7640 return FoundParameter;
Sebastian Popc62c6792013-11-12 22:47:20 +00007641 }
Sebastian Popc62c6792013-11-12 22:47:20 +00007642};
7643}
7644
Sebastian Pop448712b2014-05-07 18:01:20 +00007645// Returns true when S contains at least a SCEVUnknown parameter.
7646static inline bool
7647containsParameters(const SCEV *S) {
7648 FindParameter F;
7649 SCEVTraversal<FindParameter> ST(F);
7650 ST.visitAll(S);
7651
7652 return F.FoundParameter;
7653}
7654
7655// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7656static inline bool
7657containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7658 for (const SCEV *T : Terms)
7659 if (containsParameters(T))
7660 return true;
7661 return false;
7662}
7663
7664// Return the number of product terms in S.
7665static inline int numberOfTerms(const SCEV *S) {
7666 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7667 return Expr->getNumOperands();
7668 return 1;
7669}
7670
Sebastian Popa6e58602014-05-27 22:41:45 +00007671static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7672 if (isa<SCEVConstant>(T))
7673 return nullptr;
7674
7675 if (isa<SCEVUnknown>(T))
7676 return T;
7677
7678 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7679 SmallVector<const SCEV *, 2> Factors;
7680 for (const SCEV *Op : M->operands())
7681 if (!isa<SCEVConstant>(Op))
7682 Factors.push_back(Op);
7683
7684 return SE.getMulExpr(Factors);
7685 }
7686
7687 return T;
7688}
7689
7690/// Return the size of an element read or written by Inst.
7691const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7692 Type *Ty;
7693 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7694 Ty = Store->getValueOperand()->getType();
7695 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00007696 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00007697 else
7698 return nullptr;
7699
7700 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7701 return getSizeOfExpr(ETy, Ty);
7702}
7703
Sebastian Pop448712b2014-05-07 18:01:20 +00007704/// Second step of delinearization: compute the array dimensions Sizes from the
7705/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00007706void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7707 SmallVectorImpl<const SCEV *> &Sizes,
7708 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007709
Sebastian Pop53524082014-05-29 19:44:05 +00007710 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00007711 return;
7712
7713 // Early return when Terms do not contain parameters: we do not delinearize
7714 // non parametric SCEVs.
7715 if (!containsParameters(Terms))
7716 return;
7717
7718 DEBUG({
7719 dbgs() << "Terms:\n";
7720 for (const SCEV *T : Terms)
7721 dbgs() << *T << "\n";
7722 });
7723
7724 // Remove duplicates.
7725 std::sort(Terms.begin(), Terms.end());
7726 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7727
7728 // Put larger terms first.
7729 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7730 return numberOfTerms(LHS) > numberOfTerms(RHS);
7731 });
7732
Sebastian Popa6e58602014-05-27 22:41:45 +00007733 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7734
7735 // Divide all terms by the element size.
7736 for (const SCEV *&Term : Terms) {
7737 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00007738 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Sebastian Popa6e58602014-05-27 22:41:45 +00007739 Term = Q;
7740 }
7741
7742 SmallVector<const SCEV *, 4> NewTerms;
7743
7744 // Remove constant factors.
7745 for (const SCEV *T : Terms)
7746 if (const SCEV *NewT = removeConstantFactors(SE, T))
7747 NewTerms.push_back(NewT);
7748
Sebastian Pop448712b2014-05-07 18:01:20 +00007749 DEBUG({
7750 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00007751 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00007752 dbgs() << *T << "\n";
7753 });
7754
Sebastian Popa6e58602014-05-27 22:41:45 +00007755 if (NewTerms.empty() ||
7756 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00007757 Sizes.clear();
7758 return;
7759 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007760
Sebastian Popa6e58602014-05-27 22:41:45 +00007761 // The last element to be pushed into Sizes is the size of an element.
7762 Sizes.push_back(ElementSize);
7763
Sebastian Pop448712b2014-05-07 18:01:20 +00007764 DEBUG({
7765 dbgs() << "Sizes:\n";
7766 for (const SCEV *S : Sizes)
7767 dbgs() << *S << "\n";
7768 });
7769}
7770
7771/// Third step of delinearization: compute the access functions for the
7772/// Subscripts based on the dimensions in Sizes.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007773void SCEVAddRecExpr::computeAccessFunctions(
Sebastian Pop448712b2014-05-07 18:01:20 +00007774 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7775 SmallVectorImpl<const SCEV *> &Sizes) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007776
Sebastian Popb1a548f2014-05-12 19:01:53 +00007777 // Early exit in case this SCEV is not an affine multivariate function.
7778 if (Sizes.empty() || !this->isAffine())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007779 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007780
Sebastian Pop28e6b972014-05-27 22:41:51 +00007781 const SCEV *Res = this;
Sebastian Pop448712b2014-05-07 18:01:20 +00007782 int Last = Sizes.size() - 1;
7783 for (int i = Last; i >= 0; i--) {
7784 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00007785 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00007786
7787 DEBUG({
7788 dbgs() << "Res: " << *Res << "\n";
7789 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7790 dbgs() << "Res divided by Sizes[i]:\n";
7791 dbgs() << "Quotient: " << *Q << "\n";
7792 dbgs() << "Remainder: " << *R << "\n";
7793 });
7794
7795 Res = Q;
7796
Sebastian Popa6e58602014-05-27 22:41:45 +00007797 // Do not record the last subscript corresponding to the size of elements in
7798 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00007799 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007800
7801 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007802 if (isa<SCEVAddRecExpr>(R)) {
7803 Subscripts.clear();
7804 Sizes.clear();
7805 return;
7806 }
Sebastian Popa6e58602014-05-27 22:41:45 +00007807
Sebastian Pop448712b2014-05-07 18:01:20 +00007808 continue;
7809 }
7810
7811 // Record the access function for the current subscript.
7812 Subscripts.push_back(R);
7813 }
7814
7815 // Also push in last position the remainder of the last division: it will be
7816 // the access function of the innermost dimension.
7817 Subscripts.push_back(Res);
7818
7819 std::reverse(Subscripts.begin(), Subscripts.end());
7820
7821 DEBUG({
7822 dbgs() << "Subscripts:\n";
7823 for (const SCEV *S : Subscripts)
7824 dbgs() << *S << "\n";
7825 });
Sebastian Pop448712b2014-05-07 18:01:20 +00007826}
7827
Sebastian Popc62c6792013-11-12 22:47:20 +00007828/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7829/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00007830/// is the offset start of the array. The SCEV->delinearize algorithm computes
7831/// the multiples of SCEV coefficients: that is a pattern matching of sub
7832/// expressions in the stride and base of a SCEV corresponding to the
7833/// computation of a GCD (greatest common divisor) of base and stride. When
7834/// SCEV->delinearize fails, it returns the SCEV unchanged.
7835///
7836/// For example: when analyzing the memory access A[i][j][k] in this loop nest
7837///
7838/// void foo(long n, long m, long o, double A[n][m][o]) {
7839///
7840/// for (long i = 0; i < n; i++)
7841/// for (long j = 0; j < m; j++)
7842/// for (long k = 0; k < o; k++)
7843/// A[i][j][k] = 1.0;
7844/// }
7845///
7846/// the delinearization input is the following AddRec SCEV:
7847///
7848/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7849///
7850/// From this SCEV, we are able to say that the base offset of the access is %A
7851/// because it appears as an offset that does not divide any of the strides in
7852/// the loops:
7853///
7854/// CHECK: Base offset: %A
7855///
7856/// and then SCEV->delinearize determines the size of some of the dimensions of
7857/// the array as these are the multiples by which the strides are happening:
7858///
7859/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7860///
7861/// Note that the outermost dimension remains of UnknownSize because there are
7862/// no strides that would help identifying the size of the last dimension: when
7863/// the array has been statically allocated, one could compute the size of that
7864/// dimension by dividing the overall size of the array by the size of the known
7865/// dimensions: %m * %o * 8.
7866///
7867/// Finally delinearize provides the access functions for the array reference
7868/// that does correspond to A[i][j][k] of the above C testcase:
7869///
7870/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7871///
7872/// The testcases are checking the output of a function pass:
7873/// DelinearizationPass that walks through all loads and stores of a function
7874/// asking for the SCEV of the memory access with respect to all enclosing
7875/// loops, calling SCEV->delinearize on that and printing the results.
7876
Sebastian Pop28e6b972014-05-27 22:41:51 +00007877void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7878 SmallVectorImpl<const SCEV *> &Subscripts,
7879 SmallVectorImpl<const SCEV *> &Sizes,
7880 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007881 // First step: collect parametric terms.
7882 SmallVector<const SCEV *, 4> Terms;
7883 collectParametricTerms(SE, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00007884
Sebastian Popb1a548f2014-05-12 19:01:53 +00007885 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007886 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007887
Sebastian Pop448712b2014-05-07 18:01:20 +00007888 // Second step: find subscript sizes.
Sebastian Popa6e58602014-05-27 22:41:45 +00007889 SE.findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00007890
Sebastian Popb1a548f2014-05-12 19:01:53 +00007891 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007892 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007893
Sebastian Pop448712b2014-05-07 18:01:20 +00007894 // Third step: compute the access functions for each subscript.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007895 computeAccessFunctions(SE, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00007896
Sebastian Pop28e6b972014-05-27 22:41:51 +00007897 if (Subscripts.empty())
7898 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007899
Sebastian Pop448712b2014-05-07 18:01:20 +00007900 DEBUG({
7901 dbgs() << "succeeded to delinearize " << *this << "\n";
7902 dbgs() << "ArrayDecl[UnknownSize]";
7903 for (const SCEV *S : Sizes)
7904 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00007905
Sebastian Pop444621a2014-05-09 22:45:02 +00007906 dbgs() << "\nArrayRef";
7907 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00007908 dbgs() << "[" << *S << "]";
7909 dbgs() << "\n";
7910 });
Sebastian Popc62c6792013-11-12 22:47:20 +00007911}
Chris Lattnerd934c702004-04-02 20:23:17 +00007912
7913//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00007914// SCEVCallbackVH Class Implementation
7915//===----------------------------------------------------------------------===//
7916
Dan Gohmand33a0902009-05-19 19:22:47 +00007917void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00007918 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00007919 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7920 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007921 SE->ValueExprMap.erase(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00007922 // this now dangles!
7923}
7924
Dan Gohman7a066722010-07-28 01:09:07 +00007925void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00007926 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00007927
Dan Gohman48f82222009-05-04 22:30:44 +00007928 // Forget all the expressions associated with users of the old value,
7929 // so that future queries will recompute the expressions using the new
7930 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00007931 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007932 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00007933 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00007934 while (!Worklist.empty()) {
7935 User *U = Worklist.pop_back_val();
7936 // Deleting the Old value will cause this to dangle. Postpone
7937 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007938 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00007939 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00007940 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00007941 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00007942 if (PHINode *PN = dyn_cast<PHINode>(U))
7943 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007944 SE->ValueExprMap.erase(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00007945 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00007946 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007947 // Delete the Old value.
7948 if (PHINode *PN = dyn_cast<PHINode>(Old))
7949 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007950 SE->ValueExprMap.erase(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007951 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00007952}
7953
Dan Gohmand33a0902009-05-19 19:22:47 +00007954ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00007955 : CallbackVH(V), SE(se) {}
7956
7957//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00007958// ScalarEvolution Class Implementation
7959//===----------------------------------------------------------------------===//
7960
Dan Gohmanc8e23622009-04-21 23:15:49 +00007961ScalarEvolution::ScalarEvolution()
Craig Topper9f008862014-04-15 04:59:12 +00007962 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7963 BlockDispositions(64), FirstUnknown(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +00007964 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanc8e23622009-04-21 23:15:49 +00007965}
7966
Chris Lattnerd934c702004-04-02 20:23:17 +00007967bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007968 this->F = &F;
Chandler Carruth66b31302015-01-04 12:03:27 +00007969 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth4f8f3072015-01-17 14:16:18 +00007970 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Rafael Espindola93512512014-02-25 17:30:31 +00007971 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00007972 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chandler Carruthb98f63d2015-01-15 10:41:28 +00007973 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00007974 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerd934c702004-04-02 20:23:17 +00007975 return false;
7976}
7977
7978void ScalarEvolution::releaseMemory() {
Dan Gohman7cac9572010-08-02 23:49:30 +00007979 // Iterate through all the SCEVUnknown instances and call their
7980 // destructors, so that they release their references to their values.
7981 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7982 U->~SCEVUnknown();
Craig Topper9f008862014-04-15 04:59:12 +00007983 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00007984
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007985 ValueExprMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00007986
7987 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7988 // that a loop had multiple computable exits.
7989 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7990 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7991 I != E; ++I) {
7992 I->second.clear();
7993 }
7994
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007995 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7996
Dan Gohmanc8e23622009-04-21 23:15:49 +00007997 BackedgeTakenCounts.clear();
7998 ConstantEvolutionLoopExitValue.clear();
Dan Gohman5122d612009-05-08 20:47:27 +00007999 ValuesAtScopes.clear();
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008000 LoopDispositions.clear();
Dan Gohman8ea83d82010-11-18 00:34:22 +00008001 BlockDispositions.clear();
Dan Gohman761065e2010-11-17 02:44:44 +00008002 UnsignedRanges.clear();
8003 SignedRanges.clear();
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008004 UniqueSCEVs.clear();
8005 SCEVAllocator.Reset();
Chris Lattnerd934c702004-04-02 20:23:17 +00008006}
8007
8008void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
8009 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00008010 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00008011 AU.addRequiredTransitive<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +00008012 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00008013 AU.addRequired<TargetLibraryInfoWrapperPass>();
Dan Gohman0a40ad92009-04-16 03:18:22 +00008014}
8015
Dan Gohmanc8e23622009-04-21 23:15:49 +00008016bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00008017 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00008018}
8019
Dan Gohmanc8e23622009-04-21 23:15:49 +00008020static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00008021 const Loop *L) {
8022 // Print all inner loops first
8023 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
8024 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00008025
Dan Gohmanbc694912010-01-09 18:17:45 +00008026 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008027 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008028 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00008029
Dan Gohmancb0efec2009-12-18 01:14:11 +00008030 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00008031 L->getExitBlocks(ExitBlocks);
8032 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00008033 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00008034
Dan Gohman0bddac12009-02-24 18:55:53 +00008035 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
8036 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00008037 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00008038 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00008039 }
8040
Dan Gohmanbc694912010-01-09 18:17:45 +00008041 OS << "\n"
8042 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008043 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008044 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00008045
8046 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
8047 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
8048 } else {
8049 OS << "Unpredictable max backedge-taken count. ";
8050 }
8051
8052 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00008053}
8054
Dan Gohmancb0efec2009-12-18 01:14:11 +00008055void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00008056 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00008057 // out SCEV values of all instructions that are interesting. Doing
8058 // this potentially causes it to create new SCEV objects though,
8059 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00008060 // observable from outside the class though, so casting away the
8061 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00008062 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00008063
Dan Gohmanbc694912010-01-09 18:17:45 +00008064 OS << "Classifying expressions for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008065 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008066 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00008067 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand18dc2c2010-05-03 17:03:23 +00008068 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanfda3c4a2009-07-13 23:03:05 +00008069 OS << *I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00008070 OS << " --> ";
Dan Gohmanaf752342009-07-07 17:06:11 +00008071 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00008072 SV->print(OS);
Misha Brukman01808ca2005-04-21 21:13:18 +00008073
Dan Gohmanb9063a82009-06-19 17:49:54 +00008074 const Loop *L = LI->getLoopFor((*I).getParent());
8075
Dan Gohmanaf752342009-07-07 17:06:11 +00008076 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00008077 if (AtUse != SV) {
8078 OS << " --> ";
8079 AtUse->print(OS);
8080 }
8081
8082 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00008083 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00008084 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00008085 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008086 OS << "<<Unknown>>";
8087 } else {
8088 OS << *ExitValue;
8089 }
8090 }
8091
Chris Lattnerd934c702004-04-02 20:23:17 +00008092 OS << "\n";
8093 }
8094
Dan Gohmanbc694912010-01-09 18:17:45 +00008095 OS << "Determining loop execution counts for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008096 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008097 OS << "\n";
Dan Gohmanc8e23622009-04-21 23:15:49 +00008098 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
8099 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00008100}
Dan Gohmane20f8242009-04-21 00:47:46 +00008101
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008102ScalarEvolution::LoopDisposition
8103ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008104 auto &Values = LoopDispositions[S];
8105 for (auto &V : Values) {
8106 if (V.getPointer() == L)
8107 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00008108 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008109 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008110 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008111 auto &Values2 = LoopDispositions[S];
8112 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
8113 if (V.getPointer() == L) {
8114 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00008115 break;
8116 }
8117 }
8118 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008119}
8120
8121ScalarEvolution::LoopDisposition
8122ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00008123 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00008124 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008125 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008126 case scTruncate:
8127 case scZeroExtend:
8128 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008129 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00008130 case scAddRecExpr: {
8131 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8132
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008133 // If L is the addrec's loop, it's computable.
8134 if (AR->getLoop() == L)
8135 return LoopComputable;
8136
Dan Gohmanafd6db92010-11-17 21:23:15 +00008137 // Add recurrences are never invariant in the function-body (null loop).
8138 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008139 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008140
8141 // This recurrence is variant w.r.t. L if L contains AR's loop.
8142 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008143 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008144
8145 // This recurrence is invariant w.r.t. L if AR's loop contains L.
8146 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008147 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008148
8149 // This recurrence is variant w.r.t. L if any of its operands
8150 // are variant.
8151 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
8152 I != E; ++I)
8153 if (!isLoopInvariant(*I, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008154 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008155
8156 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008157 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008158 }
8159 case scAddExpr:
8160 case scMulExpr:
8161 case scUMaxExpr:
8162 case scSMaxExpr: {
8163 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohmanafd6db92010-11-17 21:23:15 +00008164 bool HasVarying = false;
8165 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8166 I != E; ++I) {
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008167 LoopDisposition D = getLoopDisposition(*I, L);
8168 if (D == LoopVariant)
8169 return LoopVariant;
8170 if (D == LoopComputable)
8171 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008172 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008173 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008174 }
8175 case scUDivExpr: {
8176 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008177 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
8178 if (LD == LoopVariant)
8179 return LoopVariant;
8180 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
8181 if (RD == LoopVariant)
8182 return LoopVariant;
8183 return (LD == LoopInvariant && RD == LoopInvariant) ?
8184 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008185 }
8186 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008187 // All non-instruction values are loop invariant. All instructions are loop
8188 // invariant if they are not contained in the specified loop.
8189 // Instructions are never considered invariant in the function body
8190 // (null loop) because they are defined within the "loop".
8191 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
8192 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
8193 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008194 case scCouldNotCompute:
8195 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00008196 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00008197 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00008198}
8199
8200bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
8201 return getLoopDisposition(S, L) == LoopInvariant;
8202}
8203
8204bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
8205 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00008206}
Dan Gohman20d9ce22010-11-17 21:41:58 +00008207
Dan Gohman8ea83d82010-11-18 00:34:22 +00008208ScalarEvolution::BlockDisposition
8209ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008210 auto &Values = BlockDispositions[S];
8211 for (auto &V : Values) {
8212 if (V.getPointer() == BB)
8213 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00008214 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008215 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008216 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00008217 auto &Values2 = BlockDispositions[S];
8218 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
8219 if (V.getPointer() == BB) {
8220 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00008221 break;
8222 }
8223 }
8224 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008225}
8226
Dan Gohman8ea83d82010-11-18 00:34:22 +00008227ScalarEvolution::BlockDisposition
8228ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00008229 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00008230 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00008231 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008232 case scTruncate:
8233 case scZeroExtend:
8234 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00008235 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00008236 case scAddRecExpr: {
8237 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00008238 // to test for proper dominance too, because the instruction which
8239 // produces the addrec's value is a PHI, and a PHI effectively properly
8240 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00008241 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8242 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00008243 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008244 }
8245 // FALL THROUGH into SCEVNAryExpr handling.
8246 case scAddExpr:
8247 case scMulExpr:
8248 case scUMaxExpr:
8249 case scSMaxExpr: {
8250 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008251 bool Proper = true;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008252 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman8ea83d82010-11-18 00:34:22 +00008253 I != E; ++I) {
8254 BlockDisposition D = getBlockDisposition(*I, BB);
8255 if (D == DoesNotDominateBlock)
8256 return DoesNotDominateBlock;
8257 if (D == DominatesBlock)
8258 Proper = false;
8259 }
8260 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008261 }
8262 case scUDivExpr: {
8263 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008264 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
8265 BlockDisposition LD = getBlockDisposition(LHS, BB);
8266 if (LD == DoesNotDominateBlock)
8267 return DoesNotDominateBlock;
8268 BlockDisposition RD = getBlockDisposition(RHS, BB);
8269 if (RD == DoesNotDominateBlock)
8270 return DoesNotDominateBlock;
8271 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
8272 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008273 }
8274 case scUnknown:
8275 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00008276 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
8277 if (I->getParent() == BB)
8278 return DominatesBlock;
8279 if (DT->properlyDominates(I->getParent(), BB))
8280 return ProperlyDominatesBlock;
8281 return DoesNotDominateBlock;
8282 }
8283 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008284 case scCouldNotCompute:
8285 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00008286 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00008287 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00008288}
8289
8290bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
8291 return getBlockDisposition(S, BB) >= DominatesBlock;
8292}
8293
8294bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
8295 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00008296}
Dan Gohman534749b2010-11-17 22:27:42 +00008297
Andrew Trick365e31c2012-07-13 23:33:03 +00008298namespace {
8299// Search for a SCEV expression node within an expression tree.
8300// Implements SCEVTraversal::Visitor.
8301struct SCEVSearch {
8302 const SCEV *Node;
8303 bool IsFound;
8304
8305 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8306
8307 bool follow(const SCEV *S) {
8308 IsFound |= (S == Node);
8309 return !IsFound;
8310 }
8311 bool isDone() const { return IsFound; }
8312};
8313}
8314
Dan Gohman534749b2010-11-17 22:27:42 +00008315bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Andrew Trick365e31c2012-07-13 23:33:03 +00008316 SCEVSearch Search(Op);
8317 visitAll(S, Search);
8318 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00008319}
Dan Gohman7e6b3932010-11-17 23:28:48 +00008320
8321void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8322 ValuesAtScopes.erase(S);
8323 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008324 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00008325 UnsignedRanges.erase(S);
8326 SignedRanges.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00008327
8328 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8329 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8330 BackedgeTakenInfo &BEInfo = I->second;
8331 if (BEInfo.hasOperand(S, this)) {
8332 BEInfo.clear();
8333 BackedgeTakenCounts.erase(I++);
8334 }
8335 else
8336 ++I;
8337 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00008338}
Benjamin Kramer214935e2012-10-26 17:31:32 +00008339
8340typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008341
Alp Tokercb402912014-01-24 17:20:08 +00008342/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008343static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8344 size_t Pos = 0;
8345 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8346 Str.replace(Pos, From.size(), To.data(), To.size());
8347 Pos += To.size();
8348 }
8349}
8350
Benjamin Kramer214935e2012-10-26 17:31:32 +00008351/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8352static void
8353getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8354 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8355 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8356
8357 std::string &S = Map[L];
8358 if (S.empty()) {
8359 raw_string_ostream OS(S);
8360 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008361
8362 // false and 0 are semantically equivalent. This can happen in dead loops.
8363 replaceSubString(OS.str(), "false", "0");
8364 // Remove wrap flags, their use in SCEV is highly fragile.
8365 // FIXME: Remove this when SCEV gets smarter about them.
8366 replaceSubString(OS.str(), "<nw>", "");
8367 replaceSubString(OS.str(), "<nsw>", "");
8368 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00008369 }
8370 }
8371}
8372
8373void ScalarEvolution::verifyAnalysis() const {
8374 if (!VerifySCEV)
8375 return;
8376
8377 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8378
8379 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8380 // FIXME: It would be much better to store actual values instead of strings,
8381 // but SCEV pointers will change if we drop the caches.
8382 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8383 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8384 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8385
8386 // Gather stringified backedge taken counts for all loops without using
8387 // SCEV's caches.
8388 SE.releaseMemory();
8389 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8390 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8391
8392 // Now compare whether they're the same with and without caches. This allows
8393 // verifying that no pass changed the cache.
8394 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8395 "New loops suddenly appeared!");
8396
8397 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8398 OldE = BackedgeDumpsOld.end(),
8399 NewI = BackedgeDumpsNew.begin();
8400 OldI != OldE; ++OldI, ++NewI) {
8401 assert(OldI->first == NewI->first && "Loop order changed!");
8402
8403 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8404 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008405 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00008406 // means that a pass is buggy or SCEV has to learn a new pattern but is
8407 // usually not harmful.
8408 if (OldI->second != NewI->second &&
8409 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008410 NewI->second.find("undef") == std::string::npos &&
8411 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00008412 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008413 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00008414 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008415 << "' changed from '" << OldI->second
8416 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00008417 std::abort();
8418 }
8419 }
8420
8421 // TODO: Verify more things.
8422}