blob: f61fa09a56e54145e047bffd66c59a142f1e48a1 [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"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000086#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000087#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000088#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000089#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000090#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000091#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000092#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000093#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000094using namespace llvm;
95
Chandler Carruthf1221bd2014-04-22 02:48:03 +000096#define DEBUG_TYPE "scalar-evolution"
97
Chris Lattner57ef9422006-12-19 22:30:33 +000098STATISTIC(NumArrayLenItCounts,
99 "Number of trip counts computed with array length");
100STATISTIC(NumTripCountsComputed,
101 "Number of loops with predictable loop counts");
102STATISTIC(NumTripCountsNotComputed,
103 "Number of loops without predictable loop counts");
104STATISTIC(NumBruteForceTripCountsComputed,
105 "Number of loops with trip counts computed by force");
106
Dan Gohmand78c4002008-05-13 00:00:25 +0000107static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000108MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
109 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000110 "symbolically execute a constant "
111 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000112 cl::init(100));
113
Benjamin Kramer214935e2012-10-26 17:31:32 +0000114// FIXME: Enable this with XDEBUG when the test suite is clean.
115static cl::opt<bool>
116VerifySCEV("verify-scev",
117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000118static cl::opt<bool>
119 VerifySCEVMap("verify-scev-maps",
120 cl::desc("Verify no dangling value in ScalarEvolution's"
121 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000122
Chris Lattnerd934c702004-04-02 20:23:17 +0000123//===----------------------------------------------------------------------===//
124// SCEV class definitions
125//===----------------------------------------------------------------------===//
126
127//===----------------------------------------------------------------------===//
128// Implementation of the SCEV class.
129//
Dan Gohman3423e722009-06-30 20:13:32 +0000130
Davide Italiano2071f4c2015-10-25 19:55:24 +0000131LLVM_DUMP_METHOD
132void SCEV::dump() const {
133 print(dbgs());
134 dbgs() << '\n';
135}
136
Dan Gohman534749b2010-11-17 22:27:42 +0000137void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000138 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000139 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000141 return;
142 case scTruncate: {
143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
144 const SCEV *Op = Trunc->getOperand();
145 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
146 << *Trunc->getType() << ")";
147 return;
148 }
149 case scZeroExtend: {
150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
151 const SCEV *Op = ZExt->getOperand();
152 OS << "(zext " << *Op->getType() << " " << *Op << " to "
153 << *ZExt->getType() << ")";
154 return;
155 }
156 case scSignExtend: {
157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
158 const SCEV *Op = SExt->getOperand();
159 OS << "(sext " << *Op->getType() << " " << *Op << " to "
160 << *SExt->getType() << ")";
161 return;
162 }
163 case scAddRecExpr: {
164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
165 OS << "{" << *AR->getOperand(0);
166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
167 OS << ",+," << *AR->getOperand(i);
168 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000169 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000170 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000171 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000172 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000173 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
175 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000177 OS << ">";
178 return;
179 }
180 case scAddExpr:
181 case scMulExpr:
182 case scUMaxExpr:
183 case scSMaxExpr: {
184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000185 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000186 switch (NAry->getSCEVType()) {
187 case scAddExpr: OpStr = " + "; break;
188 case scMulExpr: OpStr = " * "; break;
189 case scUMaxExpr: OpStr = " umax "; break;
190 case scSMaxExpr: OpStr = " smax "; break;
191 }
192 OS << "(";
193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
194 I != E; ++I) {
195 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000196 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000197 OS << OpStr;
198 }
199 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000200 switch (NAry->getSCEVType()) {
201 case scAddExpr:
202 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000203 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000204 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000205 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000206 OS << "<nsw>";
207 }
Dan Gohman534749b2010-11-17 22:27:42 +0000208 return;
209 }
210 case scUDivExpr: {
211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
213 return;
214 }
215 case scUnknown: {
216 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000217 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000218 if (U->isSizeOf(AllocTy)) {
219 OS << "sizeof(" << *AllocTy << ")";
220 return;
221 }
222 if (U->isAlignOf(AllocTy)) {
223 OS << "alignof(" << *AllocTy << ")";
224 return;
225 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000228 Constant *FieldNo;
229 if (U->isOffsetOf(CTy, FieldNo)) {
230 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000231 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000232 OS << ")";
233 return;
234 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000235
Dan Gohman534749b2010-11-17 22:27:42 +0000236 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000237 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000238 return;
239 }
240 case scCouldNotCompute:
241 OS << "***COULDNOTCOMPUTE***";
242 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000243 }
244 llvm_unreachable("Unknown SCEV kind!");
245}
246
Chris Lattner229907c2011-07-18 04:54:35 +0000247Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000248 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000249 case scConstant:
250 return cast<SCEVConstant>(this)->getType();
251 case scTruncate:
252 case scZeroExtend:
253 case scSignExtend:
254 return cast<SCEVCastExpr>(this)->getType();
255 case scAddRecExpr:
256 case scMulExpr:
257 case scUMaxExpr:
258 case scSMaxExpr:
259 return cast<SCEVNAryExpr>(this)->getType();
260 case scAddExpr:
261 return cast<SCEVAddExpr>(this)->getType();
262 case scUDivExpr:
263 return cast<SCEVUDivExpr>(this)->getType();
264 case scUnknown:
265 return cast<SCEVUnknown>(this)->getType();
266 case scCouldNotCompute:
267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000268 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000269 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000270}
271
Dan Gohmanbe928e32008-06-18 16:23:07 +0000272bool SCEV::isZero() const {
273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
274 return SC->getValue()->isZero();
275 return false;
276}
277
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000278bool SCEV::isOne() const {
279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280 return SC->getValue()->isOne();
281 return false;
282}
Chris Lattnerd934c702004-04-02 20:23:17 +0000283
Dan Gohman18a96bb2009-06-24 00:30:26 +0000284bool SCEV::isAllOnesValue() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isAllOnesValue();
287 return false;
288}
289
Andrew Trick881a7762012-01-07 00:27:31 +0000290/// isNonConstantNegative - Return true if the specified scev is negated, but
291/// not a constant.
292bool SCEV::isNonConstantNegative() const {
293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
294 if (!Mul) return false;
295
296 // If there is a constant factor, it will be first.
297 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
298 if (!SC) return false;
299
300 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000301 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000302}
303
Owen Anderson04052ec2009-06-22 21:57:23 +0000304SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000305 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000306
Chris Lattnerd934c702004-04-02 20:23:17 +0000307bool SCEVCouldNotCompute::classof(const SCEV *S) {
308 return S->getSCEVType() == scCouldNotCompute;
309}
310
Dan Gohmanaf752342009-07-07 17:06:11 +0000311const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000312 FoldingSetNodeID ID;
313 ID.AddInteger(scConstant);
314 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000315 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000317 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000318 UniqueSCEVs.InsertNode(S, IP);
319 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Nick Lewycky31eaca52014-01-27 10:04:03 +0000322const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000323 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000324}
325
Dan Gohmanaf752342009-07-07 17:06:11 +0000326const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000327ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
328 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000329 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000330}
331
Dan Gohman24ceda82010-06-18 19:54:20 +0000332SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000333 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000334 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000335
Dan Gohman24ceda82010-06-18 19:54:20 +0000336SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000337 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000338 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000339 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
340 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000341 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000342}
Chris Lattnerd934c702004-04-02 20:23:17 +0000343
Dan Gohman24ceda82010-06-18 19:54:20 +0000344SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000345 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000346 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
348 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350}
351
Dan Gohman24ceda82010-06-18 19:54:20 +0000352SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000353 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000354 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000355 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
356 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000357 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000358}
359
Dan Gohman7cac9572010-08-02 23:49:30 +0000360void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000361 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000362 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000363
364 // Remove this SCEVUnknown from the uniquing map.
365 SE->UniqueSCEVs.RemoveNode(this);
366
367 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000368 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000369}
370
371void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000372 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000373 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374
375 // Remove this SCEVUnknown from the uniquing map.
376 SE->UniqueSCEVs.RemoveNode(this);
377
378 // Update this SCEVUnknown to point to the new value. This is needed
379 // because there may still be outstanding SCEVs which still point to
380 // this SCEVUnknown.
381 setValPtr(New);
382}
383
Chris Lattner229907c2011-07-18 04:54:35 +0000384bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000386 if (VCE->getOpcode() == Instruction::PtrToInt)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000388 if (CE->getOpcode() == Instruction::GetElementPtr &&
389 CE->getOperand(0)->isNullValue() &&
390 CE->getNumOperands() == 2)
391 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
392 if (CI->isOne()) {
393 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
394 ->getElementType();
395 return true;
396 }
Dan Gohmancf913832010-01-28 02:15:55 +0000397
398 return false;
399}
400
Chris Lattner229907c2011-07-18 04:54:35 +0000401bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000402 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000403 if (VCE->getOpcode() == Instruction::PtrToInt)
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000405 if (CE->getOpcode() == Instruction::GetElementPtr &&
406 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000409 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (!STy->isPacked() &&
411 CE->getNumOperands() == 3 &&
412 CE->getOperand(1)->isNullValue()) {
413 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
414 if (CI->isOne() &&
415 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000416 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000417 AllocTy = STy->getElementType(1);
418 return true;
419 }
420 }
421 }
Dan Gohmancf913832010-01-28 02:15:55 +0000422
423 return false;
424}
425
Chris Lattner229907c2011-07-18 04:54:35 +0000426bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000428 if (VCE->getOpcode() == Instruction::PtrToInt)
429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
430 if (CE->getOpcode() == Instruction::GetElementPtr &&
431 CE->getNumOperands() == 3 &&
432 CE->getOperand(0)->isNullValue() &&
433 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000434 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000435 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
436 // Ignore vector types here so that ScalarEvolutionExpander doesn't
437 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000438 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000439 CTy = Ty;
440 FieldNo = CE->getOperand(2);
441 return true;
442 }
443 }
444
445 return false;
446}
447
Chris Lattnereb3e8402004-06-20 06:23:15 +0000448//===----------------------------------------------------------------------===//
449// SCEV Utilities
450//===----------------------------------------------------------------------===//
451
452namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000453/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454/// than the complexity of the RHS. This comparator is used to canonicalize
455/// expressions.
456class SCEVComplexityCompare {
457 const LoopInfo *const LI;
458public:
459 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000460
Sanjoy Das7881abd2015-12-08 04:32:51 +0000461 // Return true or false if LHS is less than, or at least RHS, respectively.
462 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
463 return compare(LHS, RHS) < 0;
464 }
Dan Gohman27065672010-08-27 15:26:01 +0000465
Sanjoy Das7881abd2015-12-08 04:32:51 +0000466 // Return negative, zero, or positive, if LHS is less than, equal to, or
467 // greater than RHS, respectively. A three-way result allows recursive
468 // comparisons to be more efficient.
469 int compare(const SCEV *LHS, const SCEV *RHS) const {
470 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
471 if (LHS == RHS)
472 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000473
Sanjoy Das7881abd2015-12-08 04:32:51 +0000474 // Primarily, sort the SCEVs by their getSCEVType().
475 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
476 if (LType != RType)
477 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000478
Sanjoy Das7881abd2015-12-08 04:32:51 +0000479 // Aside from the getSCEVType() ordering, the particular ordering
480 // isn't very important except that it's beneficial to be consistent,
481 // so that (a + b) and (b + a) don't end up as different expressions.
482 switch (static_cast<SCEVTypes>(LType)) {
483 case scUnknown: {
484 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
485 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000486
Sanjoy Das7881abd2015-12-08 04:32:51 +0000487 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
488 // not as complete as it could be.
489 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000490
Sanjoy Das7881abd2015-12-08 04:32:51 +0000491 // Order pointer values after integer values. This helps SCEVExpander
492 // form GEPs.
493 bool LIsPointer = LV->getType()->isPointerTy(),
494 RIsPointer = RV->getType()->isPointerTy();
495 if (LIsPointer != RIsPointer)
496 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000497
Sanjoy Das7881abd2015-12-08 04:32:51 +0000498 // Compare getValueID values.
499 unsigned LID = LV->getValueID(),
500 RID = RV->getValueID();
501 if (LID != RID)
502 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000503
Sanjoy Das7881abd2015-12-08 04:32:51 +0000504 // Sort arguments by their position.
505 if (const Argument *LA = dyn_cast<Argument>(LV)) {
506 const Argument *RA = cast<Argument>(RV);
507 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
508 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000509 }
510
Sanjoy Das7881abd2015-12-08 04:32:51 +0000511 // For instructions, compare their loop depth, and their operand
512 // count. This is pretty loose.
513 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
514 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000515
Sanjoy Das7881abd2015-12-08 04:32:51 +0000516 // Compare loop depths.
517 const BasicBlock *LParent = LInst->getParent(),
518 *RParent = RInst->getParent();
519 if (LParent != RParent) {
520 unsigned LDepth = LI->getLoopDepth(LParent),
521 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000523 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000524 }
Dan Gohman27065672010-08-27 15:26:01 +0000525
Sanjoy Das7881abd2015-12-08 04:32:51 +0000526 // Compare the number of operands.
527 unsigned LNumOps = LInst->getNumOperands(),
528 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000529 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000530 }
531
Sanjoy Das7881abd2015-12-08 04:32:51 +0000532 return 0;
533 }
Dan Gohman27065672010-08-27 15:26:01 +0000534
Sanjoy Das7881abd2015-12-08 04:32:51 +0000535 case scConstant: {
536 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
537 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
538
539 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000540 const APInt &LA = LC->getAPInt();
541 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000542 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
543 if (LBitWidth != RBitWidth)
544 return (int)LBitWidth - (int)RBitWidth;
545 return LA.ult(RA) ? -1 : 1;
546 }
547
548 case scAddRecExpr: {
549 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
550 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
551
552 // Compare addrec loop depths.
553 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
554 if (LLoop != RLoop) {
555 unsigned LDepth = LLoop->getLoopDepth(),
556 RDepth = RLoop->getLoopDepth();
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Addrec complexity grows with operand count.
562 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
563 if (LNumOps != RNumOps)
564 return (int)LNumOps - (int)RNumOps;
565
566 // Lexicographically compare.
567 for (unsigned i = 0; i != LNumOps; ++i) {
568 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000569 if (X != 0)
570 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000571 }
572
Sanjoy Das7881abd2015-12-08 04:32:51 +0000573 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000574 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000575
576 case scAddExpr:
577 case scMulExpr:
578 case scSMaxExpr:
579 case scUMaxExpr: {
580 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
581 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
582
583 // Lexicographically compare n-ary expressions.
584 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
585 if (LNumOps != RNumOps)
586 return (int)LNumOps - (int)RNumOps;
587
588 for (unsigned i = 0; i != LNumOps; ++i) {
589 if (i >= RNumOps)
590 return 1;
591 long X = compare(LC->getOperand(i), RC->getOperand(i));
592 if (X != 0)
593 return X;
594 }
595 return (int)LNumOps - (int)RNumOps;
596 }
597
598 case scUDivExpr: {
599 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601
602 // Lexicographically compare udiv expressions.
603 long X = compare(LC->getLHS(), RC->getLHS());
604 if (X != 0)
605 return X;
606 return compare(LC->getRHS(), RC->getRHS());
607 }
608
609 case scTruncate:
610 case scZeroExtend:
611 case scSignExtend: {
612 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
613 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
614
615 // Compare cast expressions by operand.
616 return compare(LC->getOperand(), RC->getOperand());
617 }
618
619 case scCouldNotCompute:
620 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
621 }
622 llvm_unreachable("Unknown SCEV kind!");
623 }
624};
625} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000626
627/// GroupByComplexity - Given a list of SCEV objects, order them by their
628/// complexity, and group objects of the same complexity together by value.
629/// When this routine is finished, we know that any duplicates in the vector are
630/// consecutive and that complexity is monotonically increasing.
631///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000632/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000633/// results from this routine. In other words, we don't want the results of
634/// this to depend on where the addresses of various SCEV objects happened to
635/// land in memory.
636///
Dan Gohmanaf752342009-07-07 17:06:11 +0000637static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000638 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000639 if (Ops.size() < 2) return; // Noop
640 if (Ops.size() == 2) {
641 // This is the common case, which also happens to be trivially simple.
642 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000643 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
644 if (SCEVComplexityCompare(LI)(RHS, LHS))
645 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000646 return;
647 }
648
Dan Gohman24ceda82010-06-18 19:54:20 +0000649 // Do the rough sort by complexity.
650 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
651
652 // Now that we are sorted by complexity, group elements of the same
653 // complexity. Note that this is, at worst, N^2, but the vector is likely to
654 // be extremely short in practice. Note that we take this approach because we
655 // do not want to depend on the addresses of the objects we are grouping.
656 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
657 const SCEV *S = Ops[i];
658 unsigned Complexity = S->getSCEVType();
659
660 // If there are any objects of the same complexity and same value as this
661 // one, group them.
662 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
663 if (Ops[j] == S) { // Found a duplicate.
664 // Move it to immediately after i'th element.
665 std::swap(Ops[i+1], Ops[j]);
666 ++i; // no need to rescan it.
667 if (i == e-2) return; // Done!
668 }
669 }
670 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000671}
672
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000673// Returns the size of the SCEV S.
674static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000675 struct FindSCEVSize {
676 int Size;
677 FindSCEVSize() : Size(0) {}
678
679 bool follow(const SCEV *S) {
680 ++Size;
681 // Keep looking at all operands of S.
682 return true;
683 }
684 bool isDone() const {
685 return false;
686 }
687 };
688
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000689 FindSCEVSize F;
690 SCEVTraversal<FindSCEVSize> ST(F);
691 ST.visitAll(S);
692 return F.Size;
693}
694
695namespace {
696
David Majnemer4e879362014-12-14 09:12:33 +0000697struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000698public:
699 // Computes the Quotient and Remainder of the division of Numerator by
700 // Denominator.
701 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
702 const SCEV *Denominator, const SCEV **Quotient,
703 const SCEV **Remainder) {
704 assert(Numerator && Denominator && "Uninitialized SCEV");
705
David Majnemer4e879362014-12-14 09:12:33 +0000706 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000707
708 // Check for the trivial case here to avoid having to check for it in the
709 // rest of the code.
710 if (Numerator == Denominator) {
711 *Quotient = D.One;
712 *Remainder = D.Zero;
713 return;
714 }
715
716 if (Numerator->isZero()) {
717 *Quotient = D.Zero;
718 *Remainder = D.Zero;
719 return;
720 }
721
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000722 // A simple case when N/1. The quotient is N.
723 if (Denominator->isOne()) {
724 *Quotient = Numerator;
725 *Remainder = D.Zero;
726 return;
727 }
728
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000729 // 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)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000767 APInt NumeratorVal = Numerator->getAPInt();
768 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000769 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;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000788 if (!Numerator->isAffine())
789 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000790 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
791 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000792 // Bail out if the types do not match.
793 Type *Ty = Denominator->getType();
794 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000795 Ty != StepQ->getType() || Ty != StepR->getType())
796 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
800 Numerator->getNoWrapFlags());
801 }
802
803 void visitAddExpr(const SCEVAddExpr *Numerator) {
804 SmallVector<const SCEV *, 2> Qs, Rs;
805 Type *Ty = Denominator->getType();
806
807 for (const SCEV *Op : Numerator->operands()) {
808 const SCEV *Q, *R;
809 divide(SE, Op, Denominator, &Q, &R);
810
811 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000812 if (Ty != Q->getType() || Ty != R->getType())
813 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000814
815 Qs.push_back(Q);
816 Rs.push_back(R);
817 }
818
819 if (Qs.size() == 1) {
820 Quotient = Qs[0];
821 Remainder = Rs[0];
822 return;
823 }
824
825 Quotient = SE.getAddExpr(Qs);
826 Remainder = SE.getAddExpr(Rs);
827 }
828
829 void visitMulExpr(const SCEVMulExpr *Numerator) {
830 SmallVector<const SCEV *, 2> Qs;
831 Type *Ty = Denominator->getType();
832
833 bool FoundDenominatorTerm = false;
834 for (const SCEV *Op : Numerator->operands()) {
835 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000836 if (Ty != Op->getType())
837 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000838
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.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000853 if (Ty != Q->getType())
854 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000855
856 FoundDenominatorTerm = true;
857 Qs.push_back(Q);
858 }
859
860 if (FoundDenominatorTerm) {
861 Remainder = Zero;
862 if (Qs.size() == 1)
863 Quotient = Qs[0];
864 else
865 Quotient = SE.getMulExpr(Qs);
866 return;
867 }
868
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000869 if (!isa<SCEVUnknown>(Denominator))
870 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000871
872 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
873 ValueToValueMap RewriteMap;
874 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
875 cast<SCEVConstant>(Zero)->getValue();
876 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
877
878 if (Remainder->isZero()) {
879 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(One)->getValue();
882 Quotient =
883 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884 return;
885 }
886
887 // Quotient is (Numerator - Remainder) divided by Denominator.
888 const SCEV *Q, *R;
889 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 // This SCEV does not seem to simplify: fail the division here.
891 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
892 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000893 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000894 if (R != Zero)
895 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000896 Quotient = Q;
897 }
898
899private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000900 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
901 const SCEV *Denominator)
902 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000903 Zero = SE.getZero(Denominator->getType());
904 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000905
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000906 // We generally do not know how to divide Expr by Denominator. We
907 // initialize the division to a "cannot divide" state to simplify the rest
908 // of the code.
909 cannotDivide(Numerator);
910 }
911
912 // Convenience function for giving up on the division. We set the quotient to
913 // be equal to zero and the remainder to be equal to the numerator.
914 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000915 Quotient = Zero;
916 Remainder = Numerator;
917 }
918
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000919 ScalarEvolution &SE;
920 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000921};
922
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000923}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000924
Chris Lattnerd934c702004-04-02 20:23:17 +0000925//===----------------------------------------------------------------------===//
926// Simple SCEV method implementations
927//===----------------------------------------------------------------------===//
928
Eli Friedman61f67622008-08-04 23:49:06 +0000929/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000930/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000931static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000932 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000933 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000934 // Handle the simplest case efficiently.
935 if (K == 1)
936 return SE.getTruncateOrZeroExtend(It, ResultTy);
937
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000938 // We are using the following formula for BC(It, K):
939 //
940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
941 //
Eli Friedman61f67622008-08-04 23:49:06 +0000942 // Suppose, W is the bitwidth of the return value. We must be prepared for
943 // overflow. Hence, we must assure that the result of our computation is
944 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
945 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000946 //
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000948 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
950 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000953 //
Eli Friedman61f67622008-08-04 23:49:06 +0000954 // This formula is trivially equivalent to the previous formula. However,
955 // this formula can be implemented much more efficiently. The trick is that
956 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
957 // arithmetic. To do exact division in modular arithmetic, all we have
958 // to do is multiply by the inverse. Therefore, this step can be done at
959 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000960 //
Eli Friedman61f67622008-08-04 23:49:06 +0000961 // The next issue is how to safely do the division by 2^T. The way this
962 // is done is by doing the multiplication step at a width of at least W + T
963 // bits. This way, the bottom W+T bits of the product are accurate. Then,
964 // when we perform the division by 2^T (which is equivalent to a right shift
965 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
966 // truncated out after the division by 2^T.
967 //
968 // In comparison to just directly using the first formula, this technique
969 // is much more efficient; using the first formula requires W * K bits,
970 // but this formula less than W + K bits. Also, the first formula requires
971 // a division step, whereas this formula only requires multiplies and shifts.
972 //
973 // It doesn't matter whether the subtraction step is done in the calculation
974 // width or the input iteration count's width; if the subtraction overflows,
975 // the result must be zero anyway. We prefer here to do it in the width of
976 // the induction variable because it helps a lot for certain cases; CodeGen
977 // isn't smart enough to ignore the overflow, which leads to much less
978 // efficient code if the width of the subtraction is wider than the native
979 // register width.
980 //
981 // (It's possible to not widen at all by pulling out factors of 2 before
982 // the multiplication; for example, K=2 can be calculated as
983 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
984 // extra arithmetic, so it's not an obvious win, and it gets
985 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000986
Eli Friedman61f67622008-08-04 23:49:06 +0000987 // Protection from insane SCEVs; this bound is conservative,
988 // but it probably doesn't matter.
989 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000990 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000992 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000993
Eli Friedman61f67622008-08-04 23:49:06 +0000994 // Calculate K! / 2^T and T; we divide out the factors of two before
995 // multiplying for calculating K! / 2^T to avoid overflow.
996 // Other overflow doesn't matter because we only care about the bottom
997 // W bits of the result.
998 APInt OddFactorial(W, 1);
999 unsigned T = 1;
1000 for (unsigned i = 3; i <= K; ++i) {
1001 APInt Mult(W, i);
1002 unsigned TwoFactors = Mult.countTrailingZeros();
1003 T += TwoFactors;
1004 Mult = Mult.lshr(TwoFactors);
1005 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001006 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001007
Eli Friedman61f67622008-08-04 23:49:06 +00001008 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001009 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001010
Dan Gohman8b0a4192010-03-01 17:49:51 +00001011 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001012 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001013
1014 // Calculate the multiplicative inverse of K! / 2^T;
1015 // this multiplication factor will perform the exact division by
1016 // K! / 2^T.
1017 APInt Mod = APInt::getSignedMinValue(W+1);
1018 APInt MultiplyFactor = OddFactorial.zext(W+1);
1019 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1020 MultiplyFactor = MultiplyFactor.trunc(W);
1021
1022 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001023 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001024 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001025 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001026 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001027 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001028 Dividend = SE.getMulExpr(Dividend,
1029 SE.getTruncateOrZeroExtend(S, CalculationTy));
1030 }
1031
1032 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001033 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001034
1035 // Truncate the result, and divide by K! / 2^T.
1036
1037 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1038 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001039}
1040
Chris Lattnerd934c702004-04-02 20:23:17 +00001041/// evaluateAtIteration - Return the value of this chain of recurrences at
1042/// the specified iteration number. We can evaluate this recurrence by
1043/// multiplying each element in the chain by the binomial coefficient
1044/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001048/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001049///
Dan Gohmanaf752342009-07-07 17:06:11 +00001050const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001051 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001052 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001053 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001054 // The computation is correct in the face of overflow provided that the
1055 // multiplication is performed _after_ the evaluation of the binomial
1056 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001058 if (isa<SCEVCouldNotCompute>(Coeff))
1059 return Coeff;
1060
1061 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001062 }
1063 return Result;
1064}
1065
Chris Lattnerd934c702004-04-02 20:23:17 +00001066//===----------------------------------------------------------------------===//
1067// SCEV Expression folder implementations
1068//===----------------------------------------------------------------------===//
1069
Dan Gohmanaf752342009-07-07 17:06:11 +00001070const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001072 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001073 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001074 assert(isSCEVable(Ty) &&
1075 "This is not a conversion to a SCEVable type!");
1076 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001077
Dan Gohman3a302cb2009-07-13 20:50:19 +00001078 FoldingSetNodeID ID;
1079 ID.AddInteger(scTruncate);
1080 ID.AddPointer(Op);
1081 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001082 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1084
Dan Gohman3423e722009-06-30 20:13:32 +00001085 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001087 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001088 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001089
Dan Gohman79af8542009-04-22 16:20:48 +00001090 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001091 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001092 return getTruncateExpr(ST->getOperand(), Ty);
1093
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001095 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001096 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1097
1098 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001099 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001100 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1101
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001103 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001104 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1105 SmallVector<const SCEV *, 4> Operands;
1106 bool hasTrunc = false;
1107 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1108 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001109 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1110 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001111 Operands.push_back(S);
1112 }
1113 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001114 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001115 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001116 }
1117
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001119 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001120 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1121 SmallVector<const SCEV *, 4> Operands;
1122 bool hasTrunc = false;
1123 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1124 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001125 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001127 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;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001137 for (const SCEV *Op : AddRec->operands())
1138 Operands.push_back(getTruncateExpr(Op, 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
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001216const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001217 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
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001232const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001234}
Sanjoy Das4153f472015-02-18 01:47:07 +00001235
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.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001273 auto PreStartFlags =
1274 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1275 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001276 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1277 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1278
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001279 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1280 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001281 //
1282
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001283 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1284 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1285 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001286 return PreStart;
1287
1288 // 2. Direct overflow check on the step operation's expression.
1289 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1290 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1291 const SCEV *OperandExtendedStart =
1292 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1293 (SE->*GetExtendExpr)(Step, WideTy));
1294 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1295 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1296 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1297 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1298 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1299 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1300 }
1301 return PreStart;
1302 }
1303
1304 // 3. Loop precondition.
1305 ICmpInst::Predicate Pred;
1306 const SCEV *OverflowLimit =
1307 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1308
1309 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001312
Sanjoy Das4153f472015-02-18 01:47:07 +00001313 return nullptr;
1314}
1315
1316// Get the normalized zero or sign extended expression for this AddRec's Start.
1317template <typename ExtendOpTy>
1318static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1319 ScalarEvolution *SE) {
1320 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1321
1322 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1323 if (!PreStart)
1324 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1325
1326 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1327 (SE->*GetExtendExpr)(PreStart, Ty));
1328}
1329
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001330// Try to prove away overflow by looking at "nearby" add recurrences. A
1331// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1332// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1333//
1334// Formally:
1335//
1336// {S,+,X} == {S-T,+,X} + T
1337// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1338//
1339// If ({S-T,+,X} + T) does not overflow ... (1)
1340//
1341// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1342//
1343// If {S-T,+,X} does not overflow ... (2)
1344//
1345// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1346// == {Ext(S-T)+Ext(T),+,Ext(X)}
1347//
1348// If (S-T)+T does not overflow ... (3)
1349//
1350// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1351// == {Ext(S),+,Ext(X)} == LHS
1352//
1353// Thus, if (1), (2) and (3) are true for some T, then
1354// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1355//
1356// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1357// does not overflow" restricted to the 0th iteration. Therefore we only need
1358// to check for (1) and (2).
1359//
1360// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1361// is `Delta` (defined below).
1362//
1363template <typename ExtendOpTy>
1364bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1365 const SCEV *Step,
1366 const Loop *L) {
1367 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368
1369 // We restrict `Start` to a constant to prevent SCEV from spending too much
1370 // time here. It is correct (but more expensive) to continue with a
1371 // non-constant `Start` and do a general SCEV subtraction to compute
1372 // `PreStart` below.
1373 //
1374 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1375 if (!StartC)
1376 return false;
1377
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001378 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001379
1380 for (unsigned Delta : {-2, -1, 1, 2}) {
1381 const SCEV *PreStart = getConstant(StartAI - Delta);
1382
Sanjoy Das42801102015-10-23 06:57:21 +00001383 FoldingSetNodeID ID;
1384 ID.AddInteger(scAddRecExpr);
1385 ID.AddPointer(PreStart);
1386 ID.AddPointer(Step);
1387 ID.AddPointer(L);
1388 void *IP = nullptr;
1389 const auto *PreAR =
1390 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1391
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 // Give up if we don't already have the add recurrence we need because
1393 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001394 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1395 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1396 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1397 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1398 DeltaS, &Pred, this);
1399 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1400 return true;
1401 }
1402 }
1403
1404 return false;
1405}
1406
Dan Gohmanaf752342009-07-07 17:06:11 +00001407const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001408 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001409 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001410 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001411 assert(isSCEVable(Ty) &&
1412 "This is not a conversion to a SCEVable type!");
1413 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001414
Dan Gohman3423e722009-06-30 20:13:32 +00001415 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1417 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001418 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001419
Dan Gohman79af8542009-04-22 16:20:48 +00001420 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001421 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001422 return getZeroExtendExpr(SZ->getOperand(), Ty);
1423
Dan Gohman74a0ba12009-07-13 20:55:53 +00001424 // Before doing any expensive analysis, check to see if we've already
1425 // computed a SCEV for this Op and Ty.
1426 FoldingSetNodeID ID;
1427 ID.AddInteger(scZeroExtend);
1428 ID.AddPointer(Op);
1429 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001430 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1432
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001433 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1434 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1435 // It's possible the bits taken off by the truncate were all zero bits. If
1436 // so, we should be able to simplify this further.
1437 const SCEV *X = ST->getOperand();
1438 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001439 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1440 unsigned NewBits = getTypeSizeInBits(Ty);
1441 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001442 CR.zextOrTrunc(NewBits)))
1443 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001444 }
1445
Dan Gohman76466372009-04-27 20:16:15 +00001446 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001447 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001448 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001449 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001450 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001451 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001452 const SCEV *Start = AR->getStart();
1453 const SCEV *Step = AR->getStepRecurrence(*this);
1454 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1455 const Loop *L = AR->getLoop();
1456
Dan Gohman62ef6a72009-07-25 01:22:26 +00001457 // If we have special knowledge that this addrec won't overflow,
1458 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001459 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001460 return getAddRecExpr(
1461 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1462 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001463
Dan Gohman76466372009-04-27 20:16:15 +00001464 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1465 // Note that this serves two purposes: It filters out loops that are
1466 // simply not analyzable, and it covers the case where this code is
1467 // being called from within backedge-taken count analysis, such that
1468 // attempting to ask for the backedge-taken count would likely result
1469 // in infinite recursion. In the later case, the analysis code will
1470 // cope with a conservative value, and it will take care to purge
1471 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001472 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001473 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001474 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001475 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001476
1477 // Check whether the backedge-taken count can be losslessly casted to
1478 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001479 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001480 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001481 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001482 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1483 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001484 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001485 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001486 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001487 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1488 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1489 const SCEV *WideMaxBECount =
1490 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001491 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001492 getAddExpr(WideStart,
1493 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001494 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001495 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001496 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1497 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001498 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001499 return getAddRecExpr(
1500 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1501 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001502 }
Dan Gohman76466372009-04-27 20:16:15 +00001503 // Similar to above, only this time treat the step value as signed.
1504 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001505 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001506 getAddExpr(WideStart,
1507 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001508 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001509 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001510 // Cache knowledge of AR NW, which is propagated to this AddRec.
1511 // Negative step causes unsigned wrap, but it still can't self-wrap.
1512 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001513 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001514 return getAddRecExpr(
1515 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1516 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001517 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001518 }
1519
1520 // If the backedge is guarded by a comparison with the pre-inc value
1521 // the addrec is safe. Also, if the entry is guarded by a comparison
1522 // with the start value and the backedge is guarded by a comparison
1523 // with the post-inc value, the addrec is safe.
1524 if (isKnownPositive(Step)) {
1525 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1526 getUnsignedRange(Step).getUnsignedMax());
1527 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001528 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001529 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001530 AR->getPostIncExpr(*this), N))) {
1531 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1532 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001533 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001534 return getAddRecExpr(
1535 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1536 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001537 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001538 } else if (isKnownNegative(Step)) {
1539 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1540 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001541 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1542 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001543 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001544 AR->getPostIncExpr(*this), N))) {
1545 // Cache knowledge of AR NW, which is propagated to this AddRec.
1546 // Negative step causes unsigned wrap, but it still can't self-wrap.
1547 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1548 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001549 return getAddRecExpr(
1550 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1551 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001552 }
Dan Gohman76466372009-04-27 20:16:15 +00001553 }
1554 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001555
1556 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1557 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1558 return getAddRecExpr(
1559 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1560 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1561 }
Dan Gohman76466372009-04-27 20:16:15 +00001562 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001563
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001564 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1565 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001566 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001567 // If the addition does not unsign overflow then we can, by definition,
1568 // commute the zero extension with the addition operation.
1569 SmallVector<const SCEV *, 4> Ops;
1570 for (const auto *Op : SA->operands())
1571 Ops.push_back(getZeroExtendExpr(Op, Ty));
1572 return getAddExpr(Ops, SCEV::FlagNUW);
1573 }
1574 }
1575
Dan Gohman74a0ba12009-07-13 20:55:53 +00001576 // The cast wasn't folded; create an explicit cast node.
1577 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001578 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001579 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1580 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001581 UniqueSCEVs.InsertNode(S, IP);
1582 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001583}
1584
Dan Gohmanaf752342009-07-07 17:06:11 +00001585const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001586 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001587 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001588 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001589 assert(isSCEVable(Ty) &&
1590 "This is not a conversion to a SCEVable type!");
1591 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001592
Dan Gohman3423e722009-06-30 20:13:32 +00001593 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001594 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1595 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001596 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001597
Dan Gohman79af8542009-04-22 16:20:48 +00001598 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001599 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001600 return getSignExtendExpr(SS->getOperand(), Ty);
1601
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001602 // sext(zext(x)) --> zext(x)
1603 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1604 return getZeroExtendExpr(SZ->getOperand(), Ty);
1605
Dan Gohman74a0ba12009-07-13 20:55:53 +00001606 // Before doing any expensive analysis, check to see if we've already
1607 // computed a SCEV for this Op and Ty.
1608 FoldingSetNodeID ID;
1609 ID.AddInteger(scSignExtend);
1610 ID.AddPointer(Op);
1611 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001612 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001613 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1614
Nick Lewyckyb32c8942011-01-22 22:06:21 +00001615 // If the input value is provably positive, build a zext instead.
1616 if (isKnownNonNegative(Op))
1617 return getZeroExtendExpr(Op, Ty);
1618
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001619 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1620 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1621 // It's possible the bits taken off by the truncate were all sign bits. If
1622 // so, we should be able to simplify this further.
1623 const SCEV *X = ST->getOperand();
1624 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001625 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1626 unsigned NewBits = getTypeSizeInBits(Ty);
1627 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001628 CR.sextOrTrunc(NewBits)))
1629 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001630 }
1631
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001632 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001633 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001634 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001635 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1636 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001637 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001638 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001639 const APInt &C1 = SC1->getAPInt();
1640 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001641 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001642 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001643 return getAddExpr(getSignExtendExpr(SC1, Ty),
1644 getSignExtendExpr(SMul, Ty));
1645 }
1646 }
1647 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001648
1649 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001650 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001651 // If the addition does not sign overflow then we can, by definition,
1652 // commute the sign extension with the addition operation.
1653 SmallVector<const SCEV *, 4> Ops;
1654 for (const auto *Op : SA->operands())
1655 Ops.push_back(getSignExtendExpr(Op, Ty));
1656 return getAddExpr(Ops, SCEV::FlagNSW);
1657 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001658 }
Dan Gohman76466372009-04-27 20:16:15 +00001659 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001660 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001661 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001662 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001663 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001664 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001665 const SCEV *Start = AR->getStart();
1666 const SCEV *Step = AR->getStepRecurrence(*this);
1667 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1668 const Loop *L = AR->getLoop();
1669
Dan Gohman62ef6a72009-07-25 01:22:26 +00001670 // If we have special knowledge that this addrec won't overflow,
1671 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001672 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001673 return getAddRecExpr(
1674 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1675 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001676
Dan Gohman76466372009-04-27 20:16:15 +00001677 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1678 // Note that this serves two purposes: It filters out loops that are
1679 // simply not analyzable, and it covers the case where this code is
1680 // being called from within backedge-taken count analysis, such that
1681 // attempting to ask for the backedge-taken count would likely result
1682 // in infinite recursion. In the later case, the analysis code will
1683 // cope with a conservative value, and it will take care to purge
1684 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001685 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001686 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001687 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001688 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001689
1690 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001691 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001692 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001693 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001694 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001695 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1696 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001697 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001698 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001699 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001700 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1701 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1702 const SCEV *WideMaxBECount =
1703 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001704 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001705 getAddExpr(WideStart,
1706 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001707 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001708 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001709 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1710 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001711 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001712 return getAddRecExpr(
1713 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1714 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001715 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001716 // Similar to above, only this time treat the step value as unsigned.
1717 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001718 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001719 getAddExpr(WideStart,
1720 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001721 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001722 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001723 // If AR wraps around then
1724 //
1725 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1726 // => SAdd != OperandExtendedAdd
1727 //
1728 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1729 // (SAdd == OperandExtendedAdd => AR is NW)
1730
1731 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1732
Dan Gohman8c129d72009-07-16 17:34:36 +00001733 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001734 return getAddRecExpr(
1735 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1736 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001737 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001738 }
1739
1740 // If the backedge is guarded by a comparison with the pre-inc value
1741 // the addrec is safe. Also, if the entry is guarded by a comparison
1742 // with the start value and the backedge is guarded by a comparison
1743 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001744 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001745 const SCEV *OverflowLimit =
1746 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001747 if (OverflowLimit &&
1748 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1749 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1750 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1751 OverflowLimit)))) {
1752 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1753 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001754 return getAddRecExpr(
1755 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1756 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001757 }
1758 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001759 // If Start and Step are constants, check if we can apply this
1760 // transformation:
1761 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001762 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1763 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001764 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001765 const APInt &C1 = SC1->getAPInt();
1766 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001767 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1768 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001769 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001770 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1771 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001772 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1773 }
1774 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001775
1776 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1777 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1778 return getAddRecExpr(
1779 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1780 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1781 }
Dan Gohman76466372009-04-27 20:16:15 +00001782 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001783
Dan Gohman74a0ba12009-07-13 20:55:53 +00001784 // The cast wasn't folded; create an explicit cast node.
1785 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001787 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1788 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001789 UniqueSCEVs.InsertNode(S, IP);
1790 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001791}
1792
Dan Gohman8db2edc2009-06-13 15:56:47 +00001793/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1794/// unspecified bits out to the given type.
1795///
Dan Gohmanaf752342009-07-07 17:06:11 +00001796const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001797 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001798 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1799 "This is not an extending conversion!");
1800 assert(isSCEVable(Ty) &&
1801 "This is not a conversion to a SCEVable type!");
1802 Ty = getEffectiveSCEVType(Ty);
1803
1804 // Sign-extend negative constants.
1805 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001806 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001807 return getSignExtendExpr(Op, Ty);
1808
1809 // Peel off a truncate cast.
1810 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001811 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001812 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1813 return getAnyExtendExpr(NewOp, Ty);
1814 return getTruncateOrNoop(NewOp, Ty);
1815 }
1816
1817 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001818 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001819 if (!isa<SCEVZeroExtendExpr>(ZExt))
1820 return ZExt;
1821
1822 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001823 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001824 if (!isa<SCEVSignExtendExpr>(SExt))
1825 return SExt;
1826
Dan Gohman51ad99d2010-01-21 02:09:26 +00001827 // Force the cast to be folded into the operands of an addrec.
1828 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1829 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001830 for (const SCEV *Op : AR->operands())
1831 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001832 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001833 }
1834
Dan Gohman8db2edc2009-06-13 15:56:47 +00001835 // If the expression is obviously signed, use the sext cast value.
1836 if (isa<SCEVSMaxExpr>(Op))
1837 return SExt;
1838
1839 // Absent any other information, use the zext cast value.
1840 return ZExt;
1841}
1842
Dan Gohman038d02e2009-06-14 22:58:51 +00001843/// CollectAddOperandsWithScales - Process the given Ops list, which is
1844/// a list of operands to be added under the given scale, update the given
1845/// map. This is a helper function for getAddRecExpr. As an example of
1846/// what it does, given a sequence of operands that would form an add
1847/// expression like this:
1848///
Tobias Grosserba49e422014-03-05 10:37:17 +00001849/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001850///
1851/// where A and B are constants, update the map with these values:
1852///
1853/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1854///
1855/// and add 13 + A*B*29 to AccumulatedConstant.
1856/// This will allow getAddRecExpr to produce this:
1857///
1858/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1859///
1860/// This form often exposes folding opportunities that are hidden in
1861/// the original operand list.
1862///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001863/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001864/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1865/// the common case where no interesting opportunities are present, and
1866/// is also used as a check to avoid infinite recursion.
1867///
1868static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001869CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001870 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001871 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001872 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001873 const APInt &Scale,
1874 ScalarEvolution &SE) {
1875 bool Interesting = false;
1876
Dan Gohman45073042010-06-18 19:12:32 +00001877 // Iterate over the add operands. They are sorted, with constants first.
1878 unsigned i = 0;
1879 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1880 ++i;
1881 // Pull a buried constant out to the outside.
1882 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1883 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001884 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001885 }
1886
1887 // Next comes everything else. We're especially interested in multiplies
1888 // here, but they're in the middle, so just visit the rest with one loop.
1889 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001890 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1891 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1892 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001893 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001894 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1895 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001896 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001897 Interesting |=
1898 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001899 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001900 NewScale, SE);
1901 } else {
1902 // A multiplication of a constant with some other value. Update
1903 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001904 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1905 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001906 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001907 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001908 NewOps.push_back(Pair.first->first);
1909 } else {
1910 Pair.first->second += NewScale;
1911 // The map already had an entry for this value, which may indicate
1912 // a folding opportunity.
1913 Interesting = true;
1914 }
1915 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001916 } else {
1917 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001918 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001919 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001920 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001921 NewOps.push_back(Pair.first->first);
1922 } else {
1923 Pair.first->second += Scale;
1924 // The map already had an entry for this value, which may indicate
1925 // a folding opportunity.
1926 Interesting = true;
1927 }
1928 }
1929 }
1930
1931 return Interesting;
1932}
1933
Sanjoy Das81401d42015-01-10 23:41:24 +00001934// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1935// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1936// can't-overflow flags for the operation if possible.
1937static SCEV::NoWrapFlags
1938StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1939 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001940 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001941 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001942 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001943
1944 bool CanAnalyze =
1945 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1946 (void)CanAnalyze;
1947 assert(CanAnalyze && "don't call from other places!");
1948
1949 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1950 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001951 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001952
1953 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001954 auto IsKnownNonNegative = [&](const SCEV *S) {
1955 return SE->isKnownNonNegative(S);
1956 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001957
Sanjoy Das3b827c72015-11-29 23:40:53 +00001958 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001959 Flags =
1960 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001961
Sanjoy Das8f274152015-10-22 19:57:19 +00001962 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1963
1964 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1965 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1966
1967 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1968 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1969
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001970 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00001971 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00001972 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1973 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00001974 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1975 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1976 }
1977 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00001978 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1979 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00001980 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
1981 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
1982 }
1983 }
1984
1985 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00001986}
1987
Dan Gohman4d5435d2009-05-24 23:45:28 +00001988/// getAddExpr - Get a canonical add expression, or something simpler if
1989/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001990const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00001991 SCEV::NoWrapFlags Flags) {
1992 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1993 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00001994 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00001995 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00001996#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00001997 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00001998 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00001999 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002000 "SCEVAddExpr operand types don't match!");
2001#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002002
2003 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002004 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002005
Sanjoy Das64895612015-10-09 02:44:45 +00002006 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2007
Chris Lattnerd934c702004-04-02 20:23:17 +00002008 // If there are any constants, fold them together.
2009 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002010 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002011 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002012 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002013 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002014 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002015 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002016 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002017 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002018 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002019 }
2020
2021 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002022 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002023 Ops.erase(Ops.begin());
2024 --Idx;
2025 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002026
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002027 if (Ops.size() == 1) return Ops[0];
2028 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002029
Dan Gohman15871f22010-08-27 21:39:59 +00002030 // Okay, check to see if the same value occurs in the operand list more than
2031 // once. If so, merge them together into an multiply expression. Since we
2032 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002033 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002034 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002035 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002036 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002037 // Scan ahead to count how many equal operands there are.
2038 unsigned Count = 2;
2039 while (i+Count != e && Ops[i+Count] == Ops[i])
2040 ++Count;
2041 // Merge the values into a multiply.
2042 const SCEV *Scale = getConstant(Ty, Count);
2043 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2044 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002045 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002046 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002047 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002048 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002049 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002050 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002051 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002052 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002053
Dan Gohman2e55cc52009-05-08 21:03:19 +00002054 // Check for truncates. If all the operands are truncated from the same
2055 // type, see if factoring out the truncate would permit the result to be
2056 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2057 // if the contents of the resulting outer trunc fold to something simple.
2058 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2059 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002060 Type *DstType = Trunc->getType();
2061 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002062 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002063 bool Ok = true;
2064 // Check all the operands to see if they can be represented in the
2065 // source type of the truncate.
2066 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2067 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2068 if (T->getOperand()->getType() != SrcType) {
2069 Ok = false;
2070 break;
2071 }
2072 LargeOps.push_back(T->getOperand());
2073 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002074 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002075 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002076 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002077 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2078 if (const SCEVTruncateExpr *T =
2079 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2080 if (T->getOperand()->getType() != SrcType) {
2081 Ok = false;
2082 break;
2083 }
2084 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002085 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002086 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002087 } else {
2088 Ok = false;
2089 break;
2090 }
2091 }
2092 if (Ok)
2093 LargeOps.push_back(getMulExpr(LargeMulOps));
2094 } else {
2095 Ok = false;
2096 break;
2097 }
2098 }
2099 if (Ok) {
2100 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002101 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002102 // If it folds to something simple, use it. Otherwise, don't.
2103 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2104 return getTruncateExpr(Fold, DstType);
2105 }
2106 }
2107
2108 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002109 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2110 ++Idx;
2111
2112 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002113 if (Idx < Ops.size()) {
2114 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002115 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002116 // If we have an add, expand the add operands onto the end of the operands
2117 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002118 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002119 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002120 DeletedAdd = true;
2121 }
2122
2123 // If we deleted at least one add, we added operands to the end of the list,
2124 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002125 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002126 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002127 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002128 }
2129
2130 // Skip over the add expression until we get to a multiply.
2131 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2132 ++Idx;
2133
Dan Gohman038d02e2009-06-14 22:58:51 +00002134 // Check to see if there are any folding opportunities present with
2135 // operands multiplied by constant values.
2136 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2137 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002138 DenseMap<const SCEV *, APInt> M;
2139 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002140 APInt AccumulatedConstant(BitWidth, 0);
2141 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002142 Ops.data(), Ops.size(),
2143 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002144 struct APIntCompare {
2145 bool operator()(const APInt &LHS, const APInt &RHS) const {
2146 return LHS.ult(RHS);
2147 }
2148 };
2149
Dan Gohman038d02e2009-06-14 22:58:51 +00002150 // Some interesting folding opportunity is present, so its worthwhile to
2151 // re-generate the operands list. Group the operands by constant scale,
2152 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002153 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002154 for (const SCEV *NewOp : NewOps)
2155 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002156 // Re-generate the operands list.
2157 Ops.clear();
2158 if (AccumulatedConstant != 0)
2159 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002160 for (auto &MulOp : MulOpLists)
2161 if (MulOp.first != 0)
2162 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2163 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002164 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002165 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002166 if (Ops.size() == 1)
2167 return Ops[0];
2168 return getAddExpr(Ops);
2169 }
2170 }
2171
Chris Lattnerd934c702004-04-02 20:23:17 +00002172 // If we are adding something to a multiply expression, make sure the
2173 // something is not already an operand of the multiply. If so, merge it into
2174 // the multiply.
2175 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002176 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002177 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002178 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002179 if (isa<SCEVConstant>(MulOpSCEV))
2180 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002181 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002182 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002183 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002184 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002185 if (Mul->getNumOperands() != 2) {
2186 // If the multiply has more than two operands, we must get the
2187 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002188 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2189 Mul->op_begin()+MulOp);
2190 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002191 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002192 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002193 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002194 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002195 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002196 if (Ops.size() == 2) return OuterMul;
2197 if (AddOp < Idx) {
2198 Ops.erase(Ops.begin()+AddOp);
2199 Ops.erase(Ops.begin()+Idx-1);
2200 } else {
2201 Ops.erase(Ops.begin()+Idx);
2202 Ops.erase(Ops.begin()+AddOp-1);
2203 }
2204 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002205 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002206 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002207
Chris Lattnerd934c702004-04-02 20:23:17 +00002208 // Check this multiply against other multiplies being added together.
2209 for (unsigned OtherMulIdx = Idx+1;
2210 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2211 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002212 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002213 // If MulOp occurs in OtherMul, we can fold the two multiplies
2214 // together.
2215 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2216 OMulOp != e; ++OMulOp)
2217 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2218 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002219 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002220 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002221 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002222 Mul->op_begin()+MulOp);
2223 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002224 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002225 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002226 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002227 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002228 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002229 OtherMul->op_begin()+OMulOp);
2230 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002231 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002232 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002233 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2234 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002235 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002236 Ops.erase(Ops.begin()+Idx);
2237 Ops.erase(Ops.begin()+OtherMulIdx-1);
2238 Ops.push_back(OuterMul);
2239 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002240 }
2241 }
2242 }
2243 }
2244
2245 // If there are any add recurrences in the operands list, see if any other
2246 // added values are loop invariant. If so, we can fold them into the
2247 // recurrence.
2248 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2249 ++Idx;
2250
2251 // Scan over all recurrences, trying to fold loop invariants into them.
2252 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2253 // Scan all of the other operands to this add and add them to the vector if
2254 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002255 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002256 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002257 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002258 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002259 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002260 LIOps.push_back(Ops[i]);
2261 Ops.erase(Ops.begin()+i);
2262 --i; --e;
2263 }
2264
2265 // If we found some loop invariants, fold them into the recurrence.
2266 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002267 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002268 LIOps.push_back(AddRec->getStart());
2269
Dan Gohmanaf752342009-07-07 17:06:11 +00002270 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002271 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002272 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002273
Dan Gohman16206132010-06-30 07:16:37 +00002274 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002275 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002276 // Always propagate NW.
2277 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002278 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002279
Chris Lattnerd934c702004-04-02 20:23:17 +00002280 // If all of the other operands were loop invariant, we are done.
2281 if (Ops.size() == 1) return NewRec;
2282
Nick Lewyckydb66b822011-09-06 05:08:09 +00002283 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002284 for (unsigned i = 0;; ++i)
2285 if (Ops[i] == AddRec) {
2286 Ops[i] = NewRec;
2287 break;
2288 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002289 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002290 }
2291
2292 // Okay, if there weren't any loop invariants to be folded, check to see if
2293 // there are multiple AddRec's with the same loop induction variable being
2294 // added together. If so, we can fold them.
2295 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002296 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2297 ++OtherIdx)
2298 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2299 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2300 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2301 AddRec->op_end());
2302 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2303 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002304 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002305 if (OtherAddRec->getLoop() == AddRecLoop) {
2306 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2307 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002308 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002309 AddRecOps.append(OtherAddRec->op_begin()+i,
2310 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002311 break;
2312 }
Dan Gohman028c1812010-08-29 14:53:34 +00002313 AddRecOps[i] = getAddExpr(AddRecOps[i],
2314 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002315 }
2316 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002317 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002318 // Step size has changed, so we cannot guarantee no self-wraparound.
2319 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002320 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002321 }
2322
2323 // Otherwise couldn't fold anything into this recurrence. Move onto the
2324 // next one.
2325 }
2326
2327 // Okay, it looks like we really DO need an add expr. Check to see if we
2328 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002329 FoldingSetNodeID ID;
2330 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002331 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2332 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002333 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002334 SCEVAddExpr *S =
2335 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2336 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002337 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2338 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002339 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2340 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002341 UniqueSCEVs.InsertNode(S, IP);
2342 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002343 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002344 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002345}
2346
Nick Lewycky287682e2011-10-04 06:51:26 +00002347static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2348 uint64_t k = i*j;
2349 if (j > 1 && k / j != i) Overflow = true;
2350 return k;
2351}
2352
2353/// Compute the result of "n choose k", the binomial coefficient. If an
2354/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002355/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002356static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2357 // We use the multiplicative formula:
2358 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2359 // At each iteration, we take the n-th term of the numeral and divide by the
2360 // (k-n)th term of the denominator. This division will always produce an
2361 // integral result, and helps reduce the chance of overflow in the
2362 // intermediate computations. However, we can still overflow even when the
2363 // final result would fit.
2364
2365 if (n == 0 || n == k) return 1;
2366 if (k > n) return 0;
2367
2368 if (k > n/2)
2369 k = n-k;
2370
2371 uint64_t r = 1;
2372 for (uint64_t i = 1; i <= k; ++i) {
2373 r = umul_ov(r, n-(i-1), Overflow);
2374 r /= i;
2375 }
2376 return r;
2377}
2378
Nick Lewycky05044c22014-12-06 00:45:50 +00002379/// Determine if any of the operands in this SCEV are a constant or if
2380/// any of the add or multiply expressions in this SCEV contain a constant.
2381static bool containsConstantSomewhere(const SCEV *StartExpr) {
2382 SmallVector<const SCEV *, 4> Ops;
2383 Ops.push_back(StartExpr);
2384 while (!Ops.empty()) {
2385 const SCEV *CurrentExpr = Ops.pop_back_val();
2386 if (isa<SCEVConstant>(*CurrentExpr))
2387 return true;
2388
2389 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2390 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002391 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002392 }
2393 }
2394 return false;
2395}
2396
Dan Gohman4d5435d2009-05-24 23:45:28 +00002397/// getMulExpr - Get a canonical multiply expression, or something simpler if
2398/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002399const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002400 SCEV::NoWrapFlags Flags) {
2401 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2402 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002403 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002404 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002405#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002406 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002407 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002408 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002409 "SCEVMulExpr operand types don't match!");
2410#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002411
2412 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002413 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002414
Sanjoy Das64895612015-10-09 02:44:45 +00002415 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2416
Chris Lattnerd934c702004-04-02 20:23:17 +00002417 // If there are any constants, fold them together.
2418 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002419 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002420
2421 // C1*(C2+V) -> C1*C2 + C1*V
2422 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002423 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2424 // If any of Add's ops are Adds or Muls with a constant,
2425 // apply this transformation as well.
2426 if (Add->getNumOperands() == 2)
2427 if (containsConstantSomewhere(Add))
2428 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2429 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002430
Chris Lattnerd934c702004-04-02 20:23:17 +00002431 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002432 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002433 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002434 ConstantInt *Fold =
2435 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002436 Ops[0] = getConstant(Fold);
2437 Ops.erase(Ops.begin()+1); // Erase the folded element
2438 if (Ops.size() == 1) return Ops[0];
2439 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002440 }
2441
2442 // If we are left with a constant one being multiplied, strip it off.
2443 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2444 Ops.erase(Ops.begin());
2445 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002446 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002447 // If we have a multiply of zero, it will always be zero.
2448 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002449 } else if (Ops[0]->isAllOnesValue()) {
2450 // If we have a mul by -1 of an add, try distributing the -1 among the
2451 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002452 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002453 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2454 SmallVector<const SCEV *, 4> NewOps;
2455 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002456 for (const SCEV *AddOp : Add->operands()) {
2457 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002458 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2459 NewOps.push_back(Mul);
2460 }
2461 if (AnyFolded)
2462 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002463 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002464 // Negation preserves a recurrence's no self-wrap property.
2465 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002466 for (const SCEV *AddRecOp : AddRec->operands())
2467 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2468
Andrew Tricke92dcce2011-03-14 17:38:54 +00002469 return getAddRecExpr(Operands, AddRec->getLoop(),
2470 AddRec->getNoWrapFlags(SCEV::FlagNW));
2471 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002472 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002473 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002474
2475 if (Ops.size() == 1)
2476 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002477 }
2478
2479 // Skip over the add expression until we get to a multiply.
2480 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2481 ++Idx;
2482
Chris Lattnerd934c702004-04-02 20:23:17 +00002483 // If there are mul operands inline them all into this expression.
2484 if (Idx < Ops.size()) {
2485 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002486 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002487 // If we have an mul, expand the mul operands onto the end of the operands
2488 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002489 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002490 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002491 DeletedMul = true;
2492 }
2493
2494 // If we deleted at least one mul, we added operands to the end of the list,
2495 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002496 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002497 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002498 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002499 }
2500
2501 // If there are any add recurrences in the operands list, see if any other
2502 // added values are loop invariant. If so, we can fold them into the
2503 // recurrence.
2504 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2505 ++Idx;
2506
2507 // Scan over all recurrences, trying to fold loop invariants into them.
2508 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2509 // Scan all of the other operands to this mul and add them to the vector if
2510 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002511 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002512 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002513 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002514 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002515 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002516 LIOps.push_back(Ops[i]);
2517 Ops.erase(Ops.begin()+i);
2518 --i; --e;
2519 }
2520
2521 // If we found some loop invariants, fold them into the recurrence.
2522 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002523 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002524 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002525 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002526 const SCEV *Scale = getMulExpr(LIOps);
2527 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2528 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002529
Dan Gohman16206132010-06-30 07:16:37 +00002530 // Build the new addrec. Propagate the NUW and NSW flags if both the
2531 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002532 //
2533 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002534 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002535 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2536 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002537
2538 // If all of the other operands were loop invariant, we are done.
2539 if (Ops.size() == 1) return NewRec;
2540
Nick Lewyckydb66b822011-09-06 05:08:09 +00002541 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002542 for (unsigned i = 0;; ++i)
2543 if (Ops[i] == AddRec) {
2544 Ops[i] = NewRec;
2545 break;
2546 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002547 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002548 }
2549
2550 // Okay, if there weren't any loop invariants to be folded, check to see if
2551 // there are multiple AddRec's with the same loop induction variable being
2552 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002553
2554 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2555 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2556 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2557 // ]]],+,...up to x=2n}.
2558 // Note that the arguments to choose() are always integers with values
2559 // known at compile time, never SCEV objects.
2560 //
2561 // The implementation avoids pointless extra computations when the two
2562 // addrec's are of different length (mathematically, it's equivalent to
2563 // an infinite stream of zeros on the right).
2564 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002565 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002566 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002567 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002568 const SCEVAddRecExpr *OtherAddRec =
2569 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2570 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002571 continue;
2572
Nick Lewycky97756402014-09-01 05:17:15 +00002573 bool Overflow = false;
2574 Type *Ty = AddRec->getType();
2575 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2576 SmallVector<const SCEV*, 7> AddRecOps;
2577 for (int x = 0, xe = AddRec->getNumOperands() +
2578 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002579 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002580 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2581 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2582 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2583 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2584 z < ze && !Overflow; ++z) {
2585 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2586 uint64_t Coeff;
2587 if (LargerThan64Bits)
2588 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2589 else
2590 Coeff = Coeff1*Coeff2;
2591 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2592 const SCEV *Term1 = AddRec->getOperand(y-z);
2593 const SCEV *Term2 = OtherAddRec->getOperand(z);
2594 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002595 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002596 }
Nick Lewycky97756402014-09-01 05:17:15 +00002597 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002598 }
Nick Lewycky97756402014-09-01 05:17:15 +00002599 if (!Overflow) {
2600 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2601 SCEV::FlagAnyWrap);
2602 if (Ops.size() == 2) return NewAddRec;
2603 Ops[Idx] = NewAddRec;
2604 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2605 OpsModified = true;
2606 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2607 if (!AddRec)
2608 break;
2609 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002610 }
Nick Lewycky97756402014-09-01 05:17:15 +00002611 if (OpsModified)
2612 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002613
2614 // Otherwise couldn't fold anything into this recurrence. Move onto the
2615 // next one.
2616 }
2617
2618 // Okay, it looks like we really DO need an mul expr. Check to see if we
2619 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002620 FoldingSetNodeID ID;
2621 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002622 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2623 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002624 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002625 SCEVMulExpr *S =
2626 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2627 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002628 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2629 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002630 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2631 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002632 UniqueSCEVs.InsertNode(S, IP);
2633 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002634 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002635 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002636}
2637
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002638/// getUDivExpr - Get a canonical unsigned division expression, or something
2639/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002640const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2641 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002642 assert(getEffectiveSCEVType(LHS->getType()) ==
2643 getEffectiveSCEVType(RHS->getType()) &&
2644 "SCEVUDivExpr operand types don't match!");
2645
Dan Gohmana30370b2009-05-04 22:02:23 +00002646 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002647 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002648 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002649 // If the denominator is zero, the result of the udiv is undefined. Don't
2650 // try to analyze it, because the resolution chosen here may differ from
2651 // the resolution chosen in other parts of the compiler.
2652 if (!RHSC->getValue()->isZero()) {
2653 // Determine if the division can be folded into the operands of
2654 // its operands.
2655 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002656 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002657 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002658 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002659 // For non-power-of-two values, effectively round the value up to the
2660 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002661 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002662 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002663 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002664 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002665 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2666 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002667 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2668 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002669 const APInt &StepInt = Step->getAPInt();
2670 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002671 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002672 getZeroExtendExpr(AR, ExtTy) ==
2673 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2674 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002675 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002676 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002677 for (const SCEV *Op : AR->operands())
2678 Operands.push_back(getUDivExpr(Op, RHS));
2679 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002680 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002681 /// Get a canonical UDivExpr for a recurrence.
2682 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2683 // We can currently only fold X%N if X is constant.
2684 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2685 if (StartC && !DivInt.urem(StepInt) &&
2686 getZeroExtendExpr(AR, ExtTy) ==
2687 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2688 getZeroExtendExpr(Step, ExtTy),
2689 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002690 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002691 const APInt &StartRem = StartInt.urem(StepInt);
2692 if (StartRem != 0)
2693 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2694 AR->getLoop(), SCEV::FlagNW);
2695 }
2696 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002697 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2698 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2699 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002700 for (const SCEV *Op : M->operands())
2701 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002702 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2703 // Find an operand that's safely divisible.
2704 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2705 const SCEV *Op = M->getOperand(i);
2706 const SCEV *Div = getUDivExpr(Op, RHSC);
2707 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2708 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2709 M->op_end());
2710 Operands[i] = Div;
2711 return getMulExpr(Operands);
2712 }
2713 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002714 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002715 // (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 +00002716 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002717 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002718 for (const SCEV *Op : A->operands())
2719 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002720 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2721 Operands.clear();
2722 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2723 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2724 if (isa<SCEVUDivExpr>(Op) ||
2725 getMulExpr(Op, RHS) != A->getOperand(i))
2726 break;
2727 Operands.push_back(Op);
2728 }
2729 if (Operands.size() == A->getNumOperands())
2730 return getAddExpr(Operands);
2731 }
2732 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002733
Dan Gohmanacd700a2010-04-22 01:35:11 +00002734 // Fold if both operands are constant.
2735 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2736 Constant *LHSCV = LHSC->getValue();
2737 Constant *RHSCV = RHSC->getValue();
2738 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2739 RHSCV)));
2740 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002741 }
2742 }
2743
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002744 FoldingSetNodeID ID;
2745 ID.AddInteger(scUDivExpr);
2746 ID.AddPointer(LHS);
2747 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002748 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002749 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002750 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2751 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002752 UniqueSCEVs.InsertNode(S, IP);
2753 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002754}
2755
Nick Lewycky31eaca52014-01-27 10:04:03 +00002756static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002757 APInt A = C1->getAPInt().abs();
2758 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002759 uint32_t ABW = A.getBitWidth();
2760 uint32_t BBW = B.getBitWidth();
2761
2762 if (ABW > BBW)
2763 B = B.zext(ABW);
2764 else if (ABW < BBW)
2765 A = A.zext(BBW);
2766
2767 return APIntOps::GreatestCommonDivisor(A, B);
2768}
2769
2770/// getUDivExactExpr - Get a canonical unsigned division expression, or
2771/// something simpler if possible. There is no representation for an exact udiv
2772/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2773/// We can't do this when it's not exact because the udiv may be clearing bits.
2774const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2775 const SCEV *RHS) {
2776 // TODO: we could try to find factors in all sorts of things, but for now we
2777 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2778 // end of this file for inspiration.
2779
2780 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2781 if (!Mul)
2782 return getUDivExpr(LHS, RHS);
2783
2784 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2785 // If the mulexpr multiplies by a constant, then that constant must be the
2786 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002787 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002788 if (LHSCst == RHSCst) {
2789 SmallVector<const SCEV *, 2> Operands;
2790 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2791 return getMulExpr(Operands);
2792 }
2793
2794 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2795 // that there's a factor provided by one of the other terms. We need to
2796 // check.
2797 APInt Factor = gcd(LHSCst, RHSCst);
2798 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002799 LHSCst =
2800 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2801 RHSCst =
2802 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002803 SmallVector<const SCEV *, 2> Operands;
2804 Operands.push_back(LHSCst);
2805 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2806 LHS = getMulExpr(Operands);
2807 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002808 Mul = dyn_cast<SCEVMulExpr>(LHS);
2809 if (!Mul)
2810 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002811 }
2812 }
2813 }
2814
2815 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2816 if (Mul->getOperand(i) == RHS) {
2817 SmallVector<const SCEV *, 2> Operands;
2818 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2819 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2820 return getMulExpr(Operands);
2821 }
2822 }
2823
2824 return getUDivExpr(LHS, RHS);
2825}
Chris Lattnerd934c702004-04-02 20:23:17 +00002826
Dan Gohman4d5435d2009-05-24 23:45:28 +00002827/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2828/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002829const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2830 const Loop *L,
2831 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002832 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002833 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002834 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002835 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002836 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002837 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002838 }
2839
2840 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002841 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002842}
2843
Dan Gohman4d5435d2009-05-24 23:45:28 +00002844/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2845/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002846const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002847ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002848 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002849 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002850#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002851 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002852 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002853 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002854 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002855 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002856 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002857 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002858#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002859
Dan Gohmanbe928e32008-06-18 16:23:07 +00002860 if (Operands.back()->isZero()) {
2861 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002862 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002863 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002864
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002865 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2866 // use that information to infer NUW and NSW flags. However, computing a
2867 // BE count requires calling getAddRecExpr, so we may not yet have a
2868 // meaningful BE count at this point (and if we don't, we'd be stuck
2869 // with a SCEVCouldNotCompute as the cached BE count).
2870
Sanjoy Das81401d42015-01-10 23:41:24 +00002871 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002872
Dan Gohman223a5d22008-08-08 18:33:12 +00002873 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002874 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002875 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002876 if (L->contains(NestedLoop)
2877 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2878 : (!NestedLoop->contains(L) &&
2879 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002880 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002881 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002882 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002883 // AddRecs require their operands be loop-invariant with respect to their
2884 // loops. Don't perform this transformation if it would break this
2885 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002886 bool AllInvariant = all_of(
2887 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002888
Dan Gohmancc030b72009-06-26 22:36:20 +00002889 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002890 // Create a recurrence for the outer loop with the same step size.
2891 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002892 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2893 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002894 SCEV::NoWrapFlags OuterFlags =
2895 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002896
2897 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002898 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2899 return isLoopInvariant(Op, NestedLoop);
2900 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002901
Andrew Trick8b55b732011-03-14 16:50:06 +00002902 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002903 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002904 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002905 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2906 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002907 SCEV::NoWrapFlags InnerFlags =
2908 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002909 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2910 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002911 }
2912 // Reset Operands to its original state.
2913 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002914 }
2915 }
2916
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002917 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2918 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002919 FoldingSetNodeID ID;
2920 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002921 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2922 ID.AddPointer(Operands[i]);
2923 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002924 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002925 SCEVAddRecExpr *S =
2926 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2927 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002928 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2929 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002930 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2931 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002932 UniqueSCEVs.InsertNode(S, IP);
2933 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002934 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002935 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002936}
2937
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002938const SCEV *
2939ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2940 const SmallVectorImpl<const SCEV *> &IndexExprs,
2941 bool InBounds) {
2942 // getSCEV(Base)->getType() has the same address space as Base->getType()
2943 // because SCEV::getType() preserves the address space.
2944 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2945 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2946 // instruction to its SCEV, because the Instruction may be guarded by control
2947 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002948 // context. This can be fixed similarly to how these flags are handled for
2949 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002950 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2951
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002952 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002953 // The address space is unimportant. The first thing we do on CurTy is getting
2954 // its element type.
2955 Type *CurTy = PointerType::getUnqual(PointeeType);
2956 for (const SCEV *IndexExpr : IndexExprs) {
2957 // Compute the (potentially symbolic) offset in bytes for this index.
2958 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2959 // For a struct, add the member offset.
2960 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2961 unsigned FieldNo = Index->getZExtValue();
2962 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2963
2964 // Add the field offset to the running total offset.
2965 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2966
2967 // Update CurTy to the type of the field at Index.
2968 CurTy = STy->getTypeAtIndex(Index);
2969 } else {
2970 // Update CurTy to its element type.
2971 CurTy = cast<SequentialType>(CurTy)->getElementType();
2972 // For an array, add the element offset, explicitly scaled.
2973 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2974 // Getelementptr indices are signed.
2975 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2976
2977 // Multiply the index by the element size to compute the element offset.
2978 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2979
2980 // Add the element offset to the running total offset.
2981 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2982 }
2983 }
2984
2985 // Add the total offset from all the GEP indices to the base.
2986 return getAddExpr(BaseExpr, TotalOffset, Wrap);
2987}
2988
Dan Gohmanabd17092009-06-24 14:49:00 +00002989const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2990 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002991 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002992 Ops.push_back(LHS);
2993 Ops.push_back(RHS);
2994 return getSMaxExpr(Ops);
2995}
2996
Dan Gohmanaf752342009-07-07 17:06:11 +00002997const SCEV *
2998ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002999 assert(!Ops.empty() && "Cannot get empty smax!");
3000 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003001#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003002 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003003 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003004 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003005 "SCEVSMaxExpr operand types don't match!");
3006#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003007
3008 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003009 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003010
3011 // If there are any constants, fold them together.
3012 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003013 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003014 ++Idx;
3015 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003016 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003017 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003018 ConstantInt *Fold = ConstantInt::get(
3019 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003020 Ops[0] = getConstant(Fold);
3021 Ops.erase(Ops.begin()+1); // Erase the folded element
3022 if (Ops.size() == 1) return Ops[0];
3023 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003024 }
3025
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003026 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003027 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3028 Ops.erase(Ops.begin());
3029 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003030 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3031 // If we have an smax with a constant maximum-int, it will always be
3032 // maximum-int.
3033 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003034 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003035
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003036 if (Ops.size() == 1) return Ops[0];
3037 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003038
3039 // Find the first SMax
3040 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3041 ++Idx;
3042
3043 // Check to see if one of the operands is an SMax. If so, expand its operands
3044 // onto our operand list, and recurse to simplify.
3045 if (Idx < Ops.size()) {
3046 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003047 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003048 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003049 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003050 DeletedSMax = true;
3051 }
3052
3053 if (DeletedSMax)
3054 return getSMaxExpr(Ops);
3055 }
3056
3057 // Okay, check to see if the same value occurs in the operand list twice. If
3058 // so, delete one. Since we sorted the list, these values are required to
3059 // be adjacent.
3060 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003061 // X smax Y smax Y --> X smax Y
3062 // X smax Y --> X, if X is always greater than Y
3063 if (Ops[i] == Ops[i+1] ||
3064 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3065 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3066 --i; --e;
3067 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003068 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3069 --i; --e;
3070 }
3071
3072 if (Ops.size() == 1) return Ops[0];
3073
3074 assert(!Ops.empty() && "Reduced smax down to nothing!");
3075
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003076 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003077 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003078 FoldingSetNodeID ID;
3079 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003080 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3081 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003082 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003084 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3085 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003086 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3087 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003088 UniqueSCEVs.InsertNode(S, IP);
3089 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003090}
3091
Dan Gohmanabd17092009-06-24 14:49:00 +00003092const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3093 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003094 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003095 Ops.push_back(LHS);
3096 Ops.push_back(RHS);
3097 return getUMaxExpr(Ops);
3098}
3099
Dan Gohmanaf752342009-07-07 17:06:11 +00003100const SCEV *
3101ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003102 assert(!Ops.empty() && "Cannot get empty umax!");
3103 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003104#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003105 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003106 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003107 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003108 "SCEVUMaxExpr operand types don't match!");
3109#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003110
3111 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003112 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003113
3114 // If there are any constants, fold them together.
3115 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003116 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003117 ++Idx;
3118 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003119 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003120 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003121 ConstantInt *Fold = ConstantInt::get(
3122 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003123 Ops[0] = getConstant(Fold);
3124 Ops.erase(Ops.begin()+1); // Erase the folded element
3125 if (Ops.size() == 1) return Ops[0];
3126 LHSC = cast<SCEVConstant>(Ops[0]);
3127 }
3128
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003129 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003130 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3131 Ops.erase(Ops.begin());
3132 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003133 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3134 // If we have an umax with a constant maximum-int, it will always be
3135 // maximum-int.
3136 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003137 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003138
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003139 if (Ops.size() == 1) return Ops[0];
3140 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003141
3142 // Find the first UMax
3143 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3144 ++Idx;
3145
3146 // Check to see if one of the operands is a UMax. If so, expand its operands
3147 // onto our operand list, and recurse to simplify.
3148 if (Idx < Ops.size()) {
3149 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003150 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003151 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003152 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003153 DeletedUMax = true;
3154 }
3155
3156 if (DeletedUMax)
3157 return getUMaxExpr(Ops);
3158 }
3159
3160 // Okay, check to see if the same value occurs in the operand list twice. If
3161 // so, delete one. Since we sorted the list, these values are required to
3162 // be adjacent.
3163 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003164 // X umax Y umax Y --> X umax Y
3165 // X umax Y --> X, if X is always greater than Y
3166 if (Ops[i] == Ops[i+1] ||
3167 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3168 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3169 --i; --e;
3170 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003171 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3172 --i; --e;
3173 }
3174
3175 if (Ops.size() == 1) return Ops[0];
3176
3177 assert(!Ops.empty() && "Reduced umax down to nothing!");
3178
3179 // Okay, it looks like we really DO need a umax expr. Check to see if we
3180 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003181 FoldingSetNodeID ID;
3182 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003183 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3184 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003185 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003186 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003187 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3188 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003189 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3190 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003191 UniqueSCEVs.InsertNode(S, IP);
3192 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003193}
3194
Dan Gohmanabd17092009-06-24 14:49:00 +00003195const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3196 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003197 // ~smax(~x, ~y) == smin(x, y).
3198 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3199}
3200
Dan Gohmanabd17092009-06-24 14:49:00 +00003201const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3202 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003203 // ~umax(~x, ~y) == umin(x, y)
3204 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3205}
3206
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003207const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003208 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003209 // constant expression and then folding it back into a ConstantInt.
3210 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003211 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003212}
3213
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003214const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3215 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003216 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003217 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003218 // constant expression and then folding it back into a ConstantInt.
3219 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003220 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003221 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003222}
3223
Dan Gohmanaf752342009-07-07 17:06:11 +00003224const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003225 // Don't attempt to do anything other than create a SCEVUnknown object
3226 // here. createSCEV only calls getUnknown after checking for all other
3227 // interesting possibilities, and any other code that calls getUnknown
3228 // is doing so in order to hide a value from SCEV canonicalization.
3229
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003230 FoldingSetNodeID ID;
3231 ID.AddInteger(scUnknown);
3232 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003233 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003234 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3235 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3236 "Stale SCEVUnknown in uniquing map!");
3237 return S;
3238 }
3239 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3240 FirstUnknown);
3241 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003242 UniqueSCEVs.InsertNode(S, IP);
3243 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003244}
3245
Chris Lattnerd934c702004-04-02 20:23:17 +00003246//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003247// Basic SCEV Analysis and PHI Idiom Recognition Code
3248//
3249
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003250/// isSCEVable - Test if values of the given type are analyzable within
3251/// the SCEV framework. This primarily includes integer types, and it
3252/// can optionally include pointer types if the ScalarEvolution class
3253/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003254bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003255 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003256 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003257}
3258
3259/// getTypeSizeInBits - Return the size in bits of the specified type,
3260/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003261uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003262 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003263 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003264}
3265
3266/// getEffectiveSCEVType - Return a type with the same bitwidth as
3267/// the given type and which represents how SCEV will treat the given
3268/// type, for which isSCEVable must return true. For pointer types,
3269/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003270Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003271 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3272
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003273 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003274 return Ty;
3275
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003276 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003277 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003278 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003279}
Chris Lattnerd934c702004-04-02 20:23:17 +00003280
Dan Gohmanaf752342009-07-07 17:06:11 +00003281const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003282 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003283}
3284
Sanjoy Das7d752672015-12-08 04:32:54 +00003285
3286bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003287 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3288 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3289 // is set iff if find such SCEVUnknown.
3290 //
3291 struct FindInvalidSCEVUnknown {
3292 bool FindOne;
3293 FindInvalidSCEVUnknown() { FindOne = false; }
3294 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003295 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003296 case scConstant:
3297 return false;
3298 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003299 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003300 FindOne = true;
3301 return false;
3302 default:
3303 return true;
3304 }
3305 }
3306 bool isDone() const { return FindOne; }
3307 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003308
Shuxin Yangefc4c012013-07-08 17:33:13 +00003309 FindInvalidSCEVUnknown F;
3310 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3311 ST.visitAll(S);
3312
3313 return !F.FindOne;
3314}
3315
Wei Mia49559b2016-02-04 01:27:38 +00003316namespace {
3317// Helper class working with SCEVTraversal to figure out if a SCEV contains
3318// a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set
3319// iff if such sub scAddRecExpr type SCEV is found.
3320struct FindAddRecurrence {
3321 bool FoundOne;
3322 FindAddRecurrence() : FoundOne(false) {}
3323
3324 bool follow(const SCEV *S) {
3325 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3326 case scAddRecExpr:
3327 FoundOne = true;
3328 case scConstant:
3329 case scUnknown:
3330 case scCouldNotCompute:
3331 return false;
3332 default:
3333 return true;
3334 }
3335 }
3336 bool isDone() const { return FoundOne; }
3337};
3338}
3339
3340bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3341 HasRecMapType::iterator I = HasRecMap.find_as(S);
3342 if (I != HasRecMap.end())
3343 return I->second;
3344
3345 FindAddRecurrence F;
3346 SCEVTraversal<FindAddRecurrence> ST(F);
3347 ST.visitAll(S);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003348 HasRecMap.insert({S, F.FoundOne});
Wei Mia49559b2016-02-04 01:27:38 +00003349 return F.FoundOne;
3350}
3351
3352/// getSCEVValues - Return the Value set from S.
3353SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3354 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3355 if (SI == ExprValueMap.end())
3356 return nullptr;
3357#ifndef NDEBUG
3358 if (VerifySCEVMap) {
3359 // Check there is no dangling Value in the set returned.
3360 for (const auto &VE : SI->second)
3361 assert(ValueExprMap.count(VE));
3362 }
3363#endif
3364 return &SI->second;
3365}
3366
3367/// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap.
3368/// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S),
3369/// eraseValueFromMap should be used instead to ensure whenever V->S is removed
3370/// from ValueExprMap, V is also removed from the set of ExprValueMap[S].
3371void ScalarEvolution::eraseValueFromMap(Value *V) {
3372 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3373 if (I != ValueExprMap.end()) {
3374 const SCEV *S = I->second;
3375 SetVector<Value *> *SV = getSCEVValues(S);
3376 // Remove V from the set of ExprValueMap[S]
3377 if (SV)
3378 SV->remove(V);
3379 ValueExprMap.erase(V);
3380 }
3381}
3382
Chris Lattnerd934c702004-04-02 20:23:17 +00003383/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3384/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003385const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003386 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003387
Jingyue Wu42f1d672015-07-28 18:22:40 +00003388 const SCEV *S = getExistingSCEV(V);
3389 if (S == nullptr) {
3390 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003391 // During PHI resolution, it is possible to create two SCEVs for the same
3392 // V, so it is needed to double check whether V->S is inserted into
3393 // ValueExprMap before insert S->V into ExprValueMap.
3394 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003395 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mia49559b2016-02-04 01:27:38 +00003396 if (Pair.second)
3397 ExprValueMap[S].insert(V);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003398 }
3399 return S;
3400}
3401
3402const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3403 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3404
Shuxin Yangefc4c012013-07-08 17:33:13 +00003405 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3406 if (I != ValueExprMap.end()) {
3407 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003408 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003409 return S;
Wei Mia49559b2016-02-04 01:27:38 +00003410 forgetMemoizedResults(S);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003411 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003412 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003413 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003414}
3415
Dan Gohman0a40ad92009-04-16 03:18:22 +00003416/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3417///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003418const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3419 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003420 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003421 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003422 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003423
Chris Lattner229907c2011-07-18 04:54:35 +00003424 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003425 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003426 return getMulExpr(
3427 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003428}
3429
3430/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003431const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003432 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003433 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003434 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003435
Chris Lattner229907c2011-07-18 04:54:35 +00003436 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003437 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003438 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003439 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003440 return getMinusSCEV(AllOnes, V);
3441}
3442
Andrew Trick8b55b732011-03-14 16:50:06 +00003443/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003444const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003445 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003446 // Fast path: X - X --> 0.
3447 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003448 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003449
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003450 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3451 // makes it so that we cannot make much use of NUW.
3452 auto AddFlags = SCEV::FlagAnyWrap;
3453 const bool RHSIsNotMinSigned =
3454 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3455 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3456 // Let M be the minimum representable signed value. Then (-1)*RHS
3457 // signed-wraps if and only if RHS is M. That can happen even for
3458 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3459 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3460 // (-1)*RHS, we need to prove that RHS != M.
3461 //
3462 // If LHS is non-negative and we know that LHS - RHS does not
3463 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3464 // either by proving that RHS > M or that LHS >= 0.
3465 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3466 AddFlags = SCEV::FlagNSW;
3467 }
3468 }
3469
3470 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3471 // RHS is NSW and LHS >= 0.
3472 //
3473 // The difficulty here is that the NSW flag may have been proven
3474 // relative to a loop that is to be found in a recurrence in LHS and
3475 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3476 // larger scope than intended.
3477 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3478
3479 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003480}
3481
3482/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3483/// input value to the specified type. If the type must be extended, it is zero
3484/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003485const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003486ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3487 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003488 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3489 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003490 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003491 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003492 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003493 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003494 return getTruncateExpr(V, Ty);
3495 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003496}
3497
3498/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3499/// input value to the specified type. If the type must be extended, it is sign
3500/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003501const SCEV *
3502ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003503 Type *Ty) {
3504 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003505 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3506 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003507 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003508 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003509 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003510 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003511 return getTruncateExpr(V, Ty);
3512 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003513}
3514
Dan Gohmane712a2f2009-05-13 03:46:30 +00003515/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3516/// input value to the specified type. If the type must be extended, it is zero
3517/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003518const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003519ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3520 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003521 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3522 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003523 "Cannot noop or zero extend with non-integer arguments!");
3524 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3525 "getNoopOrZeroExtend cannot truncate!");
3526 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3527 return V; // No conversion
3528 return getZeroExtendExpr(V, Ty);
3529}
3530
3531/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3532/// input value to the specified type. If the type must be extended, it is sign
3533/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003534const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003535ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3536 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003537 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3538 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003539 "Cannot noop or sign extend with non-integer arguments!");
3540 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3541 "getNoopOrSignExtend cannot truncate!");
3542 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3543 return V; // No conversion
3544 return getSignExtendExpr(V, Ty);
3545}
3546
Dan Gohman8db2edc2009-06-13 15:56:47 +00003547/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3548/// the input value to the specified type. If the type must be extended,
3549/// it is extended with unspecified bits. The conversion must not be
3550/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003551const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003552ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3553 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003554 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3555 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003556 "Cannot noop or any extend with non-integer arguments!");
3557 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3558 "getNoopOrAnyExtend cannot truncate!");
3559 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3560 return V; // No conversion
3561 return getAnyExtendExpr(V, Ty);
3562}
3563
Dan Gohmane712a2f2009-05-13 03:46:30 +00003564/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3565/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003566const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003567ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3568 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003569 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3570 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003571 "Cannot truncate or noop with non-integer arguments!");
3572 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3573 "getTruncateOrNoop cannot extend!");
3574 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3575 return V; // No conversion
3576 return getTruncateExpr(V, Ty);
3577}
3578
Dan Gohman96212b62009-06-22 00:31:57 +00003579/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3580/// the types using zero-extension, and then perform a umax operation
3581/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003582const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3583 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003584 const SCEV *PromotedLHS = LHS;
3585 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003586
3587 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3588 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3589 else
3590 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3591
3592 return getUMaxExpr(PromotedLHS, PromotedRHS);
3593}
3594
Dan Gohman2bc22302009-06-22 15:03:27 +00003595/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3596/// the types using zero-extension, and then perform a umin operation
3597/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003598const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3599 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003600 const SCEV *PromotedLHS = LHS;
3601 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003602
3603 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3604 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3605 else
3606 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3607
3608 return getUMinExpr(PromotedLHS, PromotedRHS);
3609}
3610
Andrew Trick87716c92011-03-17 23:51:11 +00003611/// getPointerBase - Transitively follow the chain of pointer-type operands
3612/// until reaching a SCEV that does not have a single pointer operand. This
3613/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3614/// but corner cases do exist.
3615const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3616 // A pointer operand may evaluate to a nonpointer expression, such as null.
3617 if (!V->getType()->isPointerTy())
3618 return V;
3619
3620 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3621 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003622 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003623 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003624 for (const SCEV *NAryOp : NAry->operands()) {
3625 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003626 // Cannot find the base of an expression with multiple pointer operands.
3627 if (PtrOp)
3628 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003629 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003630 }
3631 }
3632 if (!PtrOp)
3633 return V;
3634 return getPointerBase(PtrOp);
3635 }
3636 return V;
3637}
3638
Dan Gohman0b89dff2009-07-25 01:13:03 +00003639/// PushDefUseChildren - Push users of the given Instruction
3640/// onto the given Worklist.
3641static void
3642PushDefUseChildren(Instruction *I,
3643 SmallVectorImpl<Instruction *> &Worklist) {
3644 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003645 for (User *U : I->users())
3646 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003647}
3648
3649/// ForgetSymbolicValue - This looks up computed SCEV values for all
3650/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003651/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003652/// resolution.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003653void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003654 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003655 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003656
Dan Gohman0b89dff2009-07-25 01:13:03 +00003657 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003658 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003659 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003660 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003661 if (!Visited.insert(I).second)
3662 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003663
Sanjoy Das63914592015-10-18 00:29:20 +00003664 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003665 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003666 const SCEV *Old = It->second;
3667
Dan Gohman0b89dff2009-07-25 01:13:03 +00003668 // Short-circuit the def-use traversal if the symbolic name
3669 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003670 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003671 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003672
Dan Gohman0b89dff2009-07-25 01:13:03 +00003673 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003674 // structure, it's a PHI that's in the progress of being computed
3675 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3676 // additional loop trip count information isn't going to change anything.
3677 // In the second case, createNodeForPHI will perform the necessary
3678 // updates on its own when it gets to that point. In the third, we do
3679 // want to forget the SCEVUnknown.
3680 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003681 !isa<SCEVUnknown>(Old) ||
3682 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003683 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003684 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003685 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003686 }
3687
3688 PushDefUseChildren(I, Worklist);
3689 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003690}
Chris Lattnerd934c702004-04-02 20:23:17 +00003691
Benjamin Kramer83709b12015-11-16 09:01:28 +00003692namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003693class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3694public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003695 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003696 ScalarEvolution &SE) {
3697 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003698 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003699 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3700 }
3701
3702 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3703 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3704
3705 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3706 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3707 Valid = false;
3708 return Expr;
3709 }
3710
3711 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3712 // Only allow AddRecExprs for this loop.
3713 if (Expr->getLoop() == L)
3714 return Expr->getStart();
3715 Valid = false;
3716 return Expr;
3717 }
3718
3719 bool isValid() { return Valid; }
3720
3721private:
3722 const Loop *L;
3723 bool Valid;
3724};
3725
3726class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3727public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003728 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003729 ScalarEvolution &SE) {
3730 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003731 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003732 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3733 }
3734
3735 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3736 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3737
3738 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3739 // Only allow AddRecExprs for this loop.
3740 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3741 Valid = false;
3742 return Expr;
3743 }
3744
3745 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3746 if (Expr->getLoop() == L && Expr->isAffine())
3747 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3748 Valid = false;
3749 return Expr;
3750 }
3751 bool isValid() { return Valid; }
3752
3753private:
3754 const Loop *L;
3755 bool Valid;
3756};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003757} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003758
Sanjoy Das55015d22015-10-02 23:09:44 +00003759const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3760 const Loop *L = LI.getLoopFor(PN->getParent());
3761 if (!L || L->getHeader() != PN->getParent())
3762 return nullptr;
3763
3764 // The loop may have multiple entrances or multiple exits; we can analyze
3765 // this phi as an addrec if it has a unique entry value and a unique
3766 // backedge value.
3767 Value *BEValueV = nullptr, *StartValueV = nullptr;
3768 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3769 Value *V = PN->getIncomingValue(i);
3770 if (L->contains(PN->getIncomingBlock(i))) {
3771 if (!BEValueV) {
3772 BEValueV = V;
3773 } else if (BEValueV != V) {
3774 BEValueV = nullptr;
3775 break;
3776 }
3777 } else if (!StartValueV) {
3778 StartValueV = V;
3779 } else if (StartValueV != V) {
3780 StartValueV = nullptr;
3781 break;
3782 }
3783 }
3784 if (BEValueV && StartValueV) {
3785 // While we are analyzing this PHI node, handle its value symbolically.
3786 const SCEV *SymbolicName = getUnknown(PN);
3787 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3788 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003789 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003790
3791 // Using this symbolic name for the PHI, analyze the value coming around
3792 // the back-edge.
3793 const SCEV *BEValue = getSCEV(BEValueV);
3794
3795 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3796 // has a special value for the first iteration of the loop.
3797
3798 // If the value coming around the backedge is an add with the symbolic
3799 // value we just inserted, then we found a simple induction variable!
3800 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3801 // If there is a single occurrence of the symbolic value, replace it
3802 // with a recurrence.
3803 unsigned FoundIndex = Add->getNumOperands();
3804 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3805 if (Add->getOperand(i) == SymbolicName)
3806 if (FoundIndex == e) {
3807 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00003808 break;
3809 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003810
3811 if (FoundIndex != Add->getNumOperands()) {
3812 // Create an add with everything but the specified operand.
3813 SmallVector<const SCEV *, 8> Ops;
3814 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3815 if (i != FoundIndex)
3816 Ops.push_back(Add->getOperand(i));
3817 const SCEV *Accum = getAddExpr(Ops);
3818
3819 // This is not a valid addrec if the step amount is varying each
3820 // loop iteration, but is not itself an addrec in this loop.
3821 if (isLoopInvariant(Accum, L) ||
3822 (isa<SCEVAddRecExpr>(Accum) &&
3823 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3824 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3825
3826 // If the increment doesn't overflow, then neither the addrec nor
3827 // the post-increment will overflow.
3828 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3829 if (OBO->getOperand(0) == PN) {
3830 if (OBO->hasNoUnsignedWrap())
3831 Flags = setFlags(Flags, SCEV::FlagNUW);
3832 if (OBO->hasNoSignedWrap())
3833 Flags = setFlags(Flags, SCEV::FlagNSW);
3834 }
3835 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3836 // If the increment is an inbounds GEP, then we know the address
3837 // space cannot be wrapped around. We cannot make any guarantee
3838 // about signed or unsigned overflow because pointers are
3839 // unsigned but we may have a negative index from the base
3840 // pointer. We can guarantee that no unsigned wrap occurs if the
3841 // indices form a positive value.
3842 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3843 Flags = setFlags(Flags, SCEV::FlagNW);
3844
3845 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3846 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3847 Flags = setFlags(Flags, SCEV::FlagNUW);
3848 }
3849
3850 // We cannot transfer nuw and nsw flags from subtraction
3851 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3852 // for instance.
3853 }
3854
3855 const SCEV *StartVal = getSCEV(StartValueV);
3856 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3857
3858 // Since the no-wrap flags are on the increment, they apply to the
3859 // post-incremented value as well.
3860 if (isLoopInvariant(Accum, L))
3861 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
3862
3863 // Okay, for the entire analysis of this edge we assumed the PHI
3864 // to be symbolic. We now need to go back and purge all of the
3865 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003866 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00003867 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3868 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00003869 }
3870 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00003871 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00003872 // Otherwise, this could be a loop like this:
3873 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3874 // In this case, j = {1,+,1} and BEValue is j.
3875 // Because the other in-value of i (0) fits the evolution of BEValue
3876 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00003877 //
3878 // We can generalize this saying that i is the shifted value of BEValue
3879 // by one iteration:
3880 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
3881 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
3882 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
3883 if (Shifted != getCouldNotCompute() &&
3884 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003885 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003886 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003887 // Okay, for the entire analysis of this edge we assumed the PHI
3888 // to be symbolic. We now need to go back and purge all of the
3889 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003890 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003891 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
3892 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00003893 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003894 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003895 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00003896
3897 // Remove the temporary PHI node SCEV that has been inserted while intending
3898 // to create an AddRecExpr for this PHI node. We can not keep this temporary
3899 // as it will prevent later (possibly simpler) SCEV expressions to be added
3900 // to the ValueExprMap.
3901 ValueExprMap.erase(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00003902 }
3903
3904 return nullptr;
3905}
3906
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003907// Checks if the SCEV S is available at BB. S is considered available at BB
3908// if S can be materialized at BB without introducing a fault.
3909static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
3910 BasicBlock *BB) {
3911 struct CheckAvailable {
3912 bool TraversalDone = false;
3913 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003914
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003915 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
3916 BasicBlock *BB = nullptr;
3917 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00003918
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003919 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
3920 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00003921
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003922 bool setUnavailable() {
3923 TraversalDone = true;
3924 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003925 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003926 }
3927
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003928 bool follow(const SCEV *S) {
3929 switch (S->getSCEVType()) {
3930 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
3931 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00003932 // These expressions are available if their operand(s) is/are.
3933 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003934
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003935 case scAddRecExpr: {
3936 // We allow add recurrences that are on the loop BB is in, or some
3937 // outer loop. This guarantees availability because the value of the
3938 // add recurrence at BB is simply the "current" value of the induction
3939 // variable. We can relax this in the future; for instance an add
3940 // recurrence on a sibling dominating loop is also available at BB.
3941 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
3942 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00003943 return true;
3944
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003945 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00003946 }
3947
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003948 case scUnknown: {
3949 // For SCEVUnknown, we check for simple dominance.
3950 const auto *SU = cast<SCEVUnknown>(S);
3951 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00003952
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003953 if (isa<Argument>(V))
3954 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003955
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003956 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
3957 return false;
3958
3959 return setUnavailable();
3960 }
3961
3962 case scUDivExpr:
3963 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003964 // We do not try to smart about these at all.
3965 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003966 }
3967 llvm_unreachable("switch should be fully covered!");
3968 }
3969
3970 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00003971 };
3972
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003973 CheckAvailable CA(L, BB, DT);
3974 SCEVTraversal<CheckAvailable> ST(CA);
3975
3976 ST.visitAll(S);
3977 return CA.Available;
3978}
3979
3980// Try to match a control flow sequence that branches out at BI and merges back
3981// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
3982// match.
3983static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
3984 Value *&C, Value *&LHS, Value *&RHS) {
3985 C = BI->getCondition();
3986
3987 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
3988 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
3989
3990 if (!LeftEdge.isSingleEdge())
3991 return false;
3992
3993 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
3994
3995 Use &LeftUse = Merge->getOperandUse(0);
3996 Use &RightUse = Merge->getOperandUse(1);
3997
3998 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
3999 LHS = LeftUse;
4000 RHS = RightUse;
4001 return true;
4002 }
4003
4004 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4005 LHS = RightUse;
4006 RHS = LeftUse;
4007 return true;
4008 }
4009
4010 return false;
4011}
4012
4013const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004014 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004015 const Loop *L = LI.getLoopFor(PN->getParent());
4016
Sanjoy Das337d4782015-10-31 23:21:40 +00004017 // We don't want to break LCSSA, even in a SCEV expression tree.
4018 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4019 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4020 return nullptr;
4021
Sanjoy Das55015d22015-10-02 23:09:44 +00004022 // Try to match
4023 //
4024 // br %cond, label %left, label %right
4025 // left:
4026 // br label %merge
4027 // right:
4028 // br label %merge
4029 // merge:
4030 // V = phi [ %x, %left ], [ %y, %right ]
4031 //
4032 // as "select %cond, %x, %y"
4033
4034 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4035 assert(IDom && "At least the entry block should dominate PN");
4036
4037 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4038 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4039
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004040 if (BI && BI->isConditional() &&
4041 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4042 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4043 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004044 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4045 }
4046
4047 return nullptr;
4048}
4049
4050const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4051 if (const SCEV *S = createAddRecFromPHI(PN))
4052 return S;
4053
4054 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4055 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004056
Dan Gohmana9c205c2010-02-25 06:57:05 +00004057 // If the PHI has a single incoming value, follow that value, unless the
4058 // PHI's incoming blocks are in a different loop, in which case doing so
4059 // risks breaking LCSSA form. Instcombine would normally zap these, but
4060 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004061 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004062 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004063 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004064
Chris Lattnerd934c702004-04-02 20:23:17 +00004065 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004066 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004067}
4068
Sanjoy Das55015d22015-10-02 23:09:44 +00004069const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4070 Value *Cond,
4071 Value *TrueVal,
4072 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004073 // Handle "constant" branch or select. This can occur for instance when a
4074 // loop pass transforms an inner loop and moves on to process the outer loop.
4075 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4076 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4077
Sanjoy Dasd0671342015-10-02 19:39:59 +00004078 // Try to match some simple smax or umax patterns.
4079 auto *ICI = dyn_cast<ICmpInst>(Cond);
4080 if (!ICI)
4081 return getUnknown(I);
4082
4083 Value *LHS = ICI->getOperand(0);
4084 Value *RHS = ICI->getOperand(1);
4085
4086 switch (ICI->getPredicate()) {
4087 case ICmpInst::ICMP_SLT:
4088 case ICmpInst::ICMP_SLE:
4089 std::swap(LHS, RHS);
4090 // fall through
4091 case ICmpInst::ICMP_SGT:
4092 case ICmpInst::ICMP_SGE:
4093 // a >s b ? a+x : b+x -> smax(a, b)+x
4094 // a >s b ? b+x : a+x -> smin(a, b)+x
4095 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4096 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4097 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4098 const SCEV *LA = getSCEV(TrueVal);
4099 const SCEV *RA = getSCEV(FalseVal);
4100 const SCEV *LDiff = getMinusSCEV(LA, LS);
4101 const SCEV *RDiff = getMinusSCEV(RA, RS);
4102 if (LDiff == RDiff)
4103 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4104 LDiff = getMinusSCEV(LA, RS);
4105 RDiff = getMinusSCEV(RA, LS);
4106 if (LDiff == RDiff)
4107 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4108 }
4109 break;
4110 case ICmpInst::ICMP_ULT:
4111 case ICmpInst::ICMP_ULE:
4112 std::swap(LHS, RHS);
4113 // fall through
4114 case ICmpInst::ICMP_UGT:
4115 case ICmpInst::ICMP_UGE:
4116 // a >u b ? a+x : b+x -> umax(a, b)+x
4117 // a >u b ? b+x : a+x -> umin(a, b)+x
4118 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4119 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4120 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4121 const SCEV *LA = getSCEV(TrueVal);
4122 const SCEV *RA = getSCEV(FalseVal);
4123 const SCEV *LDiff = getMinusSCEV(LA, LS);
4124 const SCEV *RDiff = getMinusSCEV(RA, RS);
4125 if (LDiff == RDiff)
4126 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4127 LDiff = getMinusSCEV(LA, RS);
4128 RDiff = getMinusSCEV(RA, LS);
4129 if (LDiff == RDiff)
4130 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4131 }
4132 break;
4133 case ICmpInst::ICMP_NE:
4134 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4135 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4136 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4137 const SCEV *One = getOne(I->getType());
4138 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4139 const SCEV *LA = getSCEV(TrueVal);
4140 const SCEV *RA = getSCEV(FalseVal);
4141 const SCEV *LDiff = getMinusSCEV(LA, LS);
4142 const SCEV *RDiff = getMinusSCEV(RA, One);
4143 if (LDiff == RDiff)
4144 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4145 }
4146 break;
4147 case ICmpInst::ICMP_EQ:
4148 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4149 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4150 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4151 const SCEV *One = getOne(I->getType());
4152 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4153 const SCEV *LA = getSCEV(TrueVal);
4154 const SCEV *RA = getSCEV(FalseVal);
4155 const SCEV *LDiff = getMinusSCEV(LA, One);
4156 const SCEV *RDiff = getMinusSCEV(RA, LS);
4157 if (LDiff == RDiff)
4158 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4159 }
4160 break;
4161 default:
4162 break;
4163 }
4164
4165 return getUnknown(I);
4166}
4167
Dan Gohmanee750d12009-05-08 20:26:55 +00004168/// createNodeForGEP - Expand GEP instructions into add and multiply
4169/// operations. This allows them to be analyzed by regular SCEV code.
4170///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004171const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004172 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004173 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004174 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004175
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004176 SmallVector<const SCEV *, 4> IndexExprs;
4177 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4178 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004179 return getGEPExpr(GEP->getSourceElementType(),
4180 getSCEV(GEP->getPointerOperand()),
4181 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004182}
4183
Nick Lewycky3783b462007-11-22 07:59:40 +00004184/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4185/// guaranteed to end in (at every loop iteration). It is, at the same time,
4186/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
4187/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004188uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004189ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004190 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004191 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004192
Dan Gohmana30370b2009-05-04 22:02:23 +00004193 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004194 return std::min(GetMinTrailingZeros(T->getOperand()),
4195 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004196
Dan Gohmana30370b2009-05-04 22:02:23 +00004197 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004198 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4199 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4200 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004201 }
4202
Dan Gohmana30370b2009-05-04 22:02:23 +00004203 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004204 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4205 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4206 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004207 }
4208
Dan Gohmana30370b2009-05-04 22:02:23 +00004209 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004210 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004211 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004212 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004213 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004214 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004215 }
4216
Dan Gohmana30370b2009-05-04 22:02:23 +00004217 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004218 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004219 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4220 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004221 for (unsigned i = 1, e = M->getNumOperands();
4222 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004223 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004224 BitWidth);
4225 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004226 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004227
Dan Gohmana30370b2009-05-04 22:02:23 +00004228 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004229 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004230 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004231 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004232 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004233 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004234 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004235
Dan Gohmana30370b2009-05-04 22:02:23 +00004236 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004237 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004238 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004239 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004240 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004241 return MinOpRes;
4242 }
4243
Dan Gohmana30370b2009-05-04 22:02:23 +00004244 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004245 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004246 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004247 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004248 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004249 return MinOpRes;
4250 }
4251
Dan Gohmanc702fc02009-06-19 23:29:04 +00004252 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4253 // For a SCEVUnknown, ask ValueTracking.
4254 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004255 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004256 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4257 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004258 return Zeros.countTrailingOnes();
4259 }
4260
4261 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004262 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004263}
Chris Lattnerd934c702004-04-02 20:23:17 +00004264
Sanjoy Das1f05c512014-10-10 21:22:34 +00004265/// GetRangeFromMetadata - Helper method to assign a range to V from
4266/// metadata present in the IR.
4267static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004268 if (Instruction *I = dyn_cast<Instruction>(V))
4269 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4270 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004271
4272 return None;
4273}
4274
Sanjoy Das91b54772015-03-09 21:43:43 +00004275/// getRange - Determine the range for a particular SCEV. If SignHint is
4276/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4277/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004278///
4279ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004280ScalarEvolution::getRange(const SCEV *S,
4281 ScalarEvolution::RangeSignHint SignHint) {
4282 DenseMap<const SCEV *, ConstantRange> &Cache =
4283 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4284 : SignedRanges;
4285
Dan Gohman761065e2010-11-17 02:44:44 +00004286 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004287 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4288 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004289 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004290
4291 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004292 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004293
Dan Gohman85be4332010-01-26 19:19:05 +00004294 unsigned BitWidth = getTypeSizeInBits(S->getType());
4295 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4296
Sanjoy Das91b54772015-03-09 21:43:43 +00004297 // If the value has known zeros, the maximum value will have those known zeros
4298 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004299 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004300 if (TZ != 0) {
4301 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4302 ConservativeResult =
4303 ConstantRange(APInt::getMinValue(BitWidth),
4304 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4305 else
4306 ConservativeResult = ConstantRange(
4307 APInt::getSignedMinValue(BitWidth),
4308 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4309 }
Dan Gohman85be4332010-01-26 19:19:05 +00004310
Dan Gohmane65c9172009-07-13 21:35:55 +00004311 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004312 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004313 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004314 X = X.add(getRange(Add->getOperand(i), SignHint));
4315 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004316 }
4317
4318 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004319 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004320 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004321 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4322 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004323 }
4324
4325 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004326 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004327 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004328 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4329 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004330 }
4331
4332 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004333 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004334 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004335 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4336 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004337 }
4338
4339 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004340 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4341 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4342 return setRange(UDiv, SignHint,
4343 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004344 }
4345
4346 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004347 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4348 return setRange(ZExt, SignHint,
4349 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004350 }
4351
4352 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004353 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4354 return setRange(SExt, SignHint,
4355 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004356 }
4357
4358 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004359 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4360 return setRange(Trunc, SignHint,
4361 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004362 }
4363
Dan Gohmane65c9172009-07-13 21:35:55 +00004364 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004365 // If there's no unsigned wrap, the value will never be less than its
4366 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004367 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004368 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004369 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004370 ConservativeResult = ConservativeResult.intersectWith(
4371 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004372
Dan Gohman51ad99d2010-01-21 02:09:26 +00004373 // If there's no signed wrap, and all the operands have the same sign or
4374 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004375 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004376 bool AllNonNeg = true;
4377 bool AllNonPos = true;
4378 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4379 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4380 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4381 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004382 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004383 ConservativeResult = ConservativeResult.intersectWith(
4384 ConstantRange(APInt(BitWidth, 0),
4385 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004386 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004387 ConservativeResult = ConservativeResult.intersectWith(
4388 ConstantRange(APInt::getSignedMinValue(BitWidth),
4389 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004390 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004391
4392 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004393 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00004394 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00004395 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004396 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4397 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004398
4399 // Check for overflow. This must be done with ConstantRange arithmetic
4400 // because we could be called from within the ScalarEvolution overflow
4401 // checking code.
4402
Dan Gohmane65c9172009-07-13 21:35:55 +00004403 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
Sanjoy Das91b54772015-03-09 21:43:43 +00004404 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4405 ConstantRange ZExtMaxBECountRange =
4406 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004407
4408 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00004409 const SCEV *Step = AddRec->getStepRecurrence(*this);
Sanjoy Das91b54772015-03-09 21:43:43 +00004410 ConstantRange StepSRange = getSignedRange(Step);
4411 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004412
Sanjoy Das91b54772015-03-09 21:43:43 +00004413 ConstantRange StartURange = getUnsignedRange(Start);
4414 ConstantRange EndURange =
4415 StartURange.add(MaxBECountRange.multiply(StepSRange));
Dan Gohmanf76210e2010-04-12 07:39:33 +00004416
Sanjoy Das91b54772015-03-09 21:43:43 +00004417 // Check for unsigned overflow.
4418 ConstantRange ZExtStartURange =
4419 StartURange.zextOrTrunc(BitWidth * 2 + 1);
4420 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4421 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4422 ZExtEndURange) {
4423 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4424 EndURange.getUnsignedMin());
4425 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4426 EndURange.getUnsignedMax());
4427 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4428 if (!IsFullRange)
4429 ConservativeResult =
4430 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4431 }
Dan Gohmanf76210e2010-04-12 07:39:33 +00004432
Sanjoy Das91b54772015-03-09 21:43:43 +00004433 ConstantRange StartSRange = getSignedRange(Start);
4434 ConstantRange EndSRange =
4435 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4436
4437 // Check for signed overflow. This must be done with ConstantRange
4438 // arithmetic because we could be called from within the ScalarEvolution
4439 // overflow checking code.
4440 ConstantRange SExtStartSRange =
4441 StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4442 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4443 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4444 SExtEndSRange) {
4445 APInt Min = APIntOps::smin(StartSRange.getSignedMin(),
4446 EndSRange.getSignedMin());
4447 APInt Max = APIntOps::smax(StartSRange.getSignedMax(),
4448 EndSRange.getSignedMax());
4449 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4450 if (!IsFullRange)
4451 ConservativeResult =
4452 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4453 }
Dan Gohmand261d272009-06-24 01:05:09 +00004454 }
Dan Gohmand261d272009-06-24 01:05:09 +00004455 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004456
Sanjoy Das91b54772015-03-09 21:43:43 +00004457 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004458 }
4459
Dan Gohmanc702fc02009-06-19 23:29:04 +00004460 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004461 // Check if the IR explicitly contains !range metadata.
4462 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4463 if (MDRange.hasValue())
4464 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4465
Sanjoy Das91b54772015-03-09 21:43:43 +00004466 // Split here to avoid paying the compile-time cost of calling both
4467 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4468 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004469 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004470 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4471 // For a SCEVUnknown, ask ValueTracking.
4472 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004473 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004474 if (Ones != ~Zeros + 1)
4475 ConservativeResult =
4476 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4477 } else {
4478 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4479 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004480 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004481 if (NS > 1)
4482 ConservativeResult = ConservativeResult.intersectWith(
4483 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4484 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004485 }
4486
4487 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004488 }
4489
Sanjoy Das91b54772015-03-09 21:43:43 +00004490 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004491}
4492
Jingyue Wu42f1d672015-07-28 18:22:40 +00004493SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004494 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004495 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4496
4497 // Return early if there are no flags to propagate to the SCEV.
4498 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4499 if (BinOp->hasNoUnsignedWrap())
4500 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4501 if (BinOp->hasNoSignedWrap())
4502 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4503 if (Flags == SCEV::FlagAnyWrap) {
4504 return SCEV::FlagAnyWrap;
4505 }
4506
4507 // Here we check that BinOp is in the header of the innermost loop
4508 // containing BinOp, since we only deal with instructions in the loop
4509 // header. The actual loop we need to check later will come from an add
4510 // recurrence, but getting that requires computing the SCEV of the operands,
4511 // which can be expensive. This check we can do cheaply to rule out some
4512 // cases early.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004513 Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004514 if (innermostContainingLoop == nullptr ||
4515 innermostContainingLoop->getHeader() != BinOp->getParent())
4516 return SCEV::FlagAnyWrap;
4517
4518 // Only proceed if we can prove that BinOp does not yield poison.
4519 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4520
4521 // At this point we know that if V is executed, then it does not wrap
4522 // according to at least one of NSW or NUW. If V is not executed, then we do
4523 // not know if the calculation that V represents would wrap. Multiple
4524 // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4525 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4526 // derived from other instructions that map to the same SCEV. We cannot make
4527 // that guarantee for cases where V is not executed. So we need to find the
4528 // loop that V is considered in relation to and prove that V is executed for
4529 // every iteration of that loop. That implies that the value that V
4530 // calculates does not wrap anywhere in the loop, so then we can apply the
4531 // flags to the SCEV.
4532 //
4533 // We check isLoopInvariant to disambiguate in case we are adding two
4534 // recurrences from different loops, so that we know which loop to prove
4535 // that V is executed in.
4536 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4537 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4538 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4539 const int OtherOpIndex = 1 - OpIndex;
4540 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4541 if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4542 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4543 return Flags;
4544 }
4545 }
4546 return SCEV::FlagAnyWrap;
4547}
4548
4549/// createSCEV - We know that there is no SCEV for the specified value. Analyze
4550/// the expression.
Chris Lattnerd934c702004-04-02 20:23:17 +00004551///
Dan Gohmanaf752342009-07-07 17:06:11 +00004552const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004553 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004554 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004555
Dan Gohman05e89732008-06-22 19:56:46 +00004556 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004557 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004558 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004559
4560 // Don't attempt to analyze instructions in blocks that aren't
4561 // reachable. Such instructions don't matter, and they aren't required
4562 // to obey basic rules for definitions dominating uses which this
4563 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004564 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004565 return getUnknown(V);
4566 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004567 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004568 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4569 return getConstant(CI);
4570 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004571 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004572 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4573 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004574 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004575 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004576
Dan Gohman80ca01c2009-07-17 20:47:02 +00004577 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004578 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004579 case Instruction::Add: {
4580 // The simple thing to do would be to just call getSCEV on both operands
4581 // and call getAddExpr with the result. However if we're looking at a
4582 // bunch of things all added together, this can be quite inefficient,
4583 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4584 // Instead, gather up all the operands and make a single getAddExpr call.
4585 // LLVM IR canonical form means we need only traverse the left operands.
4586 SmallVector<const SCEV *, 4> AddOps;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004587 for (Value *Op = U;; Op = U->getOperand(0)) {
4588 U = dyn_cast<Operator>(Op);
4589 unsigned Opcode = U ? U->getOpcode() : 0;
4590 if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) {
4591 assert(Op != V && "V should be an add");
4592 AddOps.push_back(getSCEV(Op));
Dan Gohman47308d52010-08-31 22:53:17 +00004593 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004594 }
4595
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004596 if (auto *OpSCEV = getExistingSCEV(U)) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004597 AddOps.push_back(OpSCEV);
4598 break;
4599 }
4600
4601 // If a NUW or NSW flag can be applied to the SCEV for this
4602 // addition, then compute the SCEV for this addition by itself
4603 // with a separate call to getAddExpr. We need to do that
4604 // instead of pushing the operands of the addition onto AddOps,
4605 // since the flags are only known to apply to this particular
4606 // addition - they may not apply to other additions that can be
4607 // formed with operands from AddOps.
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004608 const SCEV *RHS = getSCEV(U->getOperand(1));
4609 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4610 if (Flags != SCEV::FlagAnyWrap) {
4611 const SCEV *LHS = getSCEV(U->getOperand(0));
4612 if (Opcode == Instruction::Sub)
4613 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4614 else
4615 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4616 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004617 }
4618
Dan Gohman47308d52010-08-31 22:53:17 +00004619 if (Opcode == Instruction::Sub)
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004620 AddOps.push_back(getNegativeSCEV(RHS));
Dan Gohman47308d52010-08-31 22:53:17 +00004621 else
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004622 AddOps.push_back(RHS);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004623 }
Andrew Trickd25089f2011-11-29 02:16:38 +00004624 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004625 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004626
Dan Gohmane5fb1032010-08-16 16:03:49 +00004627 case Instruction::Mul: {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004628 SmallVector<const SCEV *, 4> MulOps;
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004629 for (Value *Op = U;; Op = U->getOperand(0)) {
4630 U = dyn_cast<Operator>(Op);
4631 if (!U || U->getOpcode() != Instruction::Mul) {
4632 assert(Op != V && "V should be a mul");
4633 MulOps.push_back(getSCEV(Op));
4634 break;
4635 }
4636
4637 if (auto *OpSCEV = getExistingSCEV(U)) {
4638 MulOps.push_back(OpSCEV);
4639 break;
4640 }
4641
4642 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4643 if (Flags != SCEV::FlagAnyWrap) {
4644 MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)),
4645 getSCEV(U->getOperand(1)), Flags));
4646 break;
4647 }
4648
Dan Gohmane5fb1032010-08-16 16:03:49 +00004649 MulOps.push_back(getSCEV(U->getOperand(1)));
4650 }
Dan Gohmane5fb1032010-08-16 16:03:49 +00004651 return getMulExpr(MulOps);
4652 }
Dan Gohman05e89732008-06-22 19:56:46 +00004653 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004654 return getUDivExpr(getSCEV(U->getOperand(0)),
4655 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004656 case Instruction::Sub:
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004657 return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)),
4658 getNoWrapFlagsFromUB(U));
Dan Gohman0ec05372009-04-21 02:26:00 +00004659 case Instruction::And:
4660 // For an expression like x&255 that merely masks off the high bits,
4661 // use zext(trunc(x)) as the SCEV expression.
4662 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004663 if (CI->isNullValue())
4664 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004665 if (CI->isAllOnesValue())
4666 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004667 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004668
4669 // Instcombine's ShrinkDemandedConstant may strip bits out of
4670 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004671 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004672 // knew about to reconstruct a low-bits mask value.
4673 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004674 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004675 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004676 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004677 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, getDataLayout(),
4678 0, &AC, nullptr, &DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004679
Nick Lewycky31eaca52014-01-27 10:04:03 +00004680 APInt EffectiveMask =
4681 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4682 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4683 const SCEV *MulCount = getConstant(
4684 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4685 return getMulExpr(
4686 getZeroExtendExpr(
4687 getTruncateExpr(
4688 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4689 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4690 U->getType()),
4691 MulCount);
4692 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004693 }
4694 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004695
Dan Gohman05e89732008-06-22 19:56:46 +00004696 case Instruction::Or:
4697 // If the RHS of the Or is a constant, we may have something like:
4698 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4699 // optimizations will transparently handle this case.
4700 //
4701 // In order for this transformation to be safe, the LHS must be of the
4702 // form X*(2^n) and the Or constant must be less than 2^n.
4703 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004704 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004705 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004706 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004707 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4708 // Build a plain add SCEV.
4709 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4710 // If the LHS of the add was an addrec and it has no-wrap flags,
4711 // transfer the no-wrap flags, since an or won't introduce a wrap.
4712 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4713 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004714 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4715 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004716 }
4717 return S;
4718 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004719 }
Dan Gohman05e89732008-06-22 19:56:46 +00004720 break;
4721 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004722 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004723 // If the RHS of the xor is a signbit, then this is just an add.
4724 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004725 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004726 return getAddExpr(getSCEV(U->getOperand(0)),
4727 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004728
4729 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004730 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004731 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004732
4733 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4734 // This is a variant of the check for xor with -1, and it handles
4735 // the case where instcombine has trimmed non-demanded bits out
4736 // of an xor with -1.
4737 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4738 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4739 if (BO->getOpcode() == Instruction::And &&
4740 LCI->getValue() == CI->getValue())
4741 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004742 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004743 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004744 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004745 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004746 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4747
Dan Gohman8b0a4192010-03-01 17:49:51 +00004748 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004749 // mask off the high bits. Complement the operand and
4750 // re-apply the zext.
4751 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4752 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4753
4754 // If C is a single bit, it may be in the sign-bit position
4755 // before the zero-extend. In this case, represent the xor
4756 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004757 APInt Trunc = CI->getValue().trunc(Z0TySize);
4758 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004759 Trunc.isSignBit())
4760 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4761 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004762 }
Dan Gohman05e89732008-06-22 19:56:46 +00004763 }
4764 break;
4765
4766 case Instruction::Shl:
4767 // Turn shift left of a constant amount into a multiply.
4768 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004769 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004770
4771 // If the shift count is not less than the bitwidth, the result of
4772 // the shift is undefined. Don't try to analyze it, because the
4773 // resolution chosen here may differ from the resolution chosen in
4774 // other parts of the compiler.
4775 if (SA->getValue().uge(BitWidth))
4776 break;
4777
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004778 // It is currently not resolved how to interpret NSW for left
4779 // shift by BitWidth - 1, so we avoid applying flags in that
4780 // case. Remove this check (or this comment) once the situation
4781 // is resolved. See
4782 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
4783 // and http://reviews.llvm.org/D8890 .
4784 auto Flags = SCEV::FlagAnyWrap;
4785 if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U);
4786
Owen Andersonedb4a702009-07-24 23:12:02 +00004787 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004788 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004789 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00004790 }
4791 break;
4792
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004793 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004794 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004795 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004796 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004797
4798 // If the shift count is not less than the bitwidth, the result of
4799 // the shift is undefined. Don't try to analyze it, because the
4800 // resolution chosen here may differ from the resolution chosen in
4801 // other parts of the compiler.
4802 if (SA->getValue().uge(BitWidth))
4803 break;
4804
Owen Andersonedb4a702009-07-24 23:12:02 +00004805 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004806 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004807 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004808 }
4809 break;
4810
Dan Gohman0ec05372009-04-21 02:26:00 +00004811 case Instruction::AShr:
4812 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4813 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004814 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004815 if (L->getOpcode() == Instruction::Shl &&
4816 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004817 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4818
4819 // If the shift count is not less than the bitwidth, the result of
4820 // the shift is undefined. Don't try to analyze it, because the
4821 // resolution chosen here may differ from the resolution chosen in
4822 // other parts of the compiler.
4823 if (CI->getValue().uge(BitWidth))
4824 break;
4825
Dan Gohmandf199482009-04-25 17:05:40 +00004826 uint64_t Amt = BitWidth - CI->getZExtValue();
4827 if (Amt == BitWidth)
4828 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004829 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004830 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004831 IntegerType::get(getContext(),
4832 Amt)),
4833 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004834 }
4835 break;
4836
Dan Gohman05e89732008-06-22 19:56:46 +00004837 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004838 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004839
4840 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004841 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004842
4843 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004844 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004845
4846 case Instruction::BitCast:
4847 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004848 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004849 return getSCEV(U->getOperand(0));
4850 break;
4851
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004852 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4853 // lead to pointer expressions which cannot safely be expanded to GEPs,
4854 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4855 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004856
Dan Gohmanee750d12009-05-08 20:26:55 +00004857 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004858 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004859
Dan Gohman05e89732008-06-22 19:56:46 +00004860 case Instruction::PHI:
4861 return createNodeForPHI(cast<PHINode>(U));
4862
4863 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00004864 // U can also be a select constant expr, which let fall through. Since
4865 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
4866 // constant expressions cannot have instructions as operands, we'd have
4867 // returned getUnknown for a select constant expressions anyway.
4868 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00004869 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
4870 U->getOperand(1), U->getOperand(2));
Dan Gohman05e89732008-06-22 19:56:46 +00004871
4872 default: // We cannot analyze this expression.
4873 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004874 }
4875
Dan Gohmanc8e23622009-04-21 23:15:49 +00004876 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004877}
4878
4879
4880
4881//===----------------------------------------------------------------------===//
4882// Iteration Count Computation Code
4883//
4884
Chandler Carruth6666c272014-10-11 00:12:11 +00004885unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4886 if (BasicBlock *ExitingBB = L->getExitingBlock())
4887 return getSmallConstantTripCount(L, ExitingBB);
4888
4889 // No trip count information for multiple exits.
4890 return 0;
4891}
4892
Andrew Trick2b6860f2011-08-11 23:36:16 +00004893/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004894/// normal unsigned value. Returns 0 if the trip count is unknown or not
4895/// constant. Will also return 0 if the maximum trip count is very large (>=
4896/// 2^32).
4897///
4898/// This "trip count" assumes that control exits via ExitingBlock. More
4899/// precisely, it is the number of times that control may reach ExitingBlock
4900/// before taking the branch. For loops with multiple exits, it may not be the
4901/// number times that the loop header executes because the loop may exit
4902/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004903unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4904 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004905 assert(ExitingBlock && "Must pass a non-null exiting block!");
4906 assert(L->isLoopExiting(ExitingBlock) &&
4907 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00004908 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004909 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004910 if (!ExitCount)
4911 return 0;
4912
4913 ConstantInt *ExitConst = ExitCount->getValue();
4914
4915 // Guard against huge trip counts.
4916 if (ExitConst->getValue().getActiveBits() > 32)
4917 return 0;
4918
4919 // In case of integer overflow, this returns 0, which is correct.
4920 return ((unsigned)ExitConst->getZExtValue()) + 1;
4921}
4922
Chandler Carruth6666c272014-10-11 00:12:11 +00004923unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4924 if (BasicBlock *ExitingBB = L->getExitingBlock())
4925 return getSmallConstantTripMultiple(L, ExitingBB);
4926
4927 // No trip multiple information for multiple exits.
4928 return 0;
4929}
4930
Andrew Trick2b6860f2011-08-11 23:36:16 +00004931/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4932/// trip count of this loop as a normal unsigned value, if possible. This
4933/// means that the actual trip count is always a multiple of the returned
4934/// value (don't forget the trip count could very well be zero as well!).
4935///
4936/// Returns 1 if the trip count is unknown or not guaranteed to be the
4937/// multiple of a constant (which is also the case if the trip count is simply
4938/// constant, use getSmallConstantTripCount for that case), Will also return 1
4939/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004940///
4941/// As explained in the comments for getSmallConstantTripCount, this assumes
4942/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004943unsigned
4944ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4945 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004946 assert(ExitingBlock && "Must pass a non-null exiting block!");
4947 assert(L->isLoopExiting(ExitingBlock) &&
4948 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004949 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004950 if (ExitCount == getCouldNotCompute())
4951 return 1;
4952
4953 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004954 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004955 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4956 // to factor simple cases.
4957 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4958 TCMul = Mul->getOperand(0);
4959
4960 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4961 if (!MulC)
4962 return 1;
4963
4964 ConstantInt *Result = MulC->getValue();
4965
Hal Finkel30bd9342012-10-24 19:46:44 +00004966 // Guard against huge trip counts (this requires checking
4967 // for zero to handle the case where the trip count == -1 and the
4968 // addition wraps).
4969 if (!Result || Result->getValue().getActiveBits() > 32 ||
4970 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004971 return 1;
4972
4973 return (unsigned)Result->getZExtValue();
4974}
4975
Andrew Trick3ca3f982011-07-26 17:19:55 +00004976// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004977// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004978// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004979const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4980 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004981}
4982
Dan Gohman0bddac12009-02-24 18:55:53 +00004983/// getBackedgeTakenCount - If the specified loop has a predictable
4984/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4985/// object. The backedge-taken count is the number of times the loop header
4986/// will be branched to from within the loop. This is one less than the
4987/// trip count of the loop, since it doesn't count the first iteration,
4988/// when the header is branched to from outside the loop.
4989///
4990/// Note that it is not valid to call this method on a loop without a
4991/// loop-invariant backedge-taken count (see
4992/// hasLoopInvariantBackedgeTakenCount).
4993///
Dan Gohmanaf752342009-07-07 17:06:11 +00004994const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004995 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004996}
4997
4998/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4999/// return the least SCEV value that is known never to be less than the
5000/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005001const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005002 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005003}
5004
Dan Gohmandc191042009-07-08 19:23:34 +00005005/// PushLoopPHIs - Push PHI nodes in the header of the given loop
5006/// onto the given Worklist.
5007static void
5008PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5009 BasicBlock *Header = L->getHeader();
5010
5011 // Push all Loop-header PHIs onto the Worklist stack.
5012 for (BasicBlock::iterator I = Header->begin();
5013 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5014 Worklist.push_back(PN);
5015}
5016
Dan Gohman2b8da352009-04-30 20:47:05 +00005017const ScalarEvolution::BackedgeTakenInfo &
5018ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005019 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005020 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005021 // update the value. The temporary CouldNotCompute value tells SCEV
5022 // code elsewhere that it shouldn't attempt to request a new
5023 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005024 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005025 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005026 if (!Pair.second)
5027 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005028
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005029 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005030 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5031 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005032 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005033
5034 if (Result.getExact(this) != getCouldNotCompute()) {
5035 assert(isLoopInvariant(Result.getExact(this), L) &&
5036 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005037 "Computed backedge-taken count isn't loop invariant for loop!");
5038 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005039 }
5040 else if (Result.getMax(this) == getCouldNotCompute() &&
5041 isa<PHINode>(L->getHeader()->begin())) {
5042 // Only count loops that have phi nodes as not being computable.
5043 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005044 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005045
Chris Lattnera337f5e2011-01-09 02:16:18 +00005046 // Now that we know more about the trip count for this loop, forget any
5047 // existing SCEV values for PHI nodes in this loop since they are only
5048 // conservative estimates made without the benefit of trip count
5049 // information. This is similar to the code in forgetLoop, except that
5050 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005051 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005052 SmallVector<Instruction *, 16> Worklist;
5053 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005054
Chris Lattnera337f5e2011-01-09 02:16:18 +00005055 SmallPtrSet<Instruction *, 8> Visited;
5056 while (!Worklist.empty()) {
5057 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005058 if (!Visited.insert(I).second)
5059 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005060
Chris Lattnera337f5e2011-01-09 02:16:18 +00005061 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005062 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005063 if (It != ValueExprMap.end()) {
5064 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005065
Chris Lattnera337f5e2011-01-09 02:16:18 +00005066 // SCEVUnknown for a PHI either means that it has an unrecognized
5067 // structure, or it's a PHI that's in the progress of being computed
5068 // by createNodeForPHI. In the former case, additional loop trip
5069 // count information isn't going to change anything. In the later
5070 // case, createNodeForPHI will perform the necessary updates on its
5071 // own when it gets to that point.
5072 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5073 forgetMemoizedResults(Old);
5074 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005075 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005076 if (PHINode *PN = dyn_cast<PHINode>(I))
5077 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005078 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005079
5080 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005081 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005082 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005083
5084 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005085 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005086 // recusive call to getBackedgeTakenInfo (on a different
5087 // loop), which would invalidate the iterator computed
5088 // earlier.
5089 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00005090}
5091
Dan Gohman880c92a2009-10-31 15:04:55 +00005092/// forgetLoop - This method should be called by the client when it has
5093/// changed a loop in a way that may effect ScalarEvolution's ability to
5094/// compute a trip count, or if the loop is deleted.
5095void ScalarEvolution::forgetLoop(const Loop *L) {
5096 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005097 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
5098 BackedgeTakenCounts.find(L);
5099 if (BTCPos != BackedgeTakenCounts.end()) {
5100 BTCPos->second.clear();
5101 BackedgeTakenCounts.erase(BTCPos);
5102 }
Dan Gohmanf1505722009-05-02 17:43:35 +00005103
Dan Gohman880c92a2009-10-31 15:04:55 +00005104 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005105 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005106 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005107
Dan Gohmandc191042009-07-08 19:23:34 +00005108 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005109 while (!Worklist.empty()) {
5110 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005111 if (!Visited.insert(I).second)
5112 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005113
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005114 ValueExprMapType::iterator It =
5115 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005116 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005117 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005118 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005119 if (PHINode *PN = dyn_cast<PHINode>(I))
5120 ConstantEvolutionLoopExitValue.erase(PN);
5121 }
5122
5123 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005124 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005125
5126 // Forget all contained loops too, to avoid dangling entries in the
5127 // ValuesAtScopes map.
5128 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5129 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00005130}
5131
Eric Christopheref6d5932010-07-29 01:25:38 +00005132/// forgetValue - This method should be called by the client when it has
5133/// changed a value in a way that may effect its value, or which may
5134/// disconnect it from a def-use chain linking it to a loop.
5135void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005136 Instruction *I = dyn_cast<Instruction>(V);
5137 if (!I) return;
5138
5139 // Drop information about expressions based on loop-header PHIs.
5140 SmallVector<Instruction *, 16> Worklist;
5141 Worklist.push_back(I);
5142
5143 SmallPtrSet<Instruction *, 8> Visited;
5144 while (!Worklist.empty()) {
5145 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005146 if (!Visited.insert(I).second)
5147 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005148
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005149 ValueExprMapType::iterator It =
5150 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005151 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005152 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005153 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005154 if (PHINode *PN = dyn_cast<PHINode>(I))
5155 ConstantEvolutionLoopExitValue.erase(PN);
5156 }
5157
5158 PushDefUseChildren(I, Worklist);
5159 }
5160}
5161
Andrew Trick3ca3f982011-07-26 17:19:55 +00005162/// getExact - Get the exact loop backedge taken count considering all loop
Sanjoy Das135e5b92015-07-21 20:59:22 +00005163/// exits. A computable result can only be returned for loops with a single
5164/// exit. Returning the minimum taken count among all exits is incorrect
5165/// because one of the loop's exit limit's may have been skipped. HowFarToZero
5166/// assumes that the limit of each loop test is never skipped. This is a valid
5167/// assumption as long as the loop exits via that test. For precise results, it
5168/// is the caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005169/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005170const SCEV *
5171ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
5172 // If any exits were not computable, the loop is not computable.
5173 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5174
Andrew Trick90c7a102011-11-16 00:52:40 +00005175 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005176 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005177 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5178
Craig Topper9f008862014-04-15 04:59:12 +00005179 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005180 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005181 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005182
5183 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5184
5185 if (!BECount)
5186 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00005187 else if (BECount != ENT->ExactNotTaken)
5188 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005189 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00005190 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005191 return BECount;
5192}
5193
5194/// getExact - Get the exact not taken count for this loop exit.
5195const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005196ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005197 ScalarEvolution *SE) const {
5198 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005199 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005200
Andrew Trick77c55422011-08-02 04:23:35 +00005201 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005202 return ENT->ExactNotTaken;
5203 }
5204 return SE->getCouldNotCompute();
5205}
5206
5207/// getMax - Get the max backedge taken count for the loop.
5208const SCEV *
5209ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5210 return Max ? Max : SE->getCouldNotCompute();
5211}
5212
Andrew Trick9093e152013-03-26 03:14:53 +00005213bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5214 ScalarEvolution *SE) const {
5215 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5216 return true;
5217
5218 if (!ExitNotTaken.ExitingBlock)
5219 return false;
5220
5221 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005222 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00005223
5224 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
5225 && SE->hasOperand(ENT->ExactNotTaken, S)) {
5226 return true;
5227 }
5228 }
5229 return false;
5230}
5231
Andrew Trick3ca3f982011-07-26 17:19:55 +00005232/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5233/// computable exit into a persistent ExitNotTakenInfo array.
5234ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5235 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
5236 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
5237
5238 if (!Complete)
5239 ExitNotTaken.setIncomplete();
5240
5241 unsigned NumExits = ExitCounts.size();
5242 if (NumExits == 0) return;
5243
Andrew Trick77c55422011-08-02 04:23:35 +00005244 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005245 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
5246 if (NumExits == 1) return;
5247
5248 // Handle the rare case of multiple computable exits.
5249 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
5250
5251 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
5252 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
5253 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00005254 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005255 ENT->ExactNotTaken = ExitCounts[i].second;
5256 }
5257}
5258
5259/// clear - Invalidate this result and free the ExitNotTakenInfo array.
5260void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005261 ExitNotTaken.ExitingBlock = nullptr;
5262 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005263 delete[] ExitNotTaken.getNextExit();
5264}
5265
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005266/// computeBackedgeTakenCount - Compute the number of times the backedge
Dan Gohman0bddac12009-02-24 18:55:53 +00005267/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005268ScalarEvolution::BackedgeTakenInfo
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005269ScalarEvolution::computeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005270 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005271 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005272
Andrew Trick839e30b2014-05-23 19:47:13 +00005273 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005274 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005275 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005276 const SCEV *MustExitMaxBECount = nullptr;
5277 const SCEV *MayExitMaxBECount = nullptr;
5278
5279 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5280 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00005281 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005282 BasicBlock *ExitBB = ExitingBlocks[i];
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005283 ExitLimit EL = computeExitLimit(L, ExitBB);
Andrew Trick839e30b2014-05-23 19:47:13 +00005284
5285 // 1. For each exit that can be computed, add an entry to ExitCounts.
5286 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005287 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005288 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005289 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005290 CouldComputeBECount = false;
5291 else
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005292 ExitCounts.push_back({ExitBB, EL.Exact});
Andrew Trick3ca3f982011-07-26 17:19:55 +00005293
Andrew Trick839e30b2014-05-23 19:47:13 +00005294 // 2. Derive the loop's MaxBECount from each exit's max number of
5295 // non-exiting iterations. Partition the loop exits into two kinds:
5296 // LoopMustExits and LoopMayExits.
5297 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005298 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5299 // is a LoopMayExit. If any computable LoopMustExit is found, then
5300 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5301 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5302 // considered greater than any computable EL.Max.
5303 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005304 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005305 if (!MustExitMaxBECount)
5306 MustExitMaxBECount = EL.Max;
5307 else {
5308 MustExitMaxBECount =
5309 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005310 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005311 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5312 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5313 MayExitMaxBECount = EL.Max;
5314 else {
5315 MayExitMaxBECount =
5316 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5317 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005318 }
Dan Gohman96212b62009-06-22 00:31:57 +00005319 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005320 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5321 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005322 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005323}
5324
Andrew Trick3ca3f982011-07-26 17:19:55 +00005325ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005326ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00005327
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005328 // Okay, we've chosen an exiting block. See what condition causes us to exit
5329 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005330 // lead to the loop header.
5331 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005332 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005333 for (auto *SBB : successors(ExitingBlock))
5334 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005335 if (Exit) // Multiple exit successors.
5336 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005337 Exit = SBB;
5338 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005339 MustExecuteLoopHeader = false;
5340 }
Dan Gohmance973df2009-06-24 04:48:43 +00005341
Chris Lattner18954852007-01-07 02:24:26 +00005342 // At this point, we know we have a conditional branch that determines whether
5343 // the loop is exited. However, we don't know if the branch is executed each
5344 // time through the loop. If not, then the execution count of the branch will
5345 // not be equal to the trip count of the loop.
5346 //
5347 // Currently we check for this by checking to see if the Exit branch goes to
5348 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005349 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005350 // loop header. This is common for un-rotated loops.
5351 //
5352 // If both of those tests fail, walk up the unique predecessor chain to the
5353 // header, stopping if there is an edge that doesn't exit the loop. If the
5354 // header is reached, the execution count of the branch will be equal to the
5355 // trip count of the loop.
5356 //
5357 // More extensive analysis could be done to handle more cases here.
5358 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005359 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005360 // The simple checks failed, try climbing the unique predecessor chain
5361 // up to the header.
5362 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005363 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005364 BasicBlock *Pred = BB->getUniquePredecessor();
5365 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005366 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005367 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005368 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005369 if (PredSucc == BB)
5370 continue;
5371 // If the predecessor has a successor that isn't BB and isn't
5372 // outside the loop, assume the worst.
5373 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005374 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005375 }
5376 if (Pred == L->getHeader()) {
5377 Ok = true;
5378 break;
5379 }
5380 BB = Pred;
5381 }
5382 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005383 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005384 }
5385
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005386 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005387 TerminatorInst *Term = ExitingBlock->getTerminator();
5388 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5389 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5390 // Proceed to the next level to examine the exit condition expression.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005391 return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
Benjamin Kramer5a188542014-02-11 15:44:32 +00005392 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005393 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005394 }
5395
5396 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005397 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005398 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005399
5400 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005401}
5402
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005403/// computeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005404/// backedge of the specified loop will execute if its exit condition
5405/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00005406///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005407/// @param ControlsExit is true if ExitCond directly controls the exit
5408/// branch. In this case, we can assume that the loop exits only if the
5409/// condition is true and can infer that failing to meet the condition prior to
5410/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005411ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005412ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005413 Value *ExitCond,
5414 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005415 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005416 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005417 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005418 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5419 if (BO->getOpcode() == Instruction::And) {
5420 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005421 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005422 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005423 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005424 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005425 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005426 const SCEV *BECount = getCouldNotCompute();
5427 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005428 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005429 // Both conditions must be true for the loop to continue executing.
5430 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005431 if (EL0.Exact == getCouldNotCompute() ||
5432 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005433 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005434 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005435 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5436 if (EL0.Max == getCouldNotCompute())
5437 MaxBECount = EL1.Max;
5438 else if (EL1.Max == getCouldNotCompute())
5439 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005440 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005441 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005442 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005443 // Both conditions must be true at the same time for the loop to exit.
5444 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005445 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005446 if (EL0.Max == EL1.Max)
5447 MaxBECount = EL0.Max;
5448 if (EL0.Exact == EL1.Exact)
5449 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005450 }
5451
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005452 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5453 // to be more aggressive when computing BECount than when computing
5454 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact
5455 // to match, but for EL0.Max and EL1.Max to not.
5456 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5457 !isa<SCEVCouldNotCompute>(BECount))
5458 MaxBECount = BECount;
5459
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005460 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005461 }
5462 if (BO->getOpcode() == Instruction::Or) {
5463 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005464 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005465 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005466 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005467 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005468 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005469 const SCEV *BECount = getCouldNotCompute();
5470 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005471 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005472 // Both conditions must be false for the loop to continue executing.
5473 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005474 if (EL0.Exact == getCouldNotCompute() ||
5475 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005476 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005477 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005478 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5479 if (EL0.Max == getCouldNotCompute())
5480 MaxBECount = EL1.Max;
5481 else if (EL1.Max == getCouldNotCompute())
5482 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005483 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005484 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005485 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005486 // Both conditions must be false at the same time for the loop to exit.
5487 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005488 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005489 if (EL0.Max == EL1.Max)
5490 MaxBECount = EL0.Max;
5491 if (EL0.Exact == EL1.Exact)
5492 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005493 }
5494
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005495 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005496 }
5497 }
5498
5499 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005500 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00005501 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005502 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00005503
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005504 // Check for a constant condition. These are normally stripped out by
5505 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5506 // preserve the CFG and is temporarily leaving constant conditions
5507 // in place.
5508 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5509 if (L->contains(FBB) == !CI->getZExtValue())
5510 // The backedge is always taken.
5511 return getCouldNotCompute();
5512 else
5513 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005514 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005515 }
5516
Eli Friedmanebf98b02009-05-09 12:32:42 +00005517 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005518 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005519}
5520
Andrew Trick3ca3f982011-07-26 17:19:55 +00005521ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005522ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005523 ICmpInst *ExitCond,
5524 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005525 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005526 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005527
Reid Spencer266e42b2006-12-23 06:05:41 +00005528 // If the condition was exit on true, convert the condition to exit on false
5529 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005530 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005531 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005532 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005533 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005534
5535 // Handle common loops like: for (X = "string"; *X; ++X)
5536 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5537 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005538 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005539 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005540 if (ItCnt.hasAnyInfo())
5541 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005542 }
5543
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00005544 ExitLimit ShiftEL = computeShiftCompareExitLimit(
5545 ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond);
5546 if (ShiftEL.hasAnyInfo())
5547 return ShiftEL;
5548
Dan Gohmanaf752342009-07-07 17:06:11 +00005549 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5550 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005551
5552 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005553 LHS = getSCEVAtScope(LHS, L);
5554 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005555
Dan Gohmance973df2009-06-24 04:48:43 +00005556 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005557 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005558 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005559 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005560 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005561 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005562 }
5563
Dan Gohman81585c12010-05-03 16:35:17 +00005564 // Simplify the operands before analyzing them.
5565 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5566
Chris Lattnerd934c702004-04-02 20:23:17 +00005567 // If we have a comparison of a chrec against a constant, try to use value
5568 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005569 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5570 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005571 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005572 // Form the constant range.
5573 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00005574 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005575
Dan Gohmanaf752342009-07-07 17:06:11 +00005576 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005577 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005578 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005579
Chris Lattnerd934c702004-04-02 20:23:17 +00005580 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005581 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005582 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005583 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005584 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005585 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005586 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005587 case ICmpInst::ICMP_EQ: { // while (X == Y)
5588 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005589 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5590 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005591 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005592 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005593 case ICmpInst::ICMP_SLT:
5594 case ICmpInst::ICMP_ULT: { // while (X < Y)
5595 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005596 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005597 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005598 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005599 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005600 case ICmpInst::ICMP_SGT:
5601 case ICmpInst::ICMP_UGT: { // while (X > Y)
5602 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005603 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005604 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005605 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005606 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005607 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00005608 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005609 }
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005610 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005611}
5612
Benjamin Kramer5a188542014-02-11 15:44:32 +00005613ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005614ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00005615 SwitchInst *Switch,
5616 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005617 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005618 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5619
5620 // Give up if the exit is the default dest of a switch.
5621 if (Switch->getDefaultDest() == ExitingBlock)
5622 return getCouldNotCompute();
5623
5624 assert(L->contains(Switch->getDefaultDest()) &&
5625 "Default case must not exit the loop!");
5626 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5627 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5628
5629 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005630 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005631 if (EL.hasAnyInfo())
5632 return EL;
5633
5634 return getCouldNotCompute();
5635}
5636
Chris Lattnerec901cc2004-10-12 01:49:27 +00005637static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005638EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5639 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005640 const SCEV *InVal = SE.getConstant(C);
5641 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005642 assert(isa<SCEVConstant>(Val) &&
5643 "Evaluation of SCEV at constant didn't fold correctly?");
5644 return cast<SCEVConstant>(Val)->getValue();
5645}
5646
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005647/// computeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005648/// 'icmp op load X, cst', try to see if we can compute the backedge
5649/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005650ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005651ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00005652 LoadInst *LI,
5653 Constant *RHS,
5654 const Loop *L,
5655 ICmpInst::Predicate predicate) {
5656
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005657 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005658
5659 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005660 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005661 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005662 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005663
5664 // Make sure that it is really a constant global we are gepping, with an
5665 // initializer, and make sure the first IDX is really 0.
5666 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005667 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005668 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5669 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005670 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005671
5672 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005673 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005674 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005675 unsigned VarIdxNum = 0;
5676 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5677 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5678 Indexes.push_back(CI);
5679 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005680 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005681 VarIdx = GEP->getOperand(i);
5682 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005683 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005684 }
5685
Andrew Trick7004e4b2012-03-26 22:33:59 +00005686 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5687 if (!VarIdx)
5688 return getCouldNotCompute();
5689
Chris Lattnerec901cc2004-10-12 01:49:27 +00005690 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5691 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005692 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005693 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005694
5695 // We can only recognize very limited forms of loop index expressions, in
5696 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005697 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005698 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005699 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5700 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005701 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005702
5703 unsigned MaxSteps = MaxBruteForceIterations;
5704 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005705 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005706 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005707 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005708
5709 // Form the GEP offset.
5710 Indexes[VarIdxNum] = Val;
5711
Chris Lattnere166a852012-01-24 05:49:24 +00005712 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5713 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005714 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005715
5716 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005717 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005718 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005719 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005720 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005721 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005722 }
5723 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005724 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005725}
5726
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00005727ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
5728 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
5729 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
5730 if (!RHS)
5731 return getCouldNotCompute();
5732
5733 const BasicBlock *Latch = L->getLoopLatch();
5734 if (!Latch)
5735 return getCouldNotCompute();
5736
5737 const BasicBlock *Predecessor = L->getLoopPredecessor();
5738 if (!Predecessor)
5739 return getCouldNotCompute();
5740
5741 // Return true if V is of the form "LHS `shift_op` <positive constant>".
5742 // Return LHS in OutLHS and shift_opt in OutOpCode.
5743 auto MatchPositiveShift =
5744 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
5745
5746 using namespace PatternMatch;
5747
5748 ConstantInt *ShiftAmt;
5749 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5750 OutOpCode = Instruction::LShr;
5751 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5752 OutOpCode = Instruction::AShr;
5753 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5754 OutOpCode = Instruction::Shl;
5755 else
5756 return false;
5757
5758 return ShiftAmt->getValue().isStrictlyPositive();
5759 };
5760
5761 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
5762 //
5763 // loop:
5764 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
5765 // %iv.shifted = lshr i32 %iv, <positive constant>
5766 //
5767 // Return true on a succesful match. Return the corresponding PHI node (%iv
5768 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
5769 auto MatchShiftRecurrence =
5770 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
5771 Optional<Instruction::BinaryOps> PostShiftOpCode;
5772
5773 {
5774 Instruction::BinaryOps OpC;
5775 Value *V;
5776
5777 // If we encounter a shift instruction, "peel off" the shift operation,
5778 // and remember that we did so. Later when we inspect %iv's backedge
5779 // value, we will make sure that the backedge value uses the same
5780 // operation.
5781 //
5782 // Note: the peeled shift operation does not have to be the same
5783 // instruction as the one feeding into the PHI's backedge value. We only
5784 // really care about it being the same *kind* of shift instruction --
5785 // that's all that is required for our later inferences to hold.
5786 if (MatchPositiveShift(LHS, V, OpC)) {
5787 PostShiftOpCode = OpC;
5788 LHS = V;
5789 }
5790 }
5791
5792 PNOut = dyn_cast<PHINode>(LHS);
5793 if (!PNOut || PNOut->getParent() != L->getHeader())
5794 return false;
5795
5796 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
5797 Value *OpLHS;
5798
5799 return
5800 // The backedge value for the PHI node must be a shift by a positive
5801 // amount
5802 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
5803
5804 // of the PHI node itself
5805 OpLHS == PNOut &&
5806
5807 // and the kind of shift should be match the kind of shift we peeled
5808 // off, if any.
5809 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
5810 };
5811
5812 PHINode *PN;
5813 Instruction::BinaryOps OpCode;
5814 if (!MatchShiftRecurrence(LHS, PN, OpCode))
5815 return getCouldNotCompute();
5816
5817 const DataLayout &DL = getDataLayout();
5818
5819 // The key rationale for this optimization is that for some kinds of shift
5820 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
5821 // within a finite number of iterations. If the condition guarding the
5822 // backedge (in the sense that the backedge is taken if the condition is true)
5823 // is false for the value the shift recurrence stabilizes to, then we know
5824 // that the backedge is taken only a finite number of times.
5825
5826 ConstantInt *StableValue = nullptr;
5827 switch (OpCode) {
5828 default:
5829 llvm_unreachable("Impossible case!");
5830
5831 case Instruction::AShr: {
5832 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
5833 // bitwidth(K) iterations.
5834 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
5835 bool KnownZero, KnownOne;
5836 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
5837 Predecessor->getTerminator(), &DT);
5838 auto *Ty = cast<IntegerType>(RHS->getType());
5839 if (KnownZero)
5840 StableValue = ConstantInt::get(Ty, 0);
5841 else if (KnownOne)
5842 StableValue = ConstantInt::get(Ty, -1, true);
5843 else
5844 return getCouldNotCompute();
5845
5846 break;
5847 }
5848 case Instruction::LShr:
5849 case Instruction::Shl:
5850 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
5851 // stabilize to 0 in at most bitwidth(K) iterations.
5852 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
5853 break;
5854 }
5855
5856 auto *Result =
5857 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
5858 assert(Result->getType()->isIntegerTy(1) &&
5859 "Otherwise cannot be an operand to a branch instruction");
5860
5861 if (Result->isZeroValue()) {
5862 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
5863 const SCEV *UpperBound =
5864 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
5865 return ExitLimit(getCouldNotCompute(), UpperBound);
5866 }
5867
5868 return getCouldNotCompute();
5869}
Chris Lattnerec901cc2004-10-12 01:49:27 +00005870
Chris Lattnerdd730472004-04-17 22:58:41 +00005871/// CanConstantFold - Return true if we can constant fold an instruction of the
5872/// specified type, assuming that all operands were constants.
5873static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005874 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005875 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5876 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005877 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005878
Chris Lattnerdd730472004-04-17 22:58:41 +00005879 if (const CallInst *CI = dyn_cast<CallInst>(I))
5880 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005881 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005882 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005883}
5884
Andrew Trick3a86ba72011-10-05 03:25:31 +00005885/// Determine whether this instruction can constant evolve within this loop
5886/// assuming its operands can all constant evolve.
5887static bool canConstantEvolve(Instruction *I, const Loop *L) {
5888 // An instruction outside of the loop can't be derived from a loop PHI.
5889 if (!L->contains(I)) return false;
5890
5891 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00005892 // We don't currently keep track of the control flow needed to evaluate
5893 // PHIs, so we cannot handle PHIs inside of loops.
5894 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00005895 }
5896
5897 // If we won't be able to constant fold this expression even if the operands
5898 // are constants, bail early.
5899 return CanConstantFold(I);
5900}
5901
5902/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5903/// recursing through each instruction operand until reaching a loop header phi.
5904static PHINode *
5905getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005906 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005907
5908 // Otherwise, we can evaluate this instruction if all of its operands are
5909 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005910 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00005911 for (Value *Op : UseInst->operands()) {
5912 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005913
Sanjoy Dasd87e4352015-12-08 22:53:36 +00005914 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00005915 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005916
5917 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005918 if (!P)
5919 // If this operand is already visited, reuse the prior result.
5920 // We may have P != PHI if this is the deepest point at which the
5921 // inconsistent paths meet.
5922 P = PHIMap.lookup(OpInst);
5923 if (!P) {
5924 // Recurse and memoize the results, whether a phi is found or not.
5925 // This recursive call invalidates pointers into PHIMap.
5926 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5927 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005928 }
Craig Topper9f008862014-04-15 04:59:12 +00005929 if (!P)
5930 return nullptr; // Not evolving from PHI
5931 if (PHI && PHI != P)
5932 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005933 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005934 }
5935 // This is a expression evolving from a constant PHI!
5936 return PHI;
5937}
5938
Chris Lattnerdd730472004-04-17 22:58:41 +00005939/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5940/// in the loop that V is derived from. We allow arbitrary operations along the
5941/// way, but the operands of an operation must either be constants or a value
5942/// derived from a constant PHI. If this expression does not fit with these
5943/// constraints, return null.
5944static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005945 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005946 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005947
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00005948 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00005949 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00005950
Andrew Trick3a86ba72011-10-05 03:25:31 +00005951 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005952 DenseMap<Instruction *, PHINode *> PHIMap;
5953 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005954}
5955
5956/// EvaluateExpression - Given an expression that passes the
5957/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5958/// in the loop has the value PHIVal. If we can't fold this expression for some
5959/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005960static Constant *EvaluateExpression(Value *V, const Loop *L,
5961 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005962 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005963 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005964 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005965 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005966 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005967 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005968
Andrew Trick3a86ba72011-10-05 03:25:31 +00005969 if (Constant *C = Vals.lookup(I)) return C;
5970
Nick Lewyckya6674c72011-10-22 19:58:20 +00005971 // An instruction inside the loop depends on a value outside the loop that we
5972 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005973 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005974
5975 // An unmapped PHI can be due to a branch or another loop inside this loop,
5976 // or due to this not being the initial iteration through a loop where we
5977 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005978 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005979
Dan Gohmanf820bd32010-06-22 13:15:46 +00005980 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005981
5982 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005983 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5984 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005985 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005986 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005987 continue;
5988 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005989 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005990 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005991 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005992 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005993 }
5994
Nick Lewyckya6674c72011-10-22 19:58:20 +00005995 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005996 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005997 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005998 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5999 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006000 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006001 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006002 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006003}
6004
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006005
6006// If every incoming value to PN except the one for BB is a specific Constant,
6007// return that, else return nullptr.
6008static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6009 Constant *IncomingVal = nullptr;
6010
6011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6012 if (PN->getIncomingBlock(i) == BB)
6013 continue;
6014
6015 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6016 if (!CurrentVal)
6017 return nullptr;
6018
6019 if (IncomingVal != CurrentVal) {
6020 if (IncomingVal)
6021 return nullptr;
6022 IncomingVal = CurrentVal;
6023 }
6024 }
6025
6026 return IncomingVal;
6027}
6028
Chris Lattnerdd730472004-04-17 22:58:41 +00006029/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6030/// in the header of its containing loop, we know the loop executes a
6031/// constant number of times, and the PHI node is just a recurrence
6032/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006033Constant *
6034ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006035 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006036 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006037 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006038 if (I != ConstantEvolutionLoopExitValue.end())
6039 return I->second;
6040
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006041 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006042 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006043
6044 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6045
Andrew Trick3a86ba72011-10-05 03:25:31 +00006046 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006047 BasicBlock *Header = L->getHeader();
6048 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006049
Sanjoy Dasdd709962015-10-08 18:28:36 +00006050 BasicBlock *Latch = L->getLoopLatch();
6051 if (!Latch)
6052 return nullptr;
6053
Sanjoy Das4493b402015-10-07 17:38:25 +00006054 for (auto &I : *Header) {
6055 PHINode *PHI = dyn_cast<PHINode>(&I);
6056 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006057 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006058 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006059 CurrentIterVals[PHI] = StartCST;
6060 }
6061 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006062 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006063
Sanjoy Dasdd709962015-10-08 18:28:36 +00006064 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006065
6066 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006067 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006068 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006069
Dan Gohman0bddac12009-02-24 18:55:53 +00006070 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006071 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006072 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006073 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006074 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006075 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006076
Nick Lewyckya6674c72011-10-22 19:58:20 +00006077 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006078 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006079 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006080 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006081 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006082 if (!NextPHI)
6083 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006084 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006085
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006086 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6087
Nick Lewyckya6674c72011-10-22 19:58:20 +00006088 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6089 // cease to be able to evaluate one of them or if they stop evolving,
6090 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006091 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006092 for (const auto &I : CurrentIterVals) {
6093 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006094 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006095 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006096 }
6097 // We use two distinct loops because EvaluateExpression may invalidate any
6098 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006099 for (const auto &I : PHIsToCompute) {
6100 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006101 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006102 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006103 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006104 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006105 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006106 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006107 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006108 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006109
6110 // If all entries in CurrentIterVals == NextIterVals then we can stop
6111 // iterating, the loop can't continue to change.
6112 if (StoppedEvolving)
6113 return RetVal = CurrentIterVals[PN];
6114
Andrew Trick3a86ba72011-10-05 03:25:31 +00006115 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006116 }
6117}
6118
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006119const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006120 Value *Cond,
6121 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006122 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006123 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006124
Dan Gohman866971e2010-06-19 14:17:24 +00006125 // If the loop is canonicalized, the PHI will have exactly two entries.
6126 // That's the only form we support here.
6127 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6128
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006129 DenseMap<Instruction *, Constant *> CurrentIterVals;
6130 BasicBlock *Header = L->getHeader();
6131 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6132
Sanjoy Dasdd709962015-10-08 18:28:36 +00006133 BasicBlock *Latch = L->getLoopLatch();
6134 assert(Latch && "Should follow from NumIncomingValues == 2!");
6135
Sanjoy Das4493b402015-10-07 17:38:25 +00006136 for (auto &I : *Header) {
6137 PHINode *PHI = dyn_cast<PHINode>(&I);
6138 if (!PHI)
6139 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006140 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006141 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006142 CurrentIterVals[PHI] = StartCST;
6143 }
6144 if (!CurrentIterVals.count(PN))
6145 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006146
6147 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6148 // the loop symbolically to determine when the condition gets a value of
6149 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006150 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006151 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006152 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006153 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006154 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006155
Zhou Sheng75b871f2007-01-11 12:24:14 +00006156 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006157 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006158
Reid Spencer983e3b32007-03-01 07:25:48 +00006159 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006160 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006161 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006162 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006163
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006164 // Update all the PHI nodes for the next iteration.
6165 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006166
6167 // Create a list of which PHIs we need to compute. We want to do this before
6168 // calling EvaluateExpression on them because that may invalidate iterators
6169 // into CurrentIterVals.
6170 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006171 for (const auto &I : CurrentIterVals) {
6172 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006173 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006174 PHIsToCompute.push_back(PHI);
6175 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006176 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006177 Constant *&NextPHI = NextIterVals[PHI];
6178 if (NextPHI) continue; // Already computed!
6179
Sanjoy Dasdd709962015-10-08 18:28:36 +00006180 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006181 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006182 }
6183 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006184 }
6185
6186 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006187 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006188}
6189
Dan Gohman237d9e52009-09-03 15:00:26 +00006190/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006191/// at the specified scope in the program. The L value specifies a loop
6192/// nest to evaluate the expression at, where null is the top-level or a
6193/// specified loop is immediately inside of the loop.
6194///
6195/// This method can be used to compute the exit value for a variable defined
6196/// in a loop by querying what the value will hold in the parent loop.
6197///
Dan Gohman8ca08852009-05-24 23:25:42 +00006198/// In the case that a relevant loop exit value cannot be computed, the
6199/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006200const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006201 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6202 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006203 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006204 for (auto &LS : Values)
6205 if (LS.first == L)
6206 return LS.second ? LS.second : V;
6207
6208 Values.emplace_back(L, nullptr);
6209
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006210 // Otherwise compute it.
6211 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006212 for (auto &LS : reverse(ValuesAtScopes[V]))
6213 if (LS.first == L) {
6214 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006215 break;
6216 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006217 return C;
6218}
6219
Nick Lewyckya6674c72011-10-22 19:58:20 +00006220/// This builds up a Constant using the ConstantExpr interface. That way, we
6221/// will return Constants for objects which aren't represented by a
6222/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6223/// Returns NULL if the SCEV isn't representable as a Constant.
6224static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006225 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006226 case scCouldNotCompute:
6227 case scAddRecExpr:
6228 break;
6229 case scConstant:
6230 return cast<SCEVConstant>(V)->getValue();
6231 case scUnknown:
6232 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6233 case scSignExtend: {
6234 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6235 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6236 return ConstantExpr::getSExt(CastOp, SS->getType());
6237 break;
6238 }
6239 case scZeroExtend: {
6240 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6241 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6242 return ConstantExpr::getZExt(CastOp, SZ->getType());
6243 break;
6244 }
6245 case scTruncate: {
6246 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6247 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6248 return ConstantExpr::getTrunc(CastOp, ST->getType());
6249 break;
6250 }
6251 case scAddExpr: {
6252 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6253 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006254 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6255 unsigned AS = PTy->getAddressSpace();
6256 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6257 C = ConstantExpr::getBitCast(C, DestPtrTy);
6258 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006259 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6260 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006261 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006262
6263 // First pointer!
6264 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006265 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006266 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006267 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006268 // The offsets have been converted to bytes. We can add bytes to an
6269 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006270 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006271 }
6272
6273 // Don't bother trying to sum two pointers. We probably can't
6274 // statically compute a load that results from it anyway.
6275 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006276 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006277
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006278 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6279 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006280 C2 = ConstantExpr::getIntegerCast(
6281 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006282 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006283 } else
6284 C = ConstantExpr::getAdd(C, C2);
6285 }
6286 return C;
6287 }
6288 break;
6289 }
6290 case scMulExpr: {
6291 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6292 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6293 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006294 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006295 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6296 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006297 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006298 C = ConstantExpr::getMul(C, C2);
6299 }
6300 return C;
6301 }
6302 break;
6303 }
6304 case scUDivExpr: {
6305 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6306 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6307 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6308 if (LHS->getType() == RHS->getType())
6309 return ConstantExpr::getUDiv(LHS, RHS);
6310 break;
6311 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006312 case scSMaxExpr:
6313 case scUMaxExpr:
6314 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006315 }
Craig Topper9f008862014-04-15 04:59:12 +00006316 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006317}
6318
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006319const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006320 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006321
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006322 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006323 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006324 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006325 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006326 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006327 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6328 if (PHINode *PN = dyn_cast<PHINode>(I))
6329 if (PN->getParent() == LI->getHeader()) {
6330 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006331 // to see if the loop that contains it has a known backedge-taken
6332 // count. If so, we may be able to force computation of the exit
6333 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006334 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006335 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006336 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006337 // Okay, we know how many times the containing loop executes. If
6338 // this is a constant evolving PHI node, get the final value at
6339 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006340 Constant *RV =
6341 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006342 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006343 }
6344 }
6345
Reid Spencere6328ca2006-12-04 21:33:23 +00006346 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006347 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006348 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006349 // result. This is particularly useful for computing loop exit values.
6350 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006351 SmallVector<Constant *, 4> Operands;
6352 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006353 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006354 if (Constant *C = dyn_cast<Constant>(Op)) {
6355 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006356 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006357 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006358
6359 // If any of the operands is non-constant and if they are
6360 // non-integer and non-pointer, don't even try to analyze them
6361 // with scev techniques.
6362 if (!isSCEVable(Op->getType()))
6363 return V;
6364
6365 const SCEV *OrigV = getSCEV(Op);
6366 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6367 MadeImprovement |= OrigV != OpV;
6368
Nick Lewyckya6674c72011-10-22 19:58:20 +00006369 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006370 if (!C) return V;
6371 if (C->getType() != Op->getType())
6372 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6373 Op->getType(),
6374 false),
6375 C, Op->getType());
6376 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006377 }
Dan Gohmance973df2009-06-24 04:48:43 +00006378
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006379 // Check to see if getSCEVAtScope actually made an improvement.
6380 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006381 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006382 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006383 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006384 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006385 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006386 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6387 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006388 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006389 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006390 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006391 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006392 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006393 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006394 }
6395 }
6396
6397 // This is some other type of SCEVUnknown, just return it.
6398 return V;
6399 }
6400
Dan Gohmana30370b2009-05-04 22:02:23 +00006401 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006402 // Avoid performing the look-up in the common case where the specified
6403 // expression has no loop-variant portions.
6404 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006405 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006406 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006407 // Okay, at least one of these operands is loop variant but might be
6408 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006409 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6410 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006411 NewOps.push_back(OpAtScope);
6412
6413 for (++i; i != e; ++i) {
6414 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006415 NewOps.push_back(OpAtScope);
6416 }
6417 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006418 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006419 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006420 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006421 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006422 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006423 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006424 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006425 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006426 }
6427 }
6428 // If we got here, all operands are loop invariant.
6429 return Comm;
6430 }
6431
Dan Gohmana30370b2009-05-04 22:02:23 +00006432 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006433 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6434 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006435 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6436 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006437 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006438 }
6439
6440 // If this is a loop recurrence for a loop that does not contain L, then we
6441 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006442 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006443 // First, attempt to evaluate each operand.
6444 // Avoid performing the look-up in the common case where the specified
6445 // expression has no loop-variant portions.
6446 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6447 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6448 if (OpAtScope == AddRec->getOperand(i))
6449 continue;
6450
6451 // Okay, at least one of these operands is loop variant but might be
6452 // foldable. Build a new instance of the folded commutative expression.
6453 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6454 AddRec->op_begin()+i);
6455 NewOps.push_back(OpAtScope);
6456 for (++i; i != e; ++i)
6457 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6458
Andrew Trick759ba082011-04-27 01:21:25 +00006459 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006460 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006461 AddRec->getNoWrapFlags(SCEV::FlagNW));
6462 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006463 // The addrec may be folded to a nonrecurrence, for example, if the
6464 // induction variable is multiplied by zero after constant folding. Go
6465 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006466 if (!AddRec)
6467 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006468 break;
6469 }
6470
6471 // If the scope is outside the addrec's loop, evaluate it by using the
6472 // loop exit value of the addrec.
6473 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006474 // To evaluate this recurrence, we need to know how many times the AddRec
6475 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006476 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006477 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006478
Eli Friedman61f67622008-08-04 23:49:06 +00006479 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006480 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006481 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006482
Dan Gohman8ca08852009-05-24 23:25:42 +00006483 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006484 }
6485
Dan Gohmana30370b2009-05-04 22:02:23 +00006486 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006487 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006488 if (Op == Cast->getOperand())
6489 return Cast; // must be loop invariant
6490 return getZeroExtendExpr(Op, Cast->getType());
6491 }
6492
Dan Gohmana30370b2009-05-04 22:02:23 +00006493 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006494 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006495 if (Op == Cast->getOperand())
6496 return Cast; // must be loop invariant
6497 return getSignExtendExpr(Op, Cast->getType());
6498 }
6499
Dan Gohmana30370b2009-05-04 22:02:23 +00006500 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006501 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006502 if (Op == Cast->getOperand())
6503 return Cast; // must be loop invariant
6504 return getTruncateExpr(Op, Cast->getType());
6505 }
6506
Torok Edwinfbcc6632009-07-14 16:55:14 +00006507 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006508}
6509
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006510/// getSCEVAtScope - This is a convenience function which does
6511/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00006512const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006513 return getSCEVAtScope(getSCEV(V), L);
6514}
6515
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006516/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6517/// following equation:
6518///
6519/// A * X = B (mod N)
6520///
6521/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6522/// A and B isn't important.
6523///
6524/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006525static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006526 ScalarEvolution &SE) {
6527 uint32_t BW = A.getBitWidth();
6528 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6529 assert(A != 0 && "A must be non-zero.");
6530
6531 // 1. D = gcd(A, N)
6532 //
6533 // The gcd of A and N may have only one prime factor: 2. The number of
6534 // trailing zeros in A is its multiplicity
6535 uint32_t Mult2 = A.countTrailingZeros();
6536 // D = 2^Mult2
6537
6538 // 2. Check if B is divisible by D.
6539 //
6540 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6541 // is not less than multiplicity of this prime factor for D.
6542 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006543 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006544
6545 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6546 // modulo (N / D).
6547 //
6548 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6549 // bit width during computations.
6550 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6551 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006552 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006553 APInt I = AD.multiplicativeInverse(Mod);
6554
6555 // 4. Compute the minimum unsigned root of the equation:
6556 // I * (B / D) mod (N / D)
6557 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6558
6559 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6560 // bits.
6561 return SE.getConstant(Result.trunc(BW));
6562}
Chris Lattnerd934c702004-04-02 20:23:17 +00006563
6564/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6565/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6566/// might be the same) or two SCEVCouldNotCompute objects.
6567///
Dan Gohmanaf752342009-07-07 17:06:11 +00006568static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006569SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006570 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006571 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6572 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6573 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006574
Chris Lattnerd934c702004-04-02 20:23:17 +00006575 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00006576 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00006577 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006578 return {CNC, CNC};
Chris Lattnerd934c702004-04-02 20:23:17 +00006579 }
6580
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006581 uint32_t BitWidth = LC->getAPInt().getBitWidth();
6582 const APInt &L = LC->getAPInt();
6583 const APInt &M = MC->getAPInt();
6584 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00006585 APInt Two(BitWidth, 2);
6586 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006587
Dan Gohmance973df2009-06-24 04:48:43 +00006588 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006589 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006590 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006591 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6592 // The B coefficient is M-N/2
6593 APInt B(M);
6594 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006595
Reid Spencer983e3b32007-03-01 07:25:48 +00006596 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006597 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006598
Reid Spencer983e3b32007-03-01 07:25:48 +00006599 // Compute the B^2-4ac term.
6600 APInt SqrtTerm(B);
6601 SqrtTerm *= B;
6602 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006603
Nick Lewyckyfb780832012-08-01 09:14:36 +00006604 if (SqrtTerm.isNegative()) {
6605 // The loop is provably infinite.
6606 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006607 return {CNC, CNC};
Nick Lewyckyfb780832012-08-01 09:14:36 +00006608 }
6609
Reid Spencer983e3b32007-03-01 07:25:48 +00006610 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6611 // integer value or else APInt::sqrt() will assert.
6612 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006613
Dan Gohmance973df2009-06-24 04:48:43 +00006614 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00006615 // The divisions must be performed as signed divisions.
6616 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00006617 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00006618 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00006619 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006620 return {CNC, CNC};
Nick Lewycky7b14e202008-11-03 02:43:49 +00006621 }
6622
Owen Anderson47db9412009-07-22 00:24:57 +00006623 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00006624
6625 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006626 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00006627 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006628 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00006629
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006630 return {SE.getConstant(Solution1), SE.getConstant(Solution2)};
Nick Lewycky31555522011-10-03 07:10:45 +00006631 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00006632}
6633
6634/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00006635/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00006636///
6637/// This is only used for loops with a "x != y" exit test. The exit condition is
6638/// now expressed as a single expression, V = x-y. So the exit test is
6639/// effectively V != 0. We know and take advantage of the fact that this
6640/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006641ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006642ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006643 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00006644 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006645 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00006646 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006647 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006648 }
6649
Dan Gohman48f82222009-05-04 22:30:44 +00006650 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00006651 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006652 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006653
Chris Lattnerdff679f2011-01-09 22:39:48 +00006654 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6655 // the quadratic equation to solve it.
6656 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6657 std::pair<const SCEV *,const SCEV *> Roots =
6658 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00006659 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6660 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00006661 if (R1 && R2) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006662 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006663 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00006664 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6665 R1->getValue(),
6666 R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006667 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00006668 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00006669
Chris Lattnerd934c702004-04-02 20:23:17 +00006670 // We can only use this value if the chrec ends up with an exact zero
6671 // value at this index. When solving for "X*X != 5", for example, we
6672 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006673 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006674 if (Val->isZero())
6675 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006676 }
6677 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006678 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006679 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006680
Chris Lattnerdff679f2011-01-09 22:39:48 +00006681 // Otherwise we can only handle this if it is affine.
6682 if (!AddRec->isAffine())
6683 return getCouldNotCompute();
6684
6685 // If this is an affine expression, the execution count of this branch is
6686 // the minimum unsigned root of the following equation:
6687 //
6688 // Start + Step*N = 0 (mod 2^BW)
6689 //
6690 // equivalent to:
6691 //
6692 // Step*N = -Start (mod 2^BW)
6693 //
6694 // where BW is the common bit width of Start and Step.
6695
6696 // Get the initial value for the loop.
6697 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6698 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6699
6700 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006701 //
6702 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6703 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6704 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6705 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006706 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006707 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006708 return getCouldNotCompute();
6709
Andrew Trick8b55b732011-03-14 16:50:06 +00006710 // For positive steps (counting up until unsigned overflow):
6711 // N = -Start/Step (as unsigned)
6712 // For negative steps (counting down to zero):
6713 // N = Start/-Step
6714 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006715 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00006716 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006717
6718 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006719 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6720 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006721 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6722 ConstantRange CR = getUnsignedRange(Start);
6723 const SCEV *MaxBECount;
6724 if (!CountDown && CR.getUnsignedMin().isMinValue())
6725 // When counting up, the worst starting value is 1, not 0.
6726 MaxBECount = CR.getUnsignedMax().isMinValue()
6727 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6728 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6729 else
6730 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6731 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006732 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006733 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006734
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006735 // As a special case, handle the instance where Step is a positive power of
6736 // two. In this case, determining whether Step divides Distance evenly can be
6737 // done by counting and comparing the number of trailing zeros of Step and
6738 // Distance.
6739 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006740 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006741 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
6742 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6743 // case is not handled as this code is guarded by !CountDown.
6744 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00006745 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
6746 // Here we've constrained the equation to be of the form
6747 //
6748 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
6749 //
6750 // where we're operating on a W bit wide integer domain and k is
6751 // non-negative. The smallest unsigned solution for X is the trip count.
6752 //
6753 // (0) is equivalent to:
6754 //
6755 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
6756 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
6757 // <=> 2^k * Distance' - X = L * 2^(W - N)
6758 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
6759 //
6760 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
6761 // by 2^(W - N).
6762 //
6763 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
6764 //
6765 // E.g. say we're solving
6766 //
6767 // 2 * Val = 2 * X (in i8) ... (3)
6768 //
6769 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
6770 //
6771 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
6772 // necessarily the smallest unsigned value of X that satisfies (3).
6773 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
6774 // is i8 1, not i8 -127
6775
6776 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
6777
6778 // Since SCEV does not have a URem node, we construct one using a truncate
6779 // and a zero extend.
6780
6781 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
6782 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
6783 auto *WideTy = Distance->getType();
6784
6785 return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
6786 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006787 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006788
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006789 // If the condition controls loop exit (the loop exits only if the expression
6790 // is true) and the addition is no-wrap we can use unsigned divide to
6791 // compute the backedge count. In this case, the step may not divide the
6792 // distance, but we don't care because if the condition is "missed" the loop
6793 // will have undefined behavior due to wrapping.
Sanjoy Das76c48e02016-02-04 18:21:54 +00006794 if (ControlsExit && AddRec->hasNoSelfWrap()) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006795 const SCEV *Exact =
6796 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6797 return ExitLimit(Exact, Exact);
6798 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006799
Chris Lattnerdff679f2011-01-09 22:39:48 +00006800 // Then, try to solve the above equation provided that Start is constant.
6801 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006802 return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(),
Chris Lattnerdff679f2011-01-09 22:39:48 +00006803 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006804 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006805}
6806
6807/// HowFarToNonZero - Return the number of times a backedge checking the
6808/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006809/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006810ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006811ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006812 // Loops that look like: while (X == 0) are very strange indeed. We don't
6813 // handle them yet except for the trivial case. This could be expanded in the
6814 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006815
Chris Lattnerd934c702004-04-02 20:23:17 +00006816 // If the value is a constant, check to see if it is known to be non-zero
6817 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006818 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006819 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006820 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006821 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006822 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006823
Chris Lattnerd934c702004-04-02 20:23:17 +00006824 // We could implement others, but I really doubt anyone writes loops like
6825 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006826 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006827}
6828
Dan Gohmanf9081a22008-09-15 22:18:04 +00006829/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6830/// (which may not be an immediate predecessor) which has exactly one
6831/// successor from which BB is reachable, or null if no such block is
6832/// found.
6833///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006834std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006835ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006836 // If the block has a unique predecessor, then there is no path from the
6837 // predecessor to the block that does not go through the direct edge
6838 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006839 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006840 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00006841
6842 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006843 // If the header has a unique predecessor outside the loop, it must be
6844 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006845 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006846 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00006847
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006848 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00006849}
6850
Dan Gohman450f4e02009-06-20 00:35:32 +00006851/// HasSameValue - SCEV structural equivalence is usually sufficient for
6852/// testing whether two expressions are equal, however for the purposes of
6853/// looking for a condition guarding a loop, it can be useful to be a little
6854/// more general, since a front-end may have replicated the controlling
6855/// expression.
6856///
Dan Gohmanaf752342009-07-07 17:06:11 +00006857static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006858 // Quick check to see if they are the same SCEV.
6859 if (A == B) return true;
6860
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006861 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
6862 // Not all instructions that are "identical" compute the same value. For
6863 // instance, two distinct alloca instructions allocating the same type are
6864 // identical and do not read memory; but compute distinct values.
6865 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
6866 };
6867
Dan Gohman450f4e02009-06-20 00:35:32 +00006868 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6869 // two different instructions with the same value. Check for this case.
6870 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6871 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6872 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6873 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006874 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00006875 return true;
6876
6877 // Otherwise assume they may have a different value.
6878 return false;
6879}
6880
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006881/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006882/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006883///
6884bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006885 const SCEV *&LHS, const SCEV *&RHS,
6886 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006887 bool Changed = false;
6888
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006889 // If we hit the max recursion limit bail out.
6890 if (Depth >= 3)
6891 return false;
6892
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006893 // Canonicalize a constant to the right side.
6894 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6895 // Check for both operands constant.
6896 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6897 if (ConstantExpr::getICmp(Pred,
6898 LHSC->getValue(),
6899 RHSC->getValue())->isNullValue())
6900 goto trivially_false;
6901 else
6902 goto trivially_true;
6903 }
6904 // Otherwise swap the operands to put the constant on the right.
6905 std::swap(LHS, RHS);
6906 Pred = ICmpInst::getSwappedPredicate(Pred);
6907 Changed = true;
6908 }
6909
6910 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006911 // addrec's loop, put the addrec on the left. Also make a dominance check,
6912 // as both operands could be addrecs loop-invariant in each other's loop.
6913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6914 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006915 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006916 std::swap(LHS, RHS);
6917 Pred = ICmpInst::getSwappedPredicate(Pred);
6918 Changed = true;
6919 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006920 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006921
6922 // If there's a constant operand, canonicalize comparisons with boundary
6923 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6924 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006925 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006926 switch (Pred) {
6927 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6928 case ICmpInst::ICMP_EQ:
6929 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006930 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6931 if (!RA)
6932 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6933 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006934 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6935 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006936 RHS = AE->getOperand(1);
6937 LHS = ME->getOperand(1);
6938 Changed = true;
6939 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006940 break;
6941 case ICmpInst::ICMP_UGE:
6942 if ((RA - 1).isMinValue()) {
6943 Pred = ICmpInst::ICMP_NE;
6944 RHS = getConstant(RA - 1);
6945 Changed = true;
6946 break;
6947 }
6948 if (RA.isMaxValue()) {
6949 Pred = ICmpInst::ICMP_EQ;
6950 Changed = true;
6951 break;
6952 }
6953 if (RA.isMinValue()) goto trivially_true;
6954
6955 Pred = ICmpInst::ICMP_UGT;
6956 RHS = getConstant(RA - 1);
6957 Changed = true;
6958 break;
6959 case ICmpInst::ICMP_ULE:
6960 if ((RA + 1).isMaxValue()) {
6961 Pred = ICmpInst::ICMP_NE;
6962 RHS = getConstant(RA + 1);
6963 Changed = true;
6964 break;
6965 }
6966 if (RA.isMinValue()) {
6967 Pred = ICmpInst::ICMP_EQ;
6968 Changed = true;
6969 break;
6970 }
6971 if (RA.isMaxValue()) goto trivially_true;
6972
6973 Pred = ICmpInst::ICMP_ULT;
6974 RHS = getConstant(RA + 1);
6975 Changed = true;
6976 break;
6977 case ICmpInst::ICMP_SGE:
6978 if ((RA - 1).isMinSignedValue()) {
6979 Pred = ICmpInst::ICMP_NE;
6980 RHS = getConstant(RA - 1);
6981 Changed = true;
6982 break;
6983 }
6984 if (RA.isMaxSignedValue()) {
6985 Pred = ICmpInst::ICMP_EQ;
6986 Changed = true;
6987 break;
6988 }
6989 if (RA.isMinSignedValue()) goto trivially_true;
6990
6991 Pred = ICmpInst::ICMP_SGT;
6992 RHS = getConstant(RA - 1);
6993 Changed = true;
6994 break;
6995 case ICmpInst::ICMP_SLE:
6996 if ((RA + 1).isMaxSignedValue()) {
6997 Pred = ICmpInst::ICMP_NE;
6998 RHS = getConstant(RA + 1);
6999 Changed = true;
7000 break;
7001 }
7002 if (RA.isMinSignedValue()) {
7003 Pred = ICmpInst::ICMP_EQ;
7004 Changed = true;
7005 break;
7006 }
7007 if (RA.isMaxSignedValue()) goto trivially_true;
7008
7009 Pred = ICmpInst::ICMP_SLT;
7010 RHS = getConstant(RA + 1);
7011 Changed = true;
7012 break;
7013 case ICmpInst::ICMP_UGT:
7014 if (RA.isMinValue()) {
7015 Pred = ICmpInst::ICMP_NE;
7016 Changed = true;
7017 break;
7018 }
7019 if ((RA + 1).isMaxValue()) {
7020 Pred = ICmpInst::ICMP_EQ;
7021 RHS = getConstant(RA + 1);
7022 Changed = true;
7023 break;
7024 }
7025 if (RA.isMaxValue()) goto trivially_false;
7026 break;
7027 case ICmpInst::ICMP_ULT:
7028 if (RA.isMaxValue()) {
7029 Pred = ICmpInst::ICMP_NE;
7030 Changed = true;
7031 break;
7032 }
7033 if ((RA - 1).isMinValue()) {
7034 Pred = ICmpInst::ICMP_EQ;
7035 RHS = getConstant(RA - 1);
7036 Changed = true;
7037 break;
7038 }
7039 if (RA.isMinValue()) goto trivially_false;
7040 break;
7041 case ICmpInst::ICMP_SGT:
7042 if (RA.isMinSignedValue()) {
7043 Pred = ICmpInst::ICMP_NE;
7044 Changed = true;
7045 break;
7046 }
7047 if ((RA + 1).isMaxSignedValue()) {
7048 Pred = ICmpInst::ICMP_EQ;
7049 RHS = getConstant(RA + 1);
7050 Changed = true;
7051 break;
7052 }
7053 if (RA.isMaxSignedValue()) goto trivially_false;
7054 break;
7055 case ICmpInst::ICMP_SLT:
7056 if (RA.isMaxSignedValue()) {
7057 Pred = ICmpInst::ICMP_NE;
7058 Changed = true;
7059 break;
7060 }
7061 if ((RA - 1).isMinSignedValue()) {
7062 Pred = ICmpInst::ICMP_EQ;
7063 RHS = getConstant(RA - 1);
7064 Changed = true;
7065 break;
7066 }
7067 if (RA.isMinSignedValue()) goto trivially_false;
7068 break;
7069 }
7070 }
7071
7072 // Check for obvious equality.
7073 if (HasSameValue(LHS, RHS)) {
7074 if (ICmpInst::isTrueWhenEqual(Pred))
7075 goto trivially_true;
7076 if (ICmpInst::isFalseWhenEqual(Pred))
7077 goto trivially_false;
7078 }
7079
Dan Gohman81585c12010-05-03 16:35:17 +00007080 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7081 // adding or subtracting 1 from one of the operands.
7082 switch (Pred) {
7083 case ICmpInst::ICMP_SLE:
7084 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7085 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007086 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007087 Pred = ICmpInst::ICMP_SLT;
7088 Changed = true;
7089 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007090 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007091 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007092 Pred = ICmpInst::ICMP_SLT;
7093 Changed = true;
7094 }
7095 break;
7096 case ICmpInst::ICMP_SGE:
7097 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007098 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007099 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007100 Pred = ICmpInst::ICMP_SGT;
7101 Changed = true;
7102 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7103 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007104 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007105 Pred = ICmpInst::ICMP_SGT;
7106 Changed = true;
7107 }
7108 break;
7109 case ICmpInst::ICMP_ULE:
7110 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007111 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007112 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007113 Pred = ICmpInst::ICMP_ULT;
7114 Changed = true;
7115 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007116 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007117 Pred = ICmpInst::ICMP_ULT;
7118 Changed = true;
7119 }
7120 break;
7121 case ICmpInst::ICMP_UGE:
7122 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007123 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007124 Pred = ICmpInst::ICMP_UGT;
7125 Changed = true;
7126 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007127 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007128 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007129 Pred = ICmpInst::ICMP_UGT;
7130 Changed = true;
7131 }
7132 break;
7133 default:
7134 break;
7135 }
7136
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007137 // TODO: More simplifications are possible here.
7138
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007139 // Recursively simplify until we either hit a recursion limit or nothing
7140 // changes.
7141 if (Changed)
7142 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7143
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007144 return Changed;
7145
7146trivially_true:
7147 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007148 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007149 Pred = ICmpInst::ICMP_EQ;
7150 return true;
7151
7152trivially_false:
7153 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007154 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007155 Pred = ICmpInst::ICMP_NE;
7156 return true;
7157}
7158
Dan Gohmane65c9172009-07-13 21:35:55 +00007159bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7160 return getSignedRange(S).getSignedMax().isNegative();
7161}
7162
7163bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7164 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7165}
7166
7167bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7168 return !getSignedRange(S).getSignedMin().isNegative();
7169}
7170
7171bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7172 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7173}
7174
7175bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7176 return isKnownNegative(S) || isKnownPositive(S);
7177}
7178
7179bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7180 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007181 // Canonicalize the inputs first.
7182 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7183
Dan Gohman07591692010-04-11 22:16:48 +00007184 // If LHS or RHS is an addrec, check to see if the condition is true in
7185 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007186 // If LHS and RHS are both addrec, both conditions must be true in
7187 // every iteration of the loop.
7188 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7189 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7190 bool LeftGuarded = false;
7191 bool RightGuarded = false;
7192 if (LAR) {
7193 const Loop *L = LAR->getLoop();
7194 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7195 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7196 if (!RAR) return true;
7197 LeftGuarded = true;
7198 }
7199 }
7200 if (RAR) {
7201 const Loop *L = RAR->getLoop();
7202 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7203 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7204 if (!LAR) return true;
7205 RightGuarded = true;
7206 }
7207 }
7208 if (LeftGuarded && RightGuarded)
7209 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007210
Sanjoy Das7d910f22015-10-02 18:50:30 +00007211 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7212 return true;
7213
Dan Gohman07591692010-04-11 22:16:48 +00007214 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007215 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007216}
7217
Sanjoy Das5dab2052015-07-27 21:42:49 +00007218bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7219 ICmpInst::Predicate Pred,
7220 bool &Increasing) {
7221 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7222
7223#ifndef NDEBUG
7224 // Verify an invariant: inverting the predicate should turn a monotonically
7225 // increasing change to a monotonically decreasing one, and vice versa.
7226 bool IncreasingSwapped;
7227 bool ResultSwapped = isMonotonicPredicateImpl(
7228 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7229
7230 assert(Result == ResultSwapped && "should be able to analyze both!");
7231 if (ResultSwapped)
7232 assert(Increasing == !IncreasingSwapped &&
7233 "monotonicity should flip as we flip the predicate");
7234#endif
7235
7236 return Result;
7237}
7238
7239bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7240 ICmpInst::Predicate Pred,
7241 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007242
7243 // A zero step value for LHS means the induction variable is essentially a
7244 // loop invariant value. We don't really depend on the predicate actually
7245 // flipping from false to true (for increasing predicates, and the other way
7246 // around for decreasing predicates), all we care about is that *if* the
7247 // predicate changes then it only changes from false to true.
7248 //
7249 // A zero step value in itself is not very useful, but there may be places
7250 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7251 // as general as possible.
7252
Sanjoy Das366acc12015-08-06 20:43:41 +00007253 switch (Pred) {
7254 default:
7255 return false; // Conservative answer
7256
7257 case ICmpInst::ICMP_UGT:
7258 case ICmpInst::ICMP_UGE:
7259 case ICmpInst::ICMP_ULT:
7260 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007261 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007262 return false;
7263
7264 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007265 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007266
7267 case ICmpInst::ICMP_SGT:
7268 case ICmpInst::ICMP_SGE:
7269 case ICmpInst::ICMP_SLT:
7270 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007271 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007272 return false;
7273
7274 const SCEV *Step = LHS->getStepRecurrence(*this);
7275
7276 if (isKnownNonNegative(Step)) {
7277 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7278 return true;
7279 }
7280
7281 if (isKnownNonPositive(Step)) {
7282 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7283 return true;
7284 }
7285
7286 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007287 }
7288
Sanjoy Das5dab2052015-07-27 21:42:49 +00007289 }
7290
Sanjoy Das366acc12015-08-06 20:43:41 +00007291 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007292}
7293
7294bool ScalarEvolution::isLoopInvariantPredicate(
7295 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7296 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7297 const SCEV *&InvariantRHS) {
7298
7299 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7300 if (!isLoopInvariant(RHS, L)) {
7301 if (!isLoopInvariant(LHS, L))
7302 return false;
7303
7304 std::swap(LHS, RHS);
7305 Pred = ICmpInst::getSwappedPredicate(Pred);
7306 }
7307
7308 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7309 if (!ArLHS || ArLHS->getLoop() != L)
7310 return false;
7311
7312 bool Increasing;
7313 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7314 return false;
7315
7316 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7317 // true as the loop iterates, and the backedge is control dependent on
7318 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7319 //
7320 // * if the predicate was false in the first iteration then the predicate
7321 // is never evaluated again, since the loop exits without taking the
7322 // backedge.
7323 // * if the predicate was true in the first iteration then it will
7324 // continue to be true for all future iterations since it is
7325 // monotonically increasing.
7326 //
7327 // For both the above possibilities, we can replace the loop varying
7328 // predicate with its value on the first iteration of the loop (which is
7329 // loop invariant).
7330 //
7331 // A similar reasoning applies for a monotonically decreasing predicate, by
7332 // replacing true with false and false with true in the above two bullets.
7333
7334 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7335
7336 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7337 return false;
7338
7339 InvariantPred = Pred;
7340 InvariantLHS = ArLHS->getStart();
7341 InvariantRHS = RHS;
7342 return true;
7343}
7344
Sanjoy Das401e6312016-02-01 20:48:10 +00007345bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7346 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007347 if (HasSameValue(LHS, RHS))
7348 return ICmpInst::isTrueWhenEqual(Pred);
7349
Dan Gohman07591692010-04-11 22:16:48 +00007350 // This code is split out from isKnownPredicate because it is called from
7351 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007352
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007353 auto CheckRanges =
7354 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7355 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7356 .contains(RangeLHS);
7357 };
7358
7359 // The check at the top of the function catches the case where the values are
7360 // known to be equal.
7361 if (Pred == CmpInst::ICMP_EQ)
7362 return false;
7363
7364 if (Pred == CmpInst::ICMP_NE)
7365 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7366 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7367 isKnownNonZero(getMinusSCEV(LHS, RHS));
7368
7369 if (CmpInst::isSigned(Pred))
7370 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7371
7372 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007373}
7374
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007375bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7376 const SCEV *LHS,
7377 const SCEV *RHS) {
7378
7379 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7380 // Return Y via OutY.
7381 auto MatchBinaryAddToConst =
7382 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7383 SCEV::NoWrapFlags ExpectedFlags) {
7384 const SCEV *NonConstOp, *ConstOp;
7385 SCEV::NoWrapFlags FlagsPresent;
7386
7387 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7388 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7389 return false;
7390
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007391 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007392 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7393 };
7394
7395 APInt C;
7396
7397 switch (Pred) {
7398 default:
7399 break;
7400
7401 case ICmpInst::ICMP_SGE:
7402 std::swap(LHS, RHS);
7403 case ICmpInst::ICMP_SLE:
7404 // X s<= (X + C)<nsw> if C >= 0
7405 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7406 return true;
7407
7408 // (X + C)<nsw> s<= X if C <= 0
7409 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7410 !C.isStrictlyPositive())
7411 return true;
7412 break;
7413
7414 case ICmpInst::ICMP_SGT:
7415 std::swap(LHS, RHS);
7416 case ICmpInst::ICMP_SLT:
7417 // X s< (X + C)<nsw> if C > 0
7418 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7419 C.isStrictlyPositive())
7420 return true;
7421
7422 // (X + C)<nsw> s< X if C < 0
7423 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7424 return true;
7425 break;
7426 }
7427
7428 return false;
7429}
7430
Sanjoy Das7d910f22015-10-02 18:50:30 +00007431bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7432 const SCEV *LHS,
7433 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007434 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007435 return false;
7436
7437 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7438 // the stack can result in exponential time complexity.
7439 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7440
7441 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7442 //
7443 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7444 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7445 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7446 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7447 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007448 return isKnownNonNegative(RHS) &&
7449 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7450 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007451}
7452
Dan Gohmane65c9172009-07-13 21:35:55 +00007453/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7454/// protected by a conditional between LHS and RHS. This is used to
7455/// to eliminate casts.
7456bool
7457ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7458 ICmpInst::Predicate Pred,
7459 const SCEV *LHS, const SCEV *RHS) {
7460 // Interpret a null as meaning no loop, where there is obviously no guard
7461 // (interprocedural conditions notwithstanding).
7462 if (!L) return true;
7463
Sanjoy Das401e6312016-02-01 20:48:10 +00007464 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7465 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007466
Dan Gohmane65c9172009-07-13 21:35:55 +00007467 BasicBlock *Latch = L->getLoopLatch();
7468 if (!Latch)
7469 return false;
7470
7471 BranchInst *LoopContinuePredicate =
7472 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007473 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7474 isImpliedCond(Pred, LHS, RHS,
7475 LoopContinuePredicate->getCondition(),
7476 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7477 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007478
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007479 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007480 // -- that can lead to O(n!) time complexity.
7481 if (WalkingBEDominatingConds)
7482 return false;
7483
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007484 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007485
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007486 // See if we can exploit a trip count to prove the predicate.
7487 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7488 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7489 if (LatchBECount != getCouldNotCompute()) {
7490 // We know that Latch branches back to the loop header exactly
7491 // LatchBECount times. This means the backdege condition at Latch is
7492 // equivalent to "{0,+,1} u< LatchBECount".
7493 Type *Ty = LatchBECount->getType();
7494 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7495 const SCEV *LoopCounter =
7496 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7497 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7498 LatchBECount))
7499 return true;
7500 }
7501
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007502 // Check conditions due to any @llvm.assume intrinsics.
7503 for (auto &AssumeVH : AC.assumptions()) {
7504 if (!AssumeVH)
7505 continue;
7506 auto *CI = cast<CallInst>(AssumeVH);
7507 if (!DT.dominates(CI, Latch->getTerminator()))
7508 continue;
7509
7510 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7511 return true;
7512 }
7513
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007514 // If the loop is not reachable from the entry block, we risk running into an
7515 // infinite loop as we walk up into the dom tree. These loops do not matter
7516 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007517 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007518 return false;
7519
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007520 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7521 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007522
7523 assert(DTN && "should reach the loop header before reaching the root!");
7524
7525 BasicBlock *BB = DTN->getBlock();
7526 BasicBlock *PBB = BB->getSinglePredecessor();
7527 if (!PBB)
7528 continue;
7529
7530 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7531 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7532 continue;
7533
7534 Value *Condition = ContinuePredicate->getCondition();
7535
7536 // If we have an edge `E` within the loop body that dominates the only
7537 // latch, the condition guarding `E` also guards the backedge. This
7538 // reasoning works only for loops with a single latch.
7539
7540 BasicBlockEdge DominatingEdge(PBB, BB);
7541 if (DominatingEdge.isSingleEdge()) {
7542 // We're constructively (and conservatively) enumerating edges within the
7543 // loop body that dominate the latch. The dominator tree better agree
7544 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007545 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007546
7547 if (isImpliedCond(Pred, LHS, RHS, Condition,
7548 BB != ContinuePredicate->getSuccessor(0)))
7549 return true;
7550 }
7551 }
7552
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007553 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007554}
7555
Dan Gohmanb50349a2010-04-11 19:27:13 +00007556/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00007557/// by a conditional between LHS and RHS. This is used to help avoid max
7558/// expressions in loop trip counts, and to eliminate casts.
7559bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007560ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7561 ICmpInst::Predicate Pred,
7562 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007563 // Interpret a null as meaning no loop, where there is obviously no guard
7564 // (interprocedural conditions notwithstanding).
7565 if (!L) return false;
7566
Sanjoy Das401e6312016-02-01 20:48:10 +00007567 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7568 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007569
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007570 // Starting at the loop predecessor, climb up the predecessor chain, as long
7571 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00007572 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00007573 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00007574 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00007575 Pair.first;
7576 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00007577
7578 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00007579 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00007580 if (!LoopEntryPredicate ||
7581 LoopEntryPredicate->isUnconditional())
7582 continue;
7583
Dan Gohmane18c2d62010-08-10 23:46:30 +00007584 if (isImpliedCond(Pred, LHS, RHS,
7585 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00007586 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00007587 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007588 }
7589
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007590 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007591 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00007592 if (!AssumeVH)
7593 continue;
7594 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007595 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007596 continue;
7597
7598 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7599 return true;
7600 }
7601
Dan Gohman2a62fd92008-08-12 20:17:31 +00007602 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007603}
7604
Benjamin Kramer039b1042015-10-28 13:54:36 +00007605namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007606/// RAII wrapper to prevent recursive application of isImpliedCond.
7607/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7608/// currently evaluating isImpliedCond.
7609struct MarkPendingLoopPredicate {
7610 Value *Cond;
7611 DenseSet<Value*> &LoopPreds;
7612 bool Pending;
7613
7614 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
7615 : Cond(C), LoopPreds(LP) {
7616 Pending = !LoopPreds.insert(Cond).second;
7617 }
7618 ~MarkPendingLoopPredicate() {
7619 if (!Pending)
7620 LoopPreds.erase(Cond);
7621 }
7622};
Benjamin Kramer039b1042015-10-28 13:54:36 +00007623} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007624
Dan Gohman430f0cc2009-07-21 23:03:19 +00007625/// isImpliedCond - Test whether the condition described by Pred, LHS,
7626/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007627bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007628 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00007629 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007630 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007631 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
7632 if (Mark.Pending)
7633 return false;
7634
Dan Gohman8b0a4192010-03-01 17:49:51 +00007635 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007637 if (BO->getOpcode() == Instruction::And) {
7638 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007639 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7640 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007641 } else if (BO->getOpcode() == Instruction::Or) {
7642 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007643 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7644 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007645 }
7646 }
7647
Dan Gohmane18c2d62010-08-10 23:46:30 +00007648 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007649 if (!ICI) return false;
7650
Andrew Trickfa594032012-11-29 18:35:13 +00007651 // Now that we found a conditional branch that dominates the loop or controls
7652 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00007653 ICmpInst::Predicate FoundPred;
7654 if (Inverse)
7655 FoundPred = ICI->getInversePredicate();
7656 else
7657 FoundPred = ICI->getPredicate();
7658
7659 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
7660 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00007661
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00007662 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
7663}
7664
7665bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
7666 const SCEV *RHS,
7667 ICmpInst::Predicate FoundPred,
7668 const SCEV *FoundLHS,
7669 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00007670 // Balance the types.
7671 if (getTypeSizeInBits(LHS->getType()) <
7672 getTypeSizeInBits(FoundLHS->getType())) {
7673 if (CmpInst::isSigned(Pred)) {
7674 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
7675 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
7676 } else {
7677 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
7678 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
7679 }
7680 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00007681 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00007682 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007683 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
7684 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
7685 } else {
7686 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
7687 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
7688 }
7689 }
7690
Dan Gohman430f0cc2009-07-21 23:03:19 +00007691 // Canonicalize the query to match the way instcombine will have
7692 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00007693 if (SimplifyICmpOperands(Pred, LHS, RHS))
7694 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00007695 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00007696 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
7697 if (FoundLHS == FoundRHS)
7698 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00007699
7700 // Check to see if we can make the LHS or RHS match.
7701 if (LHS == FoundRHS || RHS == FoundLHS) {
7702 if (isa<SCEVConstant>(RHS)) {
7703 std::swap(FoundLHS, FoundRHS);
7704 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
7705 } else {
7706 std::swap(LHS, RHS);
7707 Pred = ICmpInst::getSwappedPredicate(Pred);
7708 }
7709 }
7710
7711 // Check whether the found predicate is the same as the desired predicate.
7712 if (FoundPred == Pred)
7713 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7714
7715 // Check whether swapping the found predicate makes it the same as the
7716 // desired predicate.
7717 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
7718 if (isa<SCEVConstant>(RHS))
7719 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
7720 else
7721 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
7722 RHS, LHS, FoundLHS, FoundRHS);
7723 }
7724
Sanjoy Das6e78b172015-10-22 19:57:34 +00007725 // Unsigned comparison is the same as signed comparison when both the operands
7726 // are non-negative.
7727 if (CmpInst::isUnsigned(FoundPred) &&
7728 CmpInst::getSignedPredicate(FoundPred) == Pred &&
7729 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
7730 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7731
Sanjoy Dasc5676df2014-11-13 00:00:58 +00007732 // Check if we can make progress by sharpening ranges.
7733 if (FoundPred == ICmpInst::ICMP_NE &&
7734 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
7735
7736 const SCEVConstant *C = nullptr;
7737 const SCEV *V = nullptr;
7738
7739 if (isa<SCEVConstant>(FoundLHS)) {
7740 C = cast<SCEVConstant>(FoundLHS);
7741 V = FoundRHS;
7742 } else {
7743 C = cast<SCEVConstant>(FoundRHS);
7744 V = FoundLHS;
7745 }
7746
7747 // The guarding predicate tells us that C != V. If the known range
7748 // of V is [C, t), we can sharpen the range to [C + 1, t). The
7749 // range we consider has to correspond to same signedness as the
7750 // predicate we're interested in folding.
7751
7752 APInt Min = ICmpInst::isSigned(Pred) ?
7753 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
7754
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007755 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00007756 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
7757 // This is true even if (Min + 1) wraps around -- in case of
7758 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
7759
7760 APInt SharperMin = Min + 1;
7761
7762 switch (Pred) {
7763 case ICmpInst::ICMP_SGE:
7764 case ICmpInst::ICMP_UGE:
7765 // We know V `Pred` SharperMin. If this implies LHS `Pred`
7766 // RHS, we're done.
7767 if (isImpliedCondOperands(Pred, LHS, RHS, V,
7768 getConstant(SharperMin)))
7769 return true;
7770
7771 case ICmpInst::ICMP_SGT:
7772 case ICmpInst::ICMP_UGT:
7773 // We know from the range information that (V `Pred` Min ||
7774 // V == Min). We know from the guarding condition that !(V
7775 // == Min). This gives us
7776 //
7777 // V `Pred` Min || V == Min && !(V == Min)
7778 // => V `Pred` Min
7779 //
7780 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
7781
7782 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
7783 return true;
7784
7785 default:
7786 // No change
7787 break;
7788 }
7789 }
7790 }
7791
Dan Gohman430f0cc2009-07-21 23:03:19 +00007792 // Check whether the actual condition is beyond sufficient.
7793 if (FoundPred == ICmpInst::ICMP_EQ)
7794 if (ICmpInst::isTrueWhenEqual(Pred))
7795 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
7796 return true;
7797 if (Pred == ICmpInst::ICMP_NE)
7798 if (!ICmpInst::isTrueWhenEqual(FoundPred))
7799 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
7800 return true;
7801
7802 // Otherwise assume the worst.
7803 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007804}
7805
Sanjoy Das1ed69102015-10-13 02:53:27 +00007806bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
7807 const SCEV *&L, const SCEV *&R,
7808 SCEV::NoWrapFlags &Flags) {
7809 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
7810 if (!AE || AE->getNumOperands() != 2)
7811 return false;
7812
7813 L = AE->getOperand(0);
7814 R = AE->getOperand(1);
7815 Flags = AE->getNoWrapFlags();
7816 return true;
7817}
7818
7819bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
7820 const SCEV *More,
7821 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00007822 // We avoid subtracting expressions here because this function is usually
7823 // fairly deep in the call stack (i.e. is called many times).
7824
Sanjoy Das96709c42015-09-25 23:53:45 +00007825 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
7826 const auto *LAR = cast<SCEVAddRecExpr>(Less);
7827 const auto *MAR = cast<SCEVAddRecExpr>(More);
7828
7829 if (LAR->getLoop() != MAR->getLoop())
7830 return false;
7831
7832 // We look at affine expressions only; not for correctness but to keep
7833 // getStepRecurrence cheap.
7834 if (!LAR->isAffine() || !MAR->isAffine())
7835 return false;
7836
Sanjoy Das1ed69102015-10-13 02:53:27 +00007837 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00007838 return false;
7839
7840 Less = LAR->getStart();
7841 More = MAR->getStart();
7842
7843 // fall through
7844 }
7845
7846 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007847 const auto &M = cast<SCEVConstant>(More)->getAPInt();
7848 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00007849 C = M - L;
7850 return true;
7851 }
7852
7853 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007854 SCEV::NoWrapFlags Flags;
7855 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007856 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7857 if (R == More) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007858 C = -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00007859 return true;
7860 }
7861
Sanjoy Das1ed69102015-10-13 02:53:27 +00007862 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007863 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7864 if (R == Less) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007865 C = LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00007866 return true;
7867 }
7868
7869 return false;
7870}
7871
7872bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
7873 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
7874 const SCEV *FoundLHS, const SCEV *FoundRHS) {
7875 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
7876 return false;
7877
7878 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7879 if (!AddRecLHS)
7880 return false;
7881
7882 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
7883 if (!AddRecFoundLHS)
7884 return false;
7885
7886 // We'd like to let SCEV reason about control dependencies, so we constrain
7887 // both the inequalities to be about add recurrences on the same loop. This
7888 // way we can use isLoopEntryGuardedByCond later.
7889
7890 const Loop *L = AddRecFoundLHS->getLoop();
7891 if (L != AddRecLHS->getLoop())
7892 return false;
7893
7894 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
7895 //
7896 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
7897 // ... (2)
7898 //
7899 // Informal proof for (2), assuming (1) [*]:
7900 //
7901 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
7902 //
7903 // Then
7904 //
7905 // FoundLHS s< FoundRHS s< INT_MIN - C
7906 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
7907 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
7908 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
7909 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
7910 // <=> FoundLHS + C s< FoundRHS + C
7911 //
7912 // [*]: (1) can be proved by ruling out overflow.
7913 //
7914 // [**]: This can be proved by analyzing all the four possibilities:
7915 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
7916 // (A s>= 0, B s>= 0).
7917 //
7918 // Note:
7919 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
7920 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
7921 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
7922 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
7923 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
7924 // C)".
7925
7926 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007927 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
7928 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00007929 LDiff != RDiff)
7930 return false;
7931
7932 if (LDiff == 0)
7933 return true;
7934
Sanjoy Das96709c42015-09-25 23:53:45 +00007935 APInt FoundRHSLimit;
7936
7937 if (Pred == CmpInst::ICMP_ULT) {
7938 FoundRHSLimit = -RDiff;
7939 } else {
7940 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00007941 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00007942 }
7943
7944 // Try to prove (1) or (2), as needed.
7945 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
7946 getConstant(FoundRHSLimit));
7947}
7948
Dan Gohman430f0cc2009-07-21 23:03:19 +00007949/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00007950/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007951/// and FoundRHS is true.
7952bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
7953 const SCEV *LHS, const SCEV *RHS,
7954 const SCEV *FoundLHS,
7955 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00007956 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
7957 return true;
7958
Sanjoy Das96709c42015-09-25 23:53:45 +00007959 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
7960 return true;
7961
Dan Gohman430f0cc2009-07-21 23:03:19 +00007962 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
7963 FoundLHS, FoundRHS) ||
7964 // ~x < ~y --> x > y
7965 isImpliedCondOperandsHelper(Pred, LHS, RHS,
7966 getNotSCEV(FoundRHS),
7967 getNotSCEV(FoundLHS));
7968}
7969
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007970
7971/// If Expr computes ~A, return A else return nullptr
7972static const SCEV *MatchNotExpr(const SCEV *Expr) {
7973 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007974 if (!Add || Add->getNumOperands() != 2 ||
7975 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007976 return nullptr;
7977
7978 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007979 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
7980 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007981 return nullptr;
7982
7983 return AddRHS->getOperand(1);
7984}
7985
7986
7987/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7988template<typename MaxExprType>
7989static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7990 const SCEV *Candidate) {
7991 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7992 if (!MaxExpr) return false;
7993
Sanjoy Das347d2722015-12-01 07:49:27 +00007994 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007995}
7996
7997
7998/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7999template<typename MaxExprType>
8000static bool IsMinConsistingOf(ScalarEvolution &SE,
8001 const SCEV *MaybeMinExpr,
8002 const SCEV *Candidate) {
8003 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8004 if (!MaybeMaxExpr)
8005 return false;
8006
8007 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8008}
8009
Hal Finkela8d205f2015-08-19 01:51:51 +00008010static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8011 ICmpInst::Predicate Pred,
8012 const SCEV *LHS, const SCEV *RHS) {
8013
8014 // If both sides are affine addrecs for the same loop, with equal
8015 // steps, and we know the recurrences don't wrap, then we only
8016 // need to check the predicate on the starting values.
8017
8018 if (!ICmpInst::isRelational(Pred))
8019 return false;
8020
8021 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8022 if (!LAR)
8023 return false;
8024 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8025 if (!RAR)
8026 return false;
8027 if (LAR->getLoop() != RAR->getLoop())
8028 return false;
8029 if (!LAR->isAffine() || !RAR->isAffine())
8030 return false;
8031
8032 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8033 return false;
8034
Hal Finkelff08a2e2015-08-19 17:26:07 +00008035 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8036 SCEV::FlagNSW : SCEV::FlagNUW;
8037 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008038 return false;
8039
8040 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8041}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008042
8043/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8044/// expression?
8045static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8046 ICmpInst::Predicate Pred,
8047 const SCEV *LHS, const SCEV *RHS) {
8048 switch (Pred) {
8049 default:
8050 return false;
8051
8052 case ICmpInst::ICMP_SGE:
8053 std::swap(LHS, RHS);
8054 // fall through
8055 case ICmpInst::ICMP_SLE:
8056 return
8057 // min(A, ...) <= A
8058 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8059 // A <= max(A, ...)
8060 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8061
8062 case ICmpInst::ICMP_UGE:
8063 std::swap(LHS, RHS);
8064 // fall through
8065 case ICmpInst::ICMP_ULE:
8066 return
8067 // min(A, ...) <= A
8068 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8069 // A <= max(A, ...)
8070 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8071 }
8072
8073 llvm_unreachable("covered switch fell through?!");
8074}
8075
Dan Gohman430f0cc2009-07-21 23:03:19 +00008076/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00008077/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008078/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00008079bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008080ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8081 const SCEV *LHS, const SCEV *RHS,
8082 const SCEV *FoundLHS,
8083 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008084 auto IsKnownPredicateFull =
8085 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008086 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008087 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008088 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8089 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008090 };
8091
Dan Gohmane65c9172009-07-13 21:35:55 +00008092 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008093 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8094 case ICmpInst::ICMP_EQ:
8095 case ICmpInst::ICMP_NE:
8096 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8097 return true;
8098 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008099 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008100 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008101 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8102 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008103 return true;
8104 break;
8105 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008106 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008107 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8108 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008109 return true;
8110 break;
8111 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008112 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008113 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8114 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008115 return true;
8116 break;
8117 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008118 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008119 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8120 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008121 return true;
8122 break;
8123 }
8124
8125 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008126}
8127
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008128/// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
8129/// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
8130bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8131 const SCEV *LHS,
8132 const SCEV *RHS,
8133 const SCEV *FoundLHS,
8134 const SCEV *FoundRHS) {
8135 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8136 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8137 // reduce the compile time impact of this optimization.
8138 return false;
8139
8140 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8141 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8142 !isa<SCEVConstant>(AddLHS->getOperand(0)))
8143 return false;
8144
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008145 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008146
8147 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8148 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8149 ConstantRange FoundLHSRange =
8150 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8151
8152 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8153 // for `LHS`:
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008154 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008155 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8156
8157 // We can also compute the range of values for `LHS` that satisfy the
8158 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008159 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008160 ConstantRange SatisfyingLHSRange =
8161 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8162
8163 // The antecedent implies the consequent if every value of `LHS` that
8164 // satisfies the antecedent also satisfies the consequent.
8165 return SatisfyingLHSRange.contains(LHSRange);
8166}
8167
Johannes Doerfert2683e562015-02-09 12:34:23 +00008168// Verify if an linear IV with positive stride can overflow when in a
8169// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008170// stride and the knowledge of NSW/NUW flags on the recurrence.
8171bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8172 bool IsSigned, bool NoWrap) {
8173 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008174
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008175 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008176 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008177
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008178 if (IsSigned) {
8179 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8180 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8181 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8182 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008183
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008184 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8185 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008186 }
Dan Gohman01048422009-06-21 23:46:38 +00008187
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008188 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8189 APInt MaxValue = APInt::getMaxValue(BitWidth);
8190 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8191 .getUnsignedMax();
8192
8193 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8194 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8195}
8196
Johannes Doerfert2683e562015-02-09 12:34:23 +00008197// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008198// greater-than comparison, knowing the invariant term of the comparison,
8199// the stride and the knowledge of NSW/NUW flags on the recurrence.
8200bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8201 bool IsSigned, bool NoWrap) {
8202 if (NoWrap) return false;
8203
8204 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008205 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008206
8207 if (IsSigned) {
8208 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8209 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8210 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8211 .getSignedMax();
8212
8213 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8214 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8215 }
8216
8217 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8218 APInt MinValue = APInt::getMinValue(BitWidth);
8219 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8220 .getUnsignedMax();
8221
8222 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8223 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8224}
8225
8226// Compute the backedge taken count knowing the interval difference, the
8227// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00008228const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008229 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008230 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008231 Delta = Equality ? getAddExpr(Delta, Step)
8232 : getAddExpr(Delta, getMinusSCEV(Step, One));
8233 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008234}
8235
Chris Lattner587a75b2005-08-15 23:33:51 +00008236/// HowManyLessThans - Return the number of times a backedge containing the
8237/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00008238/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00008239///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008240/// @param ControlsExit is true when the LHS < RHS condition directly controls
8241/// the branch (loops exits only if condition is true). In this case, we can use
8242/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00008243ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00008244ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008245 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008246 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008247 // We handle only IV < Invariant
8248 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008249 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008250
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008251 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00008252
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008253 // Avoid weird loops
8254 if (!IV || IV->getLoop() != L || !IV->isAffine())
8255 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008256
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008257 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008258 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008259
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008260 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008261
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008262 // Avoid negative or zero stride values
8263 if (!isKnownPositive(Stride))
8264 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008265
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008266 // Avoid proven overflow cases: this will ensure that the backedge taken count
8267 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008268 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008269 // behaviors like the case of C language.
8270 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8271 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008272
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008273 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8274 : ICmpInst::ICMP_ULT;
8275 const SCEV *Start = IV->getStart();
8276 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008277 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8278 const SCEV *Diff = getMinusSCEV(RHS, Start);
8279 // If we have NoWrap set, then we can assume that the increment won't
8280 // overflow, in which case if RHS - Start is a constant, we don't need to
8281 // do a max operation since we can just figure it out statically
8282 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008283 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008284 if (D.isNegative())
8285 End = Start;
8286 } else
8287 End = IsSigned ? getSMaxExpr(RHS, Start)
8288 : getUMaxExpr(RHS, Start);
8289 }
Dan Gohman51aaf022010-01-26 04:40:18 +00008290
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008291 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008292
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008293 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8294 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008295
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008296 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8297 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008298
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008299 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8300 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8301 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008302
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008303 // Although End can be a MAX expression we estimate MaxEnd considering only
8304 // the case End = RHS. This is safe because in the other case (End - Start)
8305 // is zero, leading to a zero maximum backedge taken count.
8306 APInt MaxEnd =
8307 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8308 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8309
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008310 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008311 if (isa<SCEVConstant>(BECount))
8312 MaxBECount = BECount;
8313 else
8314 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8315 getConstant(MinStride), false);
8316
8317 if (isa<SCEVCouldNotCompute>(MaxBECount))
8318 MaxBECount = BECount;
8319
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008320 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008321}
8322
8323ScalarEvolution::ExitLimit
8324ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8325 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008326 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008327 // We handle only IV > Invariant
8328 if (!isLoopInvariant(RHS, L))
8329 return getCouldNotCompute();
8330
8331 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8332
8333 // Avoid weird loops
8334 if (!IV || IV->getLoop() != L || !IV->isAffine())
8335 return getCouldNotCompute();
8336
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008337 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008338 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8339
8340 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8341
8342 // Avoid negative or zero stride values
8343 if (!isKnownPositive(Stride))
8344 return getCouldNotCompute();
8345
8346 // Avoid proven overflow cases: this will ensure that the backedge taken count
8347 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008348 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008349 // behaviors like the case of C language.
8350 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8351 return getCouldNotCompute();
8352
8353 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8354 : ICmpInst::ICMP_UGT;
8355
8356 const SCEV *Start = IV->getStart();
8357 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008358 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8359 const SCEV *Diff = getMinusSCEV(RHS, Start);
8360 // If we have NoWrap set, then we can assume that the increment won't
8361 // overflow, in which case if RHS - Start is a constant, we don't need to
8362 // do a max operation since we can just figure it out statically
8363 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008364 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008365 if (!D.isNegative())
8366 End = Start;
8367 } else
8368 End = IsSigned ? getSMinExpr(RHS, Start)
8369 : getUMinExpr(RHS, Start);
8370 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008371
8372 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8373
8374 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8375 : getUnsignedRange(Start).getUnsignedMax();
8376
8377 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8378 : getUnsignedRange(Stride).getUnsignedMin();
8379
8380 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8381 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8382 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8383
8384 // Although End can be a MIN expression we estimate MinEnd considering only
8385 // the case End = RHS. This is safe because in the other case (Start - End)
8386 // is zero, leading to a zero maximum backedge taken count.
8387 APInt MinEnd =
8388 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8389 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8390
8391
8392 const SCEV *MaxBECount = getCouldNotCompute();
8393 if (isa<SCEVConstant>(BECount))
8394 MaxBECount = BECount;
8395 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008396 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008397 getConstant(MinStride), false);
8398
8399 if (isa<SCEVCouldNotCompute>(MaxBECount))
8400 MaxBECount = BECount;
8401
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008402 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00008403}
8404
Chris Lattnerd934c702004-04-02 20:23:17 +00008405/// getNumIterationsInRange - Return the number of iterations of this loop that
8406/// produce values in the specified constant range. Another way of looking at
8407/// this is that it returns the first iteration number where the value is not in
8408/// the condition, thus computing the exit count. If the iteration count can't
8409/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00008410const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008411 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008412 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008413 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008414
8415 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008417 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008418 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008419 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008420 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008421 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008422 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008423 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008424 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008425 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008426 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008427 }
8428
8429 // The only time we can solve this is when we have all constant indices.
8430 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008431 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008432 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008433
8434 // Okay at this point we know that all elements of the chrec are constants and
8435 // that the start element is zero.
8436
8437 // First check to see if the range contains zero. If not, the first
8438 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008439 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008440 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008441 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008442
Chris Lattnerd934c702004-04-02 20:23:17 +00008443 if (isAffine()) {
8444 // If this is an affine expression then we have this situation:
8445 // Solve {0,+,A} in Range === Ax in Range
8446
Nick Lewycky52460262007-07-16 02:08:00 +00008447 // We know that zero is in the range. If A is positive then we know that
8448 // the upper value of the range must be the first possible exit value.
8449 // If A is negative then the lower of the range is the last possible loop
8450 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008451 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008452 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008453 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008454
Nick Lewycky52460262007-07-16 02:08:00 +00008455 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008456 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008457 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008458
8459 // Evaluate at the exit value. If we really did fall out of the valid
8460 // range, then we computed our trip count, otherwise wrap around or other
8461 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008462 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008463 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008464 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008465
8466 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008467 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008468 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008469 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008470 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008471 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008472 } else if (isQuadratic()) {
8473 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8474 // quadratic equation to solve it. To do this, we must frame our problem in
8475 // terms of figuring out when zero is crossed, instead of when
8476 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008477 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008478 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008479 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8480 // getNoWrapFlags(FlagNW)
8481 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008482
8483 // Next, solve the constructed addrec
Sanjoy Das01947432015-11-22 21:20:13 +00008484 auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00008485 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8486 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00008487 if (R1) {
8488 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008489 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8490 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008491 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00008492 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008493
Chris Lattnerd934c702004-04-02 20:23:17 +00008494 // Make sure the root is not off by one. The returned iteration should
8495 // not be in the range, but the previous one should be. When solving
8496 // for "X*X < 5", for example, we should not return a root of 2.
8497 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00008498 R1->getValue(),
8499 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008500 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008501 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008502 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008503 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008504
Dan Gohmana37eaf22007-10-22 18:31:58 +00008505 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008506 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008507 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00008508 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008509 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008510
Chris Lattnerd934c702004-04-02 20:23:17 +00008511 // If R1 was not in the range, then it is a good return value. Make
8512 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008513 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008514 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008515 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008516 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008517 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00008518 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008519 }
8520 }
8521 }
8522
Dan Gohman31efa302009-04-18 17:58:19 +00008523 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008524}
8525
Sebastian Pop448712b2014-05-07 18:01:20 +00008526namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008527struct FindUndefs {
8528 bool Found;
8529 FindUndefs() : Found(false) {}
8530
8531 bool follow(const SCEV *S) {
8532 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8533 if (isa<UndefValue>(C->getValue()))
8534 Found = true;
8535 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8536 if (isa<UndefValue>(C->getValue()))
8537 Found = true;
8538 }
8539
8540 // Keep looking if we haven't found it yet.
8541 return !Found;
8542 }
8543 bool isDone() const {
8544 // Stop recursion if we have found an undef.
8545 return Found;
8546 }
8547};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008548}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008549
8550// Return true when S contains at least an undef value.
8551static inline bool
8552containsUndefs(const SCEV *S) {
8553 FindUndefs F;
8554 SCEVTraversal<FindUndefs> ST(F);
8555 ST.visitAll(S);
8556
8557 return F.Found;
8558}
8559
8560namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008561// Collect all steps of SCEV expressions.
8562struct SCEVCollectStrides {
8563 ScalarEvolution &SE;
8564 SmallVectorImpl<const SCEV *> &Strides;
8565
8566 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8567 : SE(SE), Strides(S) {}
8568
8569 bool follow(const SCEV *S) {
8570 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8571 Strides.push_back(AR->getStepRecurrence(SE));
8572 return true;
8573 }
8574 bool isDone() const { return false; }
8575};
8576
8577// Collect all SCEVUnknown and SCEVMulExpr expressions.
8578struct SCEVCollectTerms {
8579 SmallVectorImpl<const SCEV *> &Terms;
8580
8581 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8582 : Terms(T) {}
8583
8584 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008585 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008586 if (!containsUndefs(S))
8587 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00008588
8589 // Stop recursion: once we collected a term, do not walk its operands.
8590 return false;
8591 }
8592
8593 // Keep looking.
8594 return true;
8595 }
8596 bool isDone() const { return false; }
8597};
Tobias Grosser374bce02015-10-12 08:02:00 +00008598
8599// Check if a SCEV contains an AddRecExpr.
8600struct SCEVHasAddRec {
8601 bool &ContainsAddRec;
8602
8603 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8604 ContainsAddRec = false;
8605 }
8606
8607 bool follow(const SCEV *S) {
8608 if (isa<SCEVAddRecExpr>(S)) {
8609 ContainsAddRec = true;
8610
8611 // Stop recursion: once we collected a term, do not walk its operands.
8612 return false;
8613 }
8614
8615 // Keep looking.
8616 return true;
8617 }
8618 bool isDone() const { return false; }
8619};
8620
8621// Find factors that are multiplied with an expression that (possibly as a
8622// subexpression) contains an AddRecExpr. In the expression:
8623//
8624// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
8625//
8626// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8627// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8628// parameters as they form a product with an induction variable.
8629//
8630// This collector expects all array size parameters to be in the same MulExpr.
8631// It might be necessary to later add support for collecting parameters that are
8632// spread over different nested MulExpr.
8633struct SCEVCollectAddRecMultiplies {
8634 SmallVectorImpl<const SCEV *> &Terms;
8635 ScalarEvolution &SE;
8636
8637 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
8638 : Terms(T), SE(SE) {}
8639
8640 bool follow(const SCEV *S) {
8641 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
8642 bool HasAddRec = false;
8643 SmallVector<const SCEV *, 0> Operands;
8644 for (auto Op : Mul->operands()) {
8645 if (isa<SCEVUnknown>(Op)) {
8646 Operands.push_back(Op);
8647 } else {
8648 bool ContainsAddRec;
8649 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
8650 visitAll(Op, ContiansAddRec);
8651 HasAddRec |= ContainsAddRec;
8652 }
8653 }
8654 if (Operands.size() == 0)
8655 return true;
8656
8657 if (!HasAddRec)
8658 return false;
8659
8660 Terms.push_back(SE.getMulExpr(Operands));
8661 // Stop recursion: once we collected a term, do not walk its operands.
8662 return false;
8663 }
8664
8665 // Keep looking.
8666 return true;
8667 }
8668 bool isDone() const { return false; }
8669};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008670}
Sebastian Pop448712b2014-05-07 18:01:20 +00008671
Tobias Grosser374bce02015-10-12 08:02:00 +00008672/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
8673/// two places:
8674/// 1) The strides of AddRec expressions.
8675/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008676void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
8677 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008678 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008679 SCEVCollectStrides StrideCollector(*this, Strides);
8680 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008681
8682 DEBUG({
8683 dbgs() << "Strides:\n";
8684 for (const SCEV *S : Strides)
8685 dbgs() << *S << "\n";
8686 });
8687
8688 for (const SCEV *S : Strides) {
8689 SCEVCollectTerms TermCollector(Terms);
8690 visitAll(S, TermCollector);
8691 }
8692
8693 DEBUG({
8694 dbgs() << "Terms:\n";
8695 for (const SCEV *T : Terms)
8696 dbgs() << *T << "\n";
8697 });
Tobias Grosser374bce02015-10-12 08:02:00 +00008698
8699 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
8700 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008701}
8702
Sebastian Popb1a548f2014-05-12 19:01:53 +00008703static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00008704 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00008705 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00008706 int Last = Terms.size() - 1;
8707 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00008708
Sebastian Pop448712b2014-05-07 18:01:20 +00008709 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00008710 if (Last == 0) {
8711 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008712 SmallVector<const SCEV *, 2> Qs;
8713 for (const SCEV *Op : M->operands())
8714 if (!isa<SCEVConstant>(Op))
8715 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00008716
Sebastian Pope30bd352014-05-27 22:41:56 +00008717 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00008718 }
8719
Sebastian Pope30bd352014-05-27 22:41:56 +00008720 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008721 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00008722 }
8723
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008724 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008725 // Normalize the terms before the next call to findArrayDimensionsRec.
8726 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008727 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008728
8729 // Bail out when GCD does not evenly divide one of the terms.
8730 if (!R->isZero())
8731 return false;
8732
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008733 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00008734 }
8735
Tobias Grosser3080cf12014-05-08 07:55:34 +00008736 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00008737 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
8738 return isa<SCEVConstant>(E);
8739 }),
8740 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00008741
Sebastian Pop448712b2014-05-07 18:01:20 +00008742 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00008743 if (!findArrayDimensionsRec(SE, Terms, Sizes))
8744 return false;
8745
Sebastian Pope30bd352014-05-27 22:41:56 +00008746 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008747 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00008748}
Sebastian Popc62c6792013-11-12 22:47:20 +00008749
Sebastian Pop448712b2014-05-07 18:01:20 +00008750// Returns true when S contains at least a SCEVUnknown parameter.
8751static inline bool
8752containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00008753 struct FindParameter {
8754 bool FoundParameter;
8755 FindParameter() : FoundParameter(false) {}
8756
8757 bool follow(const SCEV *S) {
8758 if (isa<SCEVUnknown>(S)) {
8759 FoundParameter = true;
8760 // Stop recursion: we found a parameter.
8761 return false;
8762 }
8763 // Keep looking.
8764 return true;
8765 }
8766 bool isDone() const {
8767 // Stop recursion if we have found a parameter.
8768 return FoundParameter;
8769 }
8770 };
8771
Sebastian Pop448712b2014-05-07 18:01:20 +00008772 FindParameter F;
8773 SCEVTraversal<FindParameter> ST(F);
8774 ST.visitAll(S);
8775
8776 return F.FoundParameter;
8777}
8778
8779// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
8780static inline bool
8781containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
8782 for (const SCEV *T : Terms)
8783 if (containsParameters(T))
8784 return true;
8785 return false;
8786}
8787
8788// Return the number of product terms in S.
8789static inline int numberOfTerms(const SCEV *S) {
8790 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
8791 return Expr->getNumOperands();
8792 return 1;
8793}
8794
Sebastian Popa6e58602014-05-27 22:41:45 +00008795static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
8796 if (isa<SCEVConstant>(T))
8797 return nullptr;
8798
8799 if (isa<SCEVUnknown>(T))
8800 return T;
8801
8802 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
8803 SmallVector<const SCEV *, 2> Factors;
8804 for (const SCEV *Op : M->operands())
8805 if (!isa<SCEVConstant>(Op))
8806 Factors.push_back(Op);
8807
8808 return SE.getMulExpr(Factors);
8809 }
8810
8811 return T;
8812}
8813
8814/// Return the size of an element read or written by Inst.
8815const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
8816 Type *Ty;
8817 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
8818 Ty = Store->getValueOperand()->getType();
8819 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00008820 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00008821 else
8822 return nullptr;
8823
8824 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
8825 return getSizeOfExpr(ETy, Ty);
8826}
8827
Sebastian Pop448712b2014-05-07 18:01:20 +00008828/// Second step of delinearization: compute the array dimensions Sizes from the
8829/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00008830void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
8831 SmallVectorImpl<const SCEV *> &Sizes,
8832 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00008833
Sebastian Pop53524082014-05-29 19:44:05 +00008834 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00008835 return;
8836
8837 // Early return when Terms do not contain parameters: we do not delinearize
8838 // non parametric SCEVs.
8839 if (!containsParameters(Terms))
8840 return;
8841
8842 DEBUG({
8843 dbgs() << "Terms:\n";
8844 for (const SCEV *T : Terms)
8845 dbgs() << *T << "\n";
8846 });
8847
8848 // Remove duplicates.
8849 std::sort(Terms.begin(), Terms.end());
8850 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
8851
8852 // Put larger terms first.
8853 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
8854 return numberOfTerms(LHS) > numberOfTerms(RHS);
8855 });
8856
Sebastian Popa6e58602014-05-27 22:41:45 +00008857 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8858
Tobias Grosser374bce02015-10-12 08:02:00 +00008859 // Try to divide all terms by the element size. If term is not divisible by
8860 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00008861 for (const SCEV *&Term : Terms) {
8862 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008863 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00008864 if (!Q->isZero())
8865 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00008866 }
8867
8868 SmallVector<const SCEV *, 4> NewTerms;
8869
8870 // Remove constant factors.
8871 for (const SCEV *T : Terms)
8872 if (const SCEV *NewT = removeConstantFactors(SE, T))
8873 NewTerms.push_back(NewT);
8874
Sebastian Pop448712b2014-05-07 18:01:20 +00008875 DEBUG({
8876 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00008877 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00008878 dbgs() << *T << "\n";
8879 });
8880
Sebastian Popa6e58602014-05-27 22:41:45 +00008881 if (NewTerms.empty() ||
8882 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00008883 Sizes.clear();
8884 return;
8885 }
Sebastian Pop448712b2014-05-07 18:01:20 +00008886
Sebastian Popa6e58602014-05-27 22:41:45 +00008887 // The last element to be pushed into Sizes is the size of an element.
8888 Sizes.push_back(ElementSize);
8889
Sebastian Pop448712b2014-05-07 18:01:20 +00008890 DEBUG({
8891 dbgs() << "Sizes:\n";
8892 for (const SCEV *S : Sizes)
8893 dbgs() << *S << "\n";
8894 });
8895}
8896
8897/// Third step of delinearization: compute the access functions for the
8898/// Subscripts based on the dimensions in Sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008899void ScalarEvolution::computeAccessFunctions(
8900 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
8901 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008902
Sebastian Popb1a548f2014-05-12 19:01:53 +00008903 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008904 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00008905 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008906
Sanjoy Das1195dbe2015-10-08 03:45:58 +00008907 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008908 if (!AR->isAffine())
8909 return;
8910
8911 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00008912 int Last = Sizes.size() - 1;
8913 for (int i = Last; i >= 0; i--) {
8914 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008915 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00008916
8917 DEBUG({
8918 dbgs() << "Res: " << *Res << "\n";
8919 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
8920 dbgs() << "Res divided by Sizes[i]:\n";
8921 dbgs() << "Quotient: " << *Q << "\n";
8922 dbgs() << "Remainder: " << *R << "\n";
8923 });
8924
8925 Res = Q;
8926
Sebastian Popa6e58602014-05-27 22:41:45 +00008927 // Do not record the last subscript corresponding to the size of elements in
8928 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00008929 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008930
8931 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00008932 if (isa<SCEVAddRecExpr>(R)) {
8933 Subscripts.clear();
8934 Sizes.clear();
8935 return;
8936 }
Sebastian Popa6e58602014-05-27 22:41:45 +00008937
Sebastian Pop448712b2014-05-07 18:01:20 +00008938 continue;
8939 }
8940
8941 // Record the access function for the current subscript.
8942 Subscripts.push_back(R);
8943 }
8944
8945 // Also push in last position the remainder of the last division: it will be
8946 // the access function of the innermost dimension.
8947 Subscripts.push_back(Res);
8948
8949 std::reverse(Subscripts.begin(), Subscripts.end());
8950
8951 DEBUG({
8952 dbgs() << "Subscripts:\n";
8953 for (const SCEV *S : Subscripts)
8954 dbgs() << *S << "\n";
8955 });
Sebastian Pop448712b2014-05-07 18:01:20 +00008956}
8957
Sebastian Popc62c6792013-11-12 22:47:20 +00008958/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
8959/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00008960/// is the offset start of the array. The SCEV->delinearize algorithm computes
8961/// the multiples of SCEV coefficients: that is a pattern matching of sub
8962/// expressions in the stride and base of a SCEV corresponding to the
8963/// computation of a GCD (greatest common divisor) of base and stride. When
8964/// SCEV->delinearize fails, it returns the SCEV unchanged.
8965///
8966/// For example: when analyzing the memory access A[i][j][k] in this loop nest
8967///
8968/// void foo(long n, long m, long o, double A[n][m][o]) {
8969///
8970/// for (long i = 0; i < n; i++)
8971/// for (long j = 0; j < m; j++)
8972/// for (long k = 0; k < o; k++)
8973/// A[i][j][k] = 1.0;
8974/// }
8975///
8976/// the delinearization input is the following AddRec SCEV:
8977///
8978/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
8979///
8980/// From this SCEV, we are able to say that the base offset of the access is %A
8981/// because it appears as an offset that does not divide any of the strides in
8982/// the loops:
8983///
8984/// CHECK: Base offset: %A
8985///
8986/// and then SCEV->delinearize determines the size of some of the dimensions of
8987/// the array as these are the multiples by which the strides are happening:
8988///
8989/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
8990///
8991/// Note that the outermost dimension remains of UnknownSize because there are
8992/// no strides that would help identifying the size of the last dimension: when
8993/// the array has been statically allocated, one could compute the size of that
8994/// dimension by dividing the overall size of the array by the size of the known
8995/// dimensions: %m * %o * 8.
8996///
8997/// Finally delinearize provides the access functions for the array reference
8998/// that does correspond to A[i][j][k] of the above C testcase:
8999///
9000/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9001///
9002/// The testcases are checking the output of a function pass:
9003/// DelinearizationPass that walks through all loads and stores of a function
9004/// asking for the SCEV of the memory access with respect to all enclosing
9005/// loops, calling SCEV->delinearize on that and printing the results.
9006
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009007void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009008 SmallVectorImpl<const SCEV *> &Subscripts,
9009 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009010 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009011 // First step: collect parametric terms.
9012 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009013 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009014
Sebastian Popb1a548f2014-05-12 19:01:53 +00009015 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009016 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009017
Sebastian Pop448712b2014-05-07 18:01:20 +00009018 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009019 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009020
Sebastian Popb1a548f2014-05-12 19:01:53 +00009021 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009022 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009023
Sebastian Pop448712b2014-05-07 18:01:20 +00009024 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009025 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009026
Sebastian Pop28e6b972014-05-27 22:41:51 +00009027 if (Subscripts.empty())
9028 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009029
Sebastian Pop448712b2014-05-07 18:01:20 +00009030 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009031 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009032 dbgs() << "ArrayDecl[UnknownSize]";
9033 for (const SCEV *S : Sizes)
9034 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009035
Sebastian Pop444621a2014-05-09 22:45:02 +00009036 dbgs() << "\nArrayRef";
9037 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009038 dbgs() << "[" << *S << "]";
9039 dbgs() << "\n";
9040 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009041}
Chris Lattnerd934c702004-04-02 20:23:17 +00009042
9043//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009044// SCEVCallbackVH Class Implementation
9045//===----------------------------------------------------------------------===//
9046
Dan Gohmand33a0902009-05-19 19:22:47 +00009047void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009048 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009049 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9050 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009051 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009052 // this now dangles!
9053}
9054
Dan Gohman7a066722010-07-28 01:09:07 +00009055void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009056 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009057
Dan Gohman48f82222009-05-04 22:30:44 +00009058 // Forget all the expressions associated with users of the old value,
9059 // so that future queries will recompute the expressions using the new
9060 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009061 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009062 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009063 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009064 while (!Worklist.empty()) {
9065 User *U = Worklist.pop_back_val();
9066 // Deleting the Old value will cause this to dangle. Postpone
9067 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009068 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009069 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009070 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009071 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009072 if (PHINode *PN = dyn_cast<PHINode>(U))
9073 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009074 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009075 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009076 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009077 // Delete the Old value.
9078 if (PHINode *PN = dyn_cast<PHINode>(Old))
9079 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009080 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009081 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009082}
9083
Dan Gohmand33a0902009-05-19 19:22:47 +00009084ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009085 : CallbackVH(V), SE(se) {}
9086
9087//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009088// ScalarEvolution Class Implementation
9089//===----------------------------------------------------------------------===//
9090
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009091ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9092 AssumptionCache &AC, DominatorTree &DT,
9093 LoopInfo &LI)
9094 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9095 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009096 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9097 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9098 FirstUnknown(nullptr) {}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009099
9100ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9101 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
9102 CouldNotCompute(std::move(Arg.CouldNotCompute)),
9103 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009104 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009105 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9106 ConstantEvolutionLoopExitValue(
9107 std::move(Arg.ConstantEvolutionLoopExitValue)),
9108 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9109 LoopDispositions(std::move(Arg.LoopDispositions)),
9110 BlockDispositions(std::move(Arg.BlockDispositions)),
9111 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9112 SignedRanges(std::move(Arg.SignedRanges)),
9113 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009114 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009115 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9116 FirstUnknown(Arg.FirstUnknown) {
9117 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009118}
9119
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009120ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009121 // Iterate through all the SCEVUnknown instances and call their
9122 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009123 for (SCEVUnknown *U = FirstUnknown; U;) {
9124 SCEVUnknown *Tmp = U;
9125 U = U->Next;
9126 Tmp->~SCEVUnknown();
9127 }
Craig Topper9f008862014-04-15 04:59:12 +00009128 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009129
Wei Mia49559b2016-02-04 01:27:38 +00009130 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009131 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009132 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009133
9134 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9135 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009136 for (auto &BTCI : BackedgeTakenCounts)
9137 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009138
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009139 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009140 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009141 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009142}
9143
Dan Gohmanc8e23622009-04-21 23:15:49 +00009144bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009145 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009146}
9147
Dan Gohmanc8e23622009-04-21 23:15:49 +00009148static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009149 const Loop *L) {
9150 // Print all inner loops first
9151 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
9152 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009153
Dan Gohmanbc694912010-01-09 18:17:45 +00009154 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009155 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009156 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009157
Dan Gohmancb0efec2009-12-18 01:14:11 +00009158 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009159 L->getExitBlocks(ExitBlocks);
9160 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009161 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009162
Dan Gohman0bddac12009-02-24 18:55:53 +00009163 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9164 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009165 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009166 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009167 }
9168
Dan Gohmanbc694912010-01-09 18:17:45 +00009169 OS << "\n"
9170 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009171 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009172 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009173
9174 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9175 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9176 } else {
9177 OS << "Unpredictable max backedge-taken count. ";
9178 }
9179
9180 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009181}
9182
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009183void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009184 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009185 // out SCEV values of all instructions that are interesting. Doing
9186 // this potentially causes it to create new SCEV objects though,
9187 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009188 // observable from outside the class though, so casting away the
9189 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009190 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009191
Dan Gohmanbc694912010-01-09 18:17:45 +00009192 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009193 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009194 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009195 for (Instruction &I : instructions(F))
9196 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9197 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009198 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009199 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009200 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009201 if (!isa<SCEVCouldNotCompute>(SV)) {
9202 OS << " U: ";
9203 SE.getUnsignedRange(SV).print(OS);
9204 OS << " S: ";
9205 SE.getSignedRange(SV).print(OS);
9206 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009207
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009208 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009209
Dan Gohmanaf752342009-07-07 17:06:11 +00009210 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009211 if (AtUse != SV) {
9212 OS << " --> ";
9213 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009214 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9215 OS << " U: ";
9216 SE.getUnsignedRange(AtUse).print(OS);
9217 OS << " S: ";
9218 SE.getSignedRange(AtUse).print(OS);
9219 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009220 }
9221
9222 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009223 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009224 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009225 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009226 OS << "<<Unknown>>";
9227 } else {
9228 OS << *ExitValue;
9229 }
9230 }
9231
Chris Lattnerd934c702004-04-02 20:23:17 +00009232 OS << "\n";
9233 }
9234
Dan Gohmanbc694912010-01-09 18:17:45 +00009235 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009236 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009237 OS << "\n";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009238 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
Dan Gohmanc8e23622009-04-21 23:15:49 +00009239 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009240}
Dan Gohmane20f8242009-04-21 00:47:46 +00009241
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009242ScalarEvolution::LoopDisposition
9243ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009244 auto &Values = LoopDispositions[S];
9245 for (auto &V : Values) {
9246 if (V.getPointer() == L)
9247 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009248 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009249 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009250 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009251 auto &Values2 = LoopDispositions[S];
9252 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9253 if (V.getPointer() == L) {
9254 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009255 break;
9256 }
9257 }
9258 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009259}
9260
9261ScalarEvolution::LoopDisposition
9262ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009263 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009264 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009265 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009266 case scTruncate:
9267 case scZeroExtend:
9268 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009269 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009270 case scAddRecExpr: {
9271 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9272
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009273 // If L is the addrec's loop, it's computable.
9274 if (AR->getLoop() == L)
9275 return LoopComputable;
9276
Dan Gohmanafd6db92010-11-17 21:23:15 +00009277 // Add recurrences are never invariant in the function-body (null loop).
9278 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009279 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009280
9281 // This recurrence is variant w.r.t. L if L contains AR's loop.
9282 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009283 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009284
9285 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9286 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009287 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009288
9289 // This recurrence is variant w.r.t. L if any of its operands
9290 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009291 for (auto *Op : AR->operands())
9292 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009293 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009294
9295 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009296 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009297 }
9298 case scAddExpr:
9299 case scMulExpr:
9300 case scUMaxExpr:
9301 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009302 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009303 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9304 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009305 if (D == LoopVariant)
9306 return LoopVariant;
9307 if (D == LoopComputable)
9308 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009309 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009310 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009311 }
9312 case scUDivExpr: {
9313 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009314 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9315 if (LD == LoopVariant)
9316 return LoopVariant;
9317 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9318 if (RD == LoopVariant)
9319 return LoopVariant;
9320 return (LD == LoopInvariant && RD == LoopInvariant) ?
9321 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009322 }
9323 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009324 // All non-instruction values are loop invariant. All instructions are loop
9325 // invariant if they are not contained in the specified loop.
9326 // Instructions are never considered invariant in the function body
9327 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009328 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009329 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9330 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009331 case scCouldNotCompute:
9332 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009333 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009334 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009335}
9336
9337bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9338 return getLoopDisposition(S, L) == LoopInvariant;
9339}
9340
9341bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9342 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009343}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009344
Dan Gohman8ea83d82010-11-18 00:34:22 +00009345ScalarEvolution::BlockDisposition
9346ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009347 auto &Values = BlockDispositions[S];
9348 for (auto &V : Values) {
9349 if (V.getPointer() == BB)
9350 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009351 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009352 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009353 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009354 auto &Values2 = BlockDispositions[S];
9355 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9356 if (V.getPointer() == BB) {
9357 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009358 break;
9359 }
9360 }
9361 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009362}
9363
Dan Gohman8ea83d82010-11-18 00:34:22 +00009364ScalarEvolution::BlockDisposition
9365ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009366 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009367 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009368 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009369 case scTruncate:
9370 case scZeroExtend:
9371 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009372 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009373 case scAddRecExpr: {
9374 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009375 // to test for proper dominance too, because the instruction which
9376 // produces the addrec's value is a PHI, and a PHI effectively properly
9377 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009378 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009379 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009380 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009381 }
9382 // FALL THROUGH into SCEVNAryExpr handling.
9383 case scAddExpr:
9384 case scMulExpr:
9385 case scUMaxExpr:
9386 case scSMaxExpr: {
9387 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009388 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009389 for (const SCEV *NAryOp : NAry->operands()) {
9390 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009391 if (D == DoesNotDominateBlock)
9392 return DoesNotDominateBlock;
9393 if (D == DominatesBlock)
9394 Proper = false;
9395 }
9396 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009397 }
9398 case scUDivExpr: {
9399 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009400 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9401 BlockDisposition LD = getBlockDisposition(LHS, BB);
9402 if (LD == DoesNotDominateBlock)
9403 return DoesNotDominateBlock;
9404 BlockDisposition RD = getBlockDisposition(RHS, BB);
9405 if (RD == DoesNotDominateBlock)
9406 return DoesNotDominateBlock;
9407 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9408 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009409 }
9410 case scUnknown:
9411 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009412 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9413 if (I->getParent() == BB)
9414 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009415 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009416 return ProperlyDominatesBlock;
9417 return DoesNotDominateBlock;
9418 }
9419 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009420 case scCouldNotCompute:
9421 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009422 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009423 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009424}
9425
9426bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9427 return getBlockDisposition(S, BB) >= DominatesBlock;
9428}
9429
9430bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9431 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009432}
Dan Gohman534749b2010-11-17 22:27:42 +00009433
9434bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009435 // Search for a SCEV expression node within an expression tree.
9436 // Implements SCEVTraversal::Visitor.
9437 struct SCEVSearch {
9438 const SCEV *Node;
9439 bool IsFound;
9440
9441 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9442
9443 bool follow(const SCEV *S) {
9444 IsFound |= (S == Node);
9445 return !IsFound;
9446 }
9447 bool isDone() const { return IsFound; }
9448 };
9449
Andrew Trick365e31c2012-07-13 23:33:03 +00009450 SCEVSearch Search(Op);
9451 visitAll(S, Search);
9452 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009453}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009454
9455void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9456 ValuesAtScopes.erase(S);
9457 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009458 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009459 UnsignedRanges.erase(S);
9460 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009461 ExprValueMap.erase(S);
9462 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009463
9464 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
9465 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
9466 BackedgeTakenInfo &BEInfo = I->second;
9467 if (BEInfo.hasOperand(S, this)) {
9468 BEInfo.clear();
9469 BackedgeTakenCounts.erase(I++);
9470 }
9471 else
9472 ++I;
9473 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00009474}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009475
9476typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009477
Alp Tokercb402912014-01-24 17:20:08 +00009478/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009479static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9480 size_t Pos = 0;
9481 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9482 Str.replace(Pos, From.size(), To.data(), To.size());
9483 Pos += To.size();
9484 }
9485}
9486
Benjamin Kramer214935e2012-10-26 17:31:32 +00009487/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9488static void
9489getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009490 std::string &S = Map[L];
9491 if (S.empty()) {
9492 raw_string_ostream OS(S);
9493 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009494
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009495 // false and 0 are semantically equivalent. This can happen in dead loops.
9496 replaceSubString(OS.str(), "false", "0");
9497 // Remove wrap flags, their use in SCEV is highly fragile.
9498 // FIXME: Remove this when SCEV gets smarter about them.
9499 replaceSubString(OS.str(), "<nw>", "");
9500 replaceSubString(OS.str(), "<nsw>", "");
9501 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009502 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009503
JF Bastien61ad8b32015-12-23 18:18:53 +00009504 for (auto *R : reverse(*L))
9505 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009506}
9507
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009508void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009509 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9510
9511 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9512 // FIXME: It would be much better to store actual values instead of strings,
9513 // but SCEV pointers will change if we drop the caches.
9514 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009515 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009516 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9517
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009518 // Gather stringified backedge taken counts for all loops using a fresh
9519 // ScalarEvolution object.
9520 ScalarEvolution SE2(F, TLI, AC, DT, LI);
9521 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9522 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009523
9524 // Now compare whether they're the same with and without caches. This allows
9525 // verifying that no pass changed the cache.
9526 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9527 "New loops suddenly appeared!");
9528
9529 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9530 OldE = BackedgeDumpsOld.end(),
9531 NewI = BackedgeDumpsNew.begin();
9532 OldI != OldE; ++OldI, ++NewI) {
9533 assert(OldI->first == NewI->first && "Loop order changed!");
9534
9535 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9536 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009537 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009538 // means that a pass is buggy or SCEV has to learn a new pattern but is
9539 // usually not harmful.
9540 if (OldI->second != NewI->second &&
9541 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009542 NewI->second.find("undef") == std::string::npos &&
9543 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00009544 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009545 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00009546 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009547 << "' changed from '" << OldI->second
9548 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00009549 std::abort();
9550 }
9551 }
9552
9553 // TODO: Verify more things.
9554}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009555
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00009556template class llvm::AnalysisBase<ScalarEvolutionAnalysis>;
9557
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009558ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
9559 AnalysisManager<Function> *AM) {
9560 return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F),
9561 AM->getResult<AssumptionAnalysis>(F),
9562 AM->getResult<DominatorTreeAnalysis>(F),
9563 AM->getResult<LoopAnalysis>(F));
9564}
9565
9566PreservedAnalyses
9567ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) {
9568 AM->getResult<ScalarEvolutionAnalysis>(F).print(OS);
9569 return PreservedAnalyses::all();
9570}
9571
9572INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9573 "Scalar Evolution Analysis", false, true)
9574INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9575INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9576INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9577INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9578INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
9579 "Scalar Evolution Analysis", false, true)
9580char ScalarEvolutionWrapperPass::ID = 0;
9581
9582ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
9583 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
9584}
9585
9586bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
9587 SE.reset(new ScalarEvolution(
9588 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
9589 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
9590 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
9591 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
9592 return false;
9593}
9594
9595void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
9596
9597void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
9598 SE->print(OS);
9599}
9600
9601void ScalarEvolutionWrapperPass::verifyAnalysis() const {
9602 if (!VerifySCEV)
9603 return;
9604
9605 SE->verify();
9606}
9607
9608void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9609 AU.setPreservesAll();
9610 AU.addRequiredTransitive<AssumptionCacheTracker>();
9611 AU.addRequiredTransitive<LoopInfoWrapperPass>();
9612 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
9613 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
9614}
Silviu Barangae3c05342015-11-02 14:41:02 +00009615
9616const SCEVPredicate *
9617ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
9618 const SCEVConstant *RHS) {
9619 FoldingSetNodeID ID;
9620 // Unique this node based on the arguments
9621 ID.AddInteger(SCEVPredicate::P_Equal);
9622 ID.AddPointer(LHS);
9623 ID.AddPointer(RHS);
9624 void *IP = nullptr;
9625 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
9626 return S;
9627 SCEVEqualPredicate *Eq = new (SCEVAllocator)
9628 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
9629 UniquePreds.InsertNode(Eq, IP);
9630 return Eq;
9631}
9632
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009633const SCEVPredicate *ScalarEvolution::getWrapPredicate(
9634 const SCEVAddRecExpr *AR,
9635 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
9636 FoldingSetNodeID ID;
9637 // Unique this node based on the arguments
9638 ID.AddInteger(SCEVPredicate::P_Wrap);
9639 ID.AddPointer(AR);
9640 ID.AddInteger(AddedFlags);
9641 void *IP = nullptr;
9642 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
9643 return S;
9644 auto *OF = new (SCEVAllocator)
9645 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
9646 UniquePreds.InsertNode(OF, IP);
9647 return OF;
9648}
9649
Benjamin Kramer83709b12015-11-16 09:01:28 +00009650namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009651
Silviu Barangae3c05342015-11-02 14:41:02 +00009652class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
9653public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00009654 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009655 // If Assume is true, rewrite is free to add further predicates to A
9656 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +00009657 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
9658 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009659 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +00009660 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +00009661 }
9662
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009663 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
9664 SCEVUnionPredicate &P, bool Assume)
9665 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +00009666
9667 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
9668 auto ExprPreds = P.getPredicatesForExpr(Expr);
9669 for (auto *Pred : ExprPreds)
9670 if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred))
9671 if (IPred->getLHS() == Expr)
9672 return IPred->getRHS();
9673
9674 return Expr;
9675 }
9676
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009677 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
9678 const SCEV *Operand = visit(Expr->getOperand());
9679 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
9680 if (AR && AR->getLoop() == L && AR->isAffine()) {
9681 // This couldn't be folded because the operand didn't have the nuw
9682 // flag. Add the nusw flag as an assumption that we could make.
9683 const SCEV *Step = AR->getStepRecurrence(SE);
9684 Type *Ty = Expr->getType();
9685 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
9686 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
9687 SE.getSignExtendExpr(Step, Ty), L,
9688 AR->getNoWrapFlags());
9689 }
9690 return SE.getZeroExtendExpr(Operand, Expr->getType());
9691 }
9692
9693 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
9694 const SCEV *Operand = visit(Expr->getOperand());
9695 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
9696 if (AR && AR->getLoop() == L && AR->isAffine()) {
9697 // This couldn't be folded because the operand didn't have the nsw
9698 // flag. Add the nssw flag as an assumption that we could make.
9699 const SCEV *Step = AR->getStepRecurrence(SE);
9700 Type *Ty = Expr->getType();
9701 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
9702 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
9703 SE.getSignExtendExpr(Step, Ty), L,
9704 AR->getNoWrapFlags());
9705 }
9706 return SE.getSignExtendExpr(Operand, Expr->getType());
9707 }
9708
Silviu Barangae3c05342015-11-02 14:41:02 +00009709private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009710 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
9711 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
9712 auto *A = SE.getWrapPredicate(AR, AddedFlags);
9713 if (!Assume) {
9714 // Check if we've already made this assumption.
9715 if (P.implies(A))
9716 return true;
9717 return false;
9718 }
9719 P.add(A);
9720 return true;
9721 }
9722
Silviu Barangae3c05342015-11-02 14:41:02 +00009723 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009724 const Loop *L;
9725 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +00009726};
Benjamin Kramer83709b12015-11-16 09:01:28 +00009727} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +00009728
Sanjoy Das807d33d2016-02-20 01:44:10 +00009729const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +00009730 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +00009731 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009732}
9733
Sanjoy Das807d33d2016-02-20 01:44:10 +00009734const SCEV *
9735ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
9736 SCEVUnionPredicate &Preds) {
9737 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, true);
Silviu Barangae3c05342015-11-02 14:41:02 +00009738}
9739
9740/// SCEV predicates
9741SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
9742 SCEVPredicateKind Kind)
9743 : FastID(ID), Kind(Kind) {}
9744
9745SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
9746 const SCEVUnknown *LHS,
9747 const SCEVConstant *RHS)
9748 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
9749
9750bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
9751 const auto *Op = dyn_cast<const SCEVEqualPredicate>(N);
9752
9753 if (!Op)
9754 return false;
9755
9756 return Op->LHS == LHS && Op->RHS == RHS;
9757}
9758
9759bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
9760
9761const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
9762
9763void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
9764 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
9765}
9766
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009767SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
9768 const SCEVAddRecExpr *AR,
9769 IncrementWrapFlags Flags)
9770 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
9771
9772const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
9773
9774bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
9775 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
9776
9777 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
9778}
9779
9780bool SCEVWrapPredicate::isAlwaysTrue() const {
9781 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
9782 IncrementWrapFlags IFlags = Flags;
9783
9784 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
9785 IFlags = clearFlags(IFlags, IncrementNSSW);
9786
9787 return IFlags == IncrementAnyWrap;
9788}
9789
9790void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
9791 OS.indent(Depth) << *getExpr() << " Added Flags: ";
9792 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
9793 OS << "<nusw>";
9794 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
9795 OS << "<nssw>";
9796 OS << "\n";
9797}
9798
9799SCEVWrapPredicate::IncrementWrapFlags
9800SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
9801 ScalarEvolution &SE) {
9802 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
9803 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
9804
9805 // We can safely transfer the NSW flag as NSSW.
9806 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
9807 ImpliedFlags = IncrementNSSW;
9808
9809 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
9810 // If the increment is positive, the SCEV NUW flag will also imply the
9811 // WrapPredicate NUSW flag.
9812 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
9813 if (Step->getValue()->getValue().isNonNegative())
9814 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
9815 }
9816
9817 return ImpliedFlags;
9818}
9819
Silviu Barangae3c05342015-11-02 14:41:02 +00009820/// Union predicates don't get cached so create a dummy set ID for it.
9821SCEVUnionPredicate::SCEVUnionPredicate()
9822 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
9823
9824bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +00009825 return all_of(Preds,
9826 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009827}
9828
9829ArrayRef<const SCEVPredicate *>
9830SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
9831 auto I = SCEVToPreds.find(Expr);
9832 if (I == SCEVToPreds.end())
9833 return ArrayRef<const SCEVPredicate *>();
9834 return I->second;
9835}
9836
9837bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
9838 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +00009839 return all_of(Set->Preds,
9840 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009841
9842 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
9843 if (ScevPredsIt == SCEVToPreds.end())
9844 return false;
9845 auto &SCEVPreds = ScevPredsIt->second;
9846
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00009847 return any_of(SCEVPreds,
9848 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009849}
9850
9851const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
9852
9853void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
9854 for (auto Pred : Preds)
9855 Pred->print(OS, Depth);
9856}
9857
9858void SCEVUnionPredicate::add(const SCEVPredicate *N) {
9859 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) {
9860 for (auto Pred : Set->Preds)
9861 add(Pred);
9862 return;
9863 }
9864
9865 if (implies(N))
9866 return;
9867
9868 const SCEV *Key = N->getExpr();
9869 assert(Key && "Only SCEVUnionPredicate doesn't have an "
9870 " associated expression!");
9871
9872 SCEVToPreds[Key].push_back(N);
9873 Preds.push_back(N);
9874}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00009875
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009876PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
9877 Loop &L)
9878 : SE(SE), L(L), Generation(0) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00009879
9880const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
9881 const SCEV *Expr = SE.getSCEV(V);
9882 RewriteEntry &Entry = RewriteMap[Expr];
9883
9884 // If we already have an entry and the version matches, return it.
9885 if (Entry.second && Generation == Entry.first)
9886 return Entry.second;
9887
9888 // We found an entry but it's stale. Rewrite the stale entry
9889 // acording to the current predicate.
9890 if (Entry.second)
9891 Expr = Entry.second;
9892
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009893 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00009894 Entry = {Generation, NewSCEV};
9895
9896 return NewSCEV;
9897}
9898
9899void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
9900 if (Preds.implies(&Pred))
9901 return;
9902 Preds.add(&Pred);
9903 updateGeneration();
9904}
9905
9906const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
9907 return Preds;
9908}
9909
9910void PredicatedScalarEvolution::updateGeneration() {
9911 // If the generation number wrapped recompute everything.
9912 if (++Generation == 0) {
9913 for (auto &II : RewriteMap) {
9914 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009915 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00009916 }
9917 }
9918}
Silviu Barangaea63a7f2016-02-08 17:02:45 +00009919
9920void PredicatedScalarEvolution::setNoOverflow(
9921 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
9922 const SCEV *Expr = getSCEV(V);
9923 const auto *AR = cast<SCEVAddRecExpr>(Expr);
9924
9925 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
9926
9927 // Clear the statically implied flags.
9928 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
9929 addPredicate(*SE.getWrapPredicate(AR, Flags));
9930
9931 auto II = FlagsMap.insert({V, Flags});
9932 if (!II.second)
9933 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
9934}
9935
9936bool PredicatedScalarEvolution::hasNoOverflow(
9937 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
9938 const SCEV *Expr = getSCEV(V);
9939 const auto *AR = cast<SCEVAddRecExpr>(Expr);
9940
9941 Flags = SCEVWrapPredicate::clearFlags(
9942 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
9943
9944 auto II = FlagsMap.find(V);
9945
9946 if (II != FlagsMap.end())
9947 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
9948
9949 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
9950}
9951
9952const SCEV *PredicatedScalarEvolution::getAsAddRec(Value *V) {
9953 const SCEV *Expr = this->getSCEV(V);
9954 const SCEV *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
9955 updateGeneration();
9956 RewriteMap[SE.getSCEV(V)] = {Generation, New};
9957 return New;
9958}
9959
9960PredicatedScalarEvolution::
9961PredicatedScalarEvolution(const PredicatedScalarEvolution &Init) :
9962 RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
9963 Generation(Init.Generation) {
9964 for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I)
9965 FlagsMap.insert(*I);
9966}