blob: 73a95ec405c7b6bd39f12f26102b9a5c7be74e23 [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"
Sanjoy Dasc46bceb2016-09-27 18:01:42 +000064#include "llvm/ADT/ScopeExit.h"
Sanjoy Das17078692016-10-31 03:32:43 +000065#include "llvm/ADT/Sequence.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000068#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000070#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000072#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000073#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000074#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000075#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000076#include "llvm/IR/Constants.h"
77#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000079#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000080#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000081#include "llvm/IR/GlobalAlias.h"
82#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000083#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Instructions.h"
85#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000086#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000087#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000088#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000089#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000090#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000091#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000092#include "llvm/Support/KnownBits.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000093#include "llvm/Support/MathExtras.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000094#include "llvm/Support/SaveAndRestore.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000095#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000096#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000097using namespace llvm;
98
Chandler Carruthf1221bd2014-04-22 02:48:03 +000099#define DEBUG_TYPE "scalar-evolution"
100
Chris Lattner57ef9422006-12-19 22:30:33 +0000101STATISTIC(NumArrayLenItCounts,
102 "Number of trip counts computed with array length");
103STATISTIC(NumTripCountsComputed,
104 "Number of loops with predictable loop counts");
105STATISTIC(NumTripCountsNotComputed,
106 "Number of loops without predictable loop counts");
107STATISTIC(NumBruteForceTripCountsComputed,
108 "Number of loops with trip counts computed by force");
109
Dan Gohmand78c4002008-05-13 00:00:25 +0000110static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000111MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000113 "symbolically execute a constant "
114 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000115 cl::init(100));
116
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000117// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Sanjoy Das0cdcdf02017-04-24 02:35:19 +0000118static cl::opt<bool>
119VerifySCEV("verify-scev",
120 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000121static cl::opt<bool>
122 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000123 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000124 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000125
Li Huangfcfe8cd2016-10-20 21:38:39 +0000126static cl::opt<unsigned> MulOpsInlineThreshold(
127 "scev-mulops-inline-threshold", cl::Hidden,
128 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
Max Kazantseveac01d42017-06-21 07:28:13 +0000129 cl::init(32));
Li Huangfcfe8cd2016-10-20 21:38:39 +0000130
Daniil Fukalovb09dac52017-01-26 13:33:17 +0000131static cl::opt<unsigned> AddOpsInlineThreshold(
132 "scev-addops-inline-threshold", cl::Hidden,
Max Kazantsev0bcf6ec2017-06-20 08:37:31 +0000133 cl::desc("Threshold for inlining addition operands into a SCEV"),
Daniil Fukalovb09dac52017-01-26 13:33:17 +0000134 cl::init(500));
135
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000136static cl::opt<unsigned> MaxSCEVCompareDepth(
137 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
139 cl::init(32));
140
Max Kazantsev2e44d292017-03-31 12:05:30 +0000141static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
144 cl::init(2));
145
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000146static cl::opt<unsigned> MaxValueCompareDepth(
147 "scalar-evolution-max-value-compare-depth", cl::Hidden,
148 cl::desc("Maximum depth of recursive value complexity comparisons"),
149 cl::init(2));
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000150
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000151static cl::opt<unsigned>
Max Kazantsevdc803662017-06-15 11:48:21 +0000152 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
153 cl::desc("Maximum depth of recursive arithmetics"),
154 cl::init(32));
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000155
Michael Liao468fb742017-01-13 18:28:30 +0000156static cl::opt<unsigned> MaxConstantEvolvingDepth(
157 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
159
Chris Lattnerd934c702004-04-02 20:23:17 +0000160//===----------------------------------------------------------------------===//
161// SCEV class definitions
162//===----------------------------------------------------------------------===//
163
164//===----------------------------------------------------------------------===//
165// Implementation of the SCEV class.
166//
Dan Gohman3423e722009-06-30 20:13:32 +0000167
Matthias Braun8c209aa2017-01-28 02:02:38 +0000168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
169LLVM_DUMP_METHOD void SCEV::dump() const {
Davide Italiano2071f4c2015-10-25 19:55:24 +0000170 print(dbgs());
171 dbgs() << '\n';
172}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000173#endif
Davide Italiano2071f4c2015-10-25 19:55:24 +0000174
Dan Gohman534749b2010-11-17 22:27:42 +0000175void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000176 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000177 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000178 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000179 return;
180 case scTruncate: {
181 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
182 const SCEV *Op = Trunc->getOperand();
183 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
184 << *Trunc->getType() << ")";
185 return;
186 }
187 case scZeroExtend: {
188 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
189 const SCEV *Op = ZExt->getOperand();
190 OS << "(zext " << *Op->getType() << " " << *Op << " to "
191 << *ZExt->getType() << ")";
192 return;
193 }
194 case scSignExtend: {
195 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
196 const SCEV *Op = SExt->getOperand();
197 OS << "(sext " << *Op->getType() << " " << *Op << " to "
198 << *SExt->getType() << ")";
199 return;
200 }
201 case scAddRecExpr: {
202 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
203 OS << "{" << *AR->getOperand(0);
204 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
205 OS << ",+," << *AR->getOperand(i);
206 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000207 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000208 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000209 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000210 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000211 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000212 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
213 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000214 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000215 OS << ">";
216 return;
217 }
218 case scAddExpr:
219 case scMulExpr:
220 case scUMaxExpr:
221 case scSMaxExpr: {
222 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000223 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000224 switch (NAry->getSCEVType()) {
225 case scAddExpr: OpStr = " + "; break;
226 case scMulExpr: OpStr = " * "; break;
227 case scUMaxExpr: OpStr = " umax "; break;
228 case scSMaxExpr: OpStr = " smax "; break;
229 }
230 OS << "(";
231 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
232 I != E; ++I) {
233 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000234 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000235 OS << OpStr;
236 }
237 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000238 switch (NAry->getSCEVType()) {
239 case scAddExpr:
240 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000241 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000242 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000243 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000244 OS << "<nsw>";
245 }
Dan Gohman534749b2010-11-17 22:27:42 +0000246 return;
247 }
248 case scUDivExpr: {
249 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
250 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
251 return;
252 }
253 case scUnknown: {
254 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000255 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000256 if (U->isSizeOf(AllocTy)) {
257 OS << "sizeof(" << *AllocTy << ")";
258 return;
259 }
260 if (U->isAlignOf(AllocTy)) {
261 OS << "alignof(" << *AllocTy << ")";
262 return;
263 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000264
Chris Lattner229907c2011-07-18 04:54:35 +0000265 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000266 Constant *FieldNo;
267 if (U->isOffsetOf(CTy, FieldNo)) {
268 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000269 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000270 OS << ")";
271 return;
272 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000273
Dan Gohman534749b2010-11-17 22:27:42 +0000274 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000275 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000276 return;
277 }
278 case scCouldNotCompute:
279 OS << "***COULDNOTCOMPUTE***";
280 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000281 }
282 llvm_unreachable("Unknown SCEV kind!");
283}
284
Chris Lattner229907c2011-07-18 04:54:35 +0000285Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000286 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000287 case scConstant:
288 return cast<SCEVConstant>(this)->getType();
289 case scTruncate:
290 case scZeroExtend:
291 case scSignExtend:
292 return cast<SCEVCastExpr>(this)->getType();
293 case scAddRecExpr:
294 case scMulExpr:
295 case scUMaxExpr:
296 case scSMaxExpr:
297 return cast<SCEVNAryExpr>(this)->getType();
298 case scAddExpr:
299 return cast<SCEVAddExpr>(this)->getType();
300 case scUDivExpr:
301 return cast<SCEVUDivExpr>(this)->getType();
302 case scUnknown:
303 return cast<SCEVUnknown>(this)->getType();
304 case scCouldNotCompute:
305 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000306 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000307 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000308}
309
Dan Gohmanbe928e32008-06-18 16:23:07 +0000310bool SCEV::isZero() const {
311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312 return SC->getValue()->isZero();
313 return false;
314}
315
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000316bool SCEV::isOne() const {
317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318 return SC->getValue()->isOne();
319 return false;
320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Dan Gohman18a96bb2009-06-24 00:30:26 +0000322bool SCEV::isAllOnesValue() const {
323 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
324 return SC->getValue()->isAllOnesValue();
325 return false;
326}
327
Andrew Trick881a7762012-01-07 00:27:31 +0000328bool SCEV::isNonConstantNegative() const {
329 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
330 if (!Mul) return false;
331
332 // If there is a constant factor, it will be first.
333 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
334 if (!SC) return false;
335
336 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000337 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000338}
339
Owen Anderson04052ec2009-06-22 21:57:23 +0000340SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000341 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000342
Chris Lattnerd934c702004-04-02 20:23:17 +0000343bool SCEVCouldNotCompute::classof(const SCEV *S) {
344 return S->getSCEVType() == scCouldNotCompute;
345}
346
Dan Gohmanaf752342009-07-07 17:06:11 +0000347const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000348 FoldingSetNodeID ID;
349 ID.AddInteger(scConstant);
350 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000351 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000352 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000353 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000354 UniqueSCEVs.InsertNode(S, IP);
355 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000356}
Chris Lattnerd934c702004-04-02 20:23:17 +0000357
Nick Lewycky31eaca52014-01-27 10:04:03 +0000358const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000359 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000360}
361
Dan Gohmanaf752342009-07-07 17:06:11 +0000362const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000363ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
364 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000365 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000366}
367
Dan Gohman24ceda82010-06-18 19:54:20 +0000368SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000369 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000370 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000371
Dan Gohman24ceda82010-06-18 19:54:20 +0000372SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000373 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000374 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000375 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000377 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000378}
Chris Lattnerd934c702004-04-02 20:23:17 +0000379
Dan Gohman24ceda82010-06-18 19:54:20 +0000380SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000381 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000382 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000383 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
384 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000385 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000386}
387
Dan Gohman24ceda82010-06-18 19:54:20 +0000388SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000389 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000390 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000391 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
392 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000393 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000394}
395
Dan Gohman7cac9572010-08-02 23:49:30 +0000396void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000397 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000398 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000399
400 // Remove this SCEVUnknown from the uniquing map.
401 SE->UniqueSCEVs.RemoveNode(this);
402
403 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000404 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000405}
406
407void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000408 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000409 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000410
411 // Remove this SCEVUnknown from the uniquing map.
412 SE->UniqueSCEVs.RemoveNode(this);
413
414 // Update this SCEVUnknown to point to the new value. This is needed
415 // because there may still be outstanding SCEVs which still point to
416 // this SCEVUnknown.
417 setValPtr(New);
418}
419
Chris Lattner229907c2011-07-18 04:54:35 +0000420bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000421 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000422 if (VCE->getOpcode() == Instruction::PtrToInt)
423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000424 if (CE->getOpcode() == Instruction::GetElementPtr &&
425 CE->getOperand(0)->isNullValue() &&
426 CE->getNumOperands() == 2)
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
428 if (CI->isOne()) {
429 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
430 ->getElementType();
431 return true;
432 }
Dan Gohmancf913832010-01-28 02:15:55 +0000433
434 return false;
435}
436
Chris Lattner229907c2011-07-18 04:54:35 +0000437bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000438 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000439 if (VCE->getOpcode() == Instruction::PtrToInt)
440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000441 if (CE->getOpcode() == Instruction::GetElementPtr &&
442 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000443 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000444 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000445 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000446 if (!STy->isPacked() &&
447 CE->getNumOperands() == 3 &&
448 CE->getOperand(1)->isNullValue()) {
449 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
450 if (CI->isOne() &&
451 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000452 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000453 AllocTy = STy->getElementType(1);
454 return true;
455 }
456 }
457 }
Dan Gohmancf913832010-01-28 02:15:55 +0000458
459 return false;
460}
461
Chris Lattner229907c2011-07-18 04:54:35 +0000462bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000463 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000464 if (VCE->getOpcode() == Instruction::PtrToInt)
465 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
466 if (CE->getOpcode() == Instruction::GetElementPtr &&
467 CE->getNumOperands() == 3 &&
468 CE->getOperand(0)->isNullValue() &&
469 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000470 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000471 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
472 // Ignore vector types here so that ScalarEvolutionExpander doesn't
473 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000474 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000475 CTy = Ty;
476 FieldNo = CE->getOperand(2);
477 return true;
478 }
479 }
480
481 return false;
482}
483
Chris Lattnereb3e8402004-06-20 06:23:15 +0000484//===----------------------------------------------------------------------===//
485// SCEV Utilities
486//===----------------------------------------------------------------------===//
487
Sanjoy Das17078692016-10-31 03:32:43 +0000488/// Compare the two values \p LV and \p RV in terms of their "complexity" where
489/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
490/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
491/// have been previously deemed to be "equally complex" by this routine. It is
492/// intended to avoid exponential time complexity in cases like:
493///
494/// %a = f(%x, %y)
495/// %b = f(%a, %a)
496/// %c = f(%b, %b)
497///
498/// %d = f(%x, %y)
499/// %e = f(%d, %d)
500/// %f = f(%e, %e)
501///
502/// CompareValueComplexity(%f, %c)
503///
504/// Since we do not continue running this routine on expression trees once we
505/// have seen unequal values, there is no need to track them in the cache.
506static int
507CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
508 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000509 unsigned Depth) {
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000510 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000511 return 0;
512
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000513 // Order pointer values after integer values. This helps SCEVExpander form
514 // GEPs.
515 bool LIsPointer = LV->getType()->isPointerTy(),
516 RIsPointer = RV->getType()->isPointerTy();
517 if (LIsPointer != RIsPointer)
518 return (int)LIsPointer - (int)RIsPointer;
519
520 // Compare getValueID values.
521 unsigned LID = LV->getValueID(), RID = RV->getValueID();
522 if (LID != RID)
523 return (int)LID - (int)RID;
524
525 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000526 if (const auto *LA = dyn_cast<Argument>(LV)) {
527 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000528 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
529 return (int)LArgNo - (int)RArgNo;
530 }
531
Sanjoy Das299e6722016-10-30 23:52:56 +0000532 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
533 const auto *RGV = cast<GlobalValue>(RV);
534
535 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
536 auto LT = GV->getLinkage();
537 return !(GlobalValue::isPrivateLinkage(LT) ||
538 GlobalValue::isInternalLinkage(LT));
539 };
540
541 // Use the names to distinguish the two values, but only if the
542 // names are semantically important.
543 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
544 return LGV->getName().compare(RGV->getName());
545 }
546
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000547 // For instructions, compare their loop depth, and their operand count. This
548 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000549 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
550 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000551
552 // Compare loop depths.
553 const BasicBlock *LParent = LInst->getParent(),
554 *RParent = RInst->getParent();
555 if (LParent != RParent) {
556 unsigned LDepth = LI->getLoopDepth(LParent),
557 RDepth = LI->getLoopDepth(RParent);
558 if (LDepth != RDepth)
559 return (int)LDepth - (int)RDepth;
560 }
561
562 // Compare the number of operands.
563 unsigned LNumOps = LInst->getNumOperands(),
564 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000565 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000566 return (int)LNumOps - (int)RNumOps;
567
Sanjoy Das17078692016-10-31 03:32:43 +0000568 for (unsigned Idx : seq(0u, LNumOps)) {
569 int Result =
570 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000571 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000572 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000573 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000574 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000575 }
576
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000577 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000578 return 0;
579}
580
Sanjoy Das237c8452016-09-27 18:01:48 +0000581// Return negative, zero, or positive, if LHS is less than, equal to, or greater
582// than RHS, respectively. A three-way result allows recursive comparisons to be
583// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000584static int CompareSCEVComplexity(
585 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
586 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000587 DominatorTree &DT, unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000588 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
589 if (LHS == RHS)
590 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000591
Sanjoy Das237c8452016-09-27 18:01:48 +0000592 // Primarily, sort the SCEVs by their getSCEVType().
593 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
594 if (LType != RType)
595 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000596
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000597 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000598 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000599 // Aside from the getSCEVType() ordering, the particular ordering
600 // isn't very important except that it's beneficial to be consistent,
601 // so that (a + b) and (b + a) don't end up as different expressions.
602 switch (static_cast<SCEVTypes>(LType)) {
603 case scUnknown: {
604 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
605 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000606
Sanjoy Das17078692016-10-31 03:32:43 +0000607 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000608 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
609 Depth + 1);
610 if (X == 0)
611 EqCacheSCEV.insert({LHS, RHS});
612 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000613 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000614
Sanjoy Das237c8452016-09-27 18:01:48 +0000615 case scConstant: {
616 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
617 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
618
619 // Compare constant values.
620 const APInt &LA = LC->getAPInt();
621 const APInt &RA = RC->getAPInt();
622 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
623 if (LBitWidth != RBitWidth)
624 return (int)LBitWidth - (int)RBitWidth;
625 return LA.ult(RA) ? -1 : 1;
626 }
627
628 case scAddRecExpr: {
629 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
630 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
631
Max Kazantsev4c7f2932017-05-17 04:09:14 +0000632 // There is always a dominance between two recs that are used by one SCEV,
633 // so we can safely sort recs by loop header dominance. We require such
634 // order in getAddExpr.
Sanjoy Das237c8452016-09-27 18:01:48 +0000635 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
636 if (LLoop != RLoop) {
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000637 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
638 assert(LHead != RHead && "Two loops share the same header?");
639 if (DT.dominates(LHead, RHead))
640 return 1;
Max Kazantsev4c7f2932017-05-17 04:09:14 +0000641 else
642 assert(DT.dominates(RHead, LHead) &&
643 "No dominance between recurrences used by one SCEV?");
644 return -1;
Sanjoy Das237c8452016-09-27 18:01:48 +0000645 }
646
647 // Addrec complexity grows with operand count.
648 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
649 if (LNumOps != RNumOps)
650 return (int)LNumOps - (int)RNumOps;
651
652 // Lexicographically compare.
653 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000654 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000655 RA->getOperand(i), DT, Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000656 if (X != 0)
657 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000658 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000659 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000660 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000661 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000662
663 case scAddExpr:
664 case scMulExpr:
665 case scSMaxExpr:
666 case scUMaxExpr: {
667 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
668 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
669
670 // Lexicographically compare n-ary expressions.
671 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
672 if (LNumOps != RNumOps)
673 return (int)LNumOps - (int)RNumOps;
674
675 for (unsigned i = 0; i != LNumOps; ++i) {
676 if (i >= RNumOps)
677 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000678 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000679 RC->getOperand(i), DT, Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000680 if (X != 0)
681 return X;
682 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000683 EqCacheSCEV.insert({LHS, RHS});
684 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000685 }
686
687 case scUDivExpr: {
688 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
689 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
690
691 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000692 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000693 DT, Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000694 if (X != 0)
695 return X;
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000696 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000697 Depth + 1);
698 if (X == 0)
699 EqCacheSCEV.insert({LHS, RHS});
700 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000701 }
702
703 case scTruncate:
704 case scZeroExtend:
705 case scSignExtend: {
706 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
707 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
708
709 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000710 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000711 RC->getOperand(), DT, Depth + 1);
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000712 if (X == 0)
713 EqCacheSCEV.insert({LHS, RHS});
714 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000715 }
716
717 case scCouldNotCompute:
718 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
719 }
720 llvm_unreachable("Unknown SCEV kind!");
721}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000722
Sanjoy Dasf8570812016-05-29 00:38:22 +0000723/// Given a list of SCEV objects, order them by their complexity, and group
724/// objects of the same complexity together by value. When this routine is
725/// finished, we know that any duplicates in the vector are consecutive and that
726/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000727///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000728/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000729/// results from this routine. In other words, we don't want the results of
730/// this to depend on where the addresses of various SCEV objects happened to
731/// land in memory.
732///
Dan Gohmanaf752342009-07-07 17:06:11 +0000733static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000734 LoopInfo *LI, DominatorTree &DT) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000735 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000736
737 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000738 if (Ops.size() == 2) {
739 // This is the common case, which also happens to be trivially simple.
740 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000741 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000742 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000743 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000744 return;
745 }
746
Dan Gohman24ceda82010-06-18 19:54:20 +0000747 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000748 std::stable_sort(Ops.begin(), Ops.end(),
Max Kazantsevb09b5db2017-05-16 07:27:06 +0000749 [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) {
750 return
751 CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000752 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000753
754 // Now that we are sorted by complexity, group elements of the same
755 // complexity. Note that this is, at worst, N^2, but the vector is likely to
756 // be extremely short in practice. Note that we take this approach because we
757 // do not want to depend on the addresses of the objects we are grouping.
758 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
759 const SCEV *S = Ops[i];
760 unsigned Complexity = S->getSCEVType();
761
762 // If there are any objects of the same complexity and same value as this
763 // one, group them.
764 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
765 if (Ops[j] == S) { // Found a duplicate.
766 // Move it to immediately after i'th element.
767 std::swap(Ops[i+1], Ops[j]);
768 ++i; // no need to rescan it.
769 if (i == e-2) return; // Done!
770 }
771 }
772 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000773}
774
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000775// Returns the size of the SCEV S.
776static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000777 struct FindSCEVSize {
778 int Size;
779 FindSCEVSize() : Size(0) {}
780
781 bool follow(const SCEV *S) {
782 ++Size;
783 // Keep looking at all operands of S.
784 return true;
785 }
786 bool isDone() const {
787 return false;
788 }
789 };
790
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000791 FindSCEVSize F;
792 SCEVTraversal<FindSCEVSize> ST(F);
793 ST.visitAll(S);
794 return F.Size;
795}
796
797namespace {
798
David Majnemer4e879362014-12-14 09:12:33 +0000799struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000800public:
801 // Computes the Quotient and Remainder of the division of Numerator by
802 // Denominator.
803 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
804 const SCEV *Denominator, const SCEV **Quotient,
805 const SCEV **Remainder) {
806 assert(Numerator && Denominator && "Uninitialized SCEV");
807
David Majnemer4e879362014-12-14 09:12:33 +0000808 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000809
810 // Check for the trivial case here to avoid having to check for it in the
811 // rest of the code.
812 if (Numerator == Denominator) {
813 *Quotient = D.One;
814 *Remainder = D.Zero;
815 return;
816 }
817
818 if (Numerator->isZero()) {
819 *Quotient = D.Zero;
820 *Remainder = D.Zero;
821 return;
822 }
823
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000824 // A simple case when N/1. The quotient is N.
825 if (Denominator->isOne()) {
826 *Quotient = Numerator;
827 *Remainder = D.Zero;
828 return;
829 }
830
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000831 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000832 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000833 const SCEV *Q, *R;
834 *Quotient = Numerator;
835 for (const SCEV *Op : T->operands()) {
836 divide(SE, *Quotient, Op, &Q, &R);
837 *Quotient = Q;
838
839 // Bail out when the Numerator is not divisible by one of the terms of
840 // the Denominator.
841 if (!R->isZero()) {
842 *Quotient = D.Zero;
843 *Remainder = Numerator;
844 return;
845 }
846 }
847 *Remainder = D.Zero;
848 return;
849 }
850
851 D.visit(Numerator);
852 *Quotient = D.Quotient;
853 *Remainder = D.Remainder;
854 }
855
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000856 // Except in the trivial case described above, we do not know how to divide
857 // Expr by Denominator for the following functions with empty implementation.
858 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
859 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
860 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
861 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
862 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
863 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
864 void visitUnknown(const SCEVUnknown *Numerator) {}
865 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
866
David Majnemer4e879362014-12-14 09:12:33 +0000867 void visitConstant(const SCEVConstant *Numerator) {
868 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000869 APInt NumeratorVal = Numerator->getAPInt();
870 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000871 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
872 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
873
874 if (NumeratorBW > DenominatorBW)
875 DenominatorVal = DenominatorVal.sext(NumeratorBW);
876 else if (NumeratorBW < DenominatorBW)
877 NumeratorVal = NumeratorVal.sext(DenominatorBW);
878
879 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
880 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
881 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
882 Quotient = SE.getConstant(QuotientVal);
883 Remainder = SE.getConstant(RemainderVal);
884 return;
885 }
886 }
887
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000888 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
889 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 if (!Numerator->isAffine())
891 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000892 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
893 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000894 // Bail out if the types do not match.
895 Type *Ty = Denominator->getType();
896 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000897 Ty != StepQ->getType() || Ty != StepR->getType())
898 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000899 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
900 Numerator->getNoWrapFlags());
901 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
902 Numerator->getNoWrapFlags());
903 }
904
905 void visitAddExpr(const SCEVAddExpr *Numerator) {
906 SmallVector<const SCEV *, 2> Qs, Rs;
907 Type *Ty = Denominator->getType();
908
909 for (const SCEV *Op : Numerator->operands()) {
910 const SCEV *Q, *R;
911 divide(SE, Op, Denominator, &Q, &R);
912
913 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000914 if (Ty != Q->getType() || Ty != R->getType())
915 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000916
917 Qs.push_back(Q);
918 Rs.push_back(R);
919 }
920
921 if (Qs.size() == 1) {
922 Quotient = Qs[0];
923 Remainder = Rs[0];
924 return;
925 }
926
927 Quotient = SE.getAddExpr(Qs);
928 Remainder = SE.getAddExpr(Rs);
929 }
930
931 void visitMulExpr(const SCEVMulExpr *Numerator) {
932 SmallVector<const SCEV *, 2> Qs;
933 Type *Ty = Denominator->getType();
934
935 bool FoundDenominatorTerm = false;
936 for (const SCEV *Op : Numerator->operands()) {
937 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000938 if (Ty != Op->getType())
939 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000940
941 if (FoundDenominatorTerm) {
942 Qs.push_back(Op);
943 continue;
944 }
945
946 // Check whether Denominator divides one of the product operands.
947 const SCEV *Q, *R;
948 divide(SE, Op, Denominator, &Q, &R);
949 if (!R->isZero()) {
950 Qs.push_back(Op);
951 continue;
952 }
953
954 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000955 if (Ty != Q->getType())
956 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000957
958 FoundDenominatorTerm = true;
959 Qs.push_back(Q);
960 }
961
962 if (FoundDenominatorTerm) {
963 Remainder = Zero;
964 if (Qs.size() == 1)
965 Quotient = Qs[0];
966 else
967 Quotient = SE.getMulExpr(Qs);
968 return;
969 }
970
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000971 if (!isa<SCEVUnknown>(Denominator))
972 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000973
974 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
975 ValueToValueMap RewriteMap;
976 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
977 cast<SCEVConstant>(Zero)->getValue();
978 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
979
980 if (Remainder->isZero()) {
981 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
982 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
983 cast<SCEVConstant>(One)->getValue();
984 Quotient =
985 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
986 return;
987 }
988
989 // Quotient is (Numerator - Remainder) divided by Denominator.
990 const SCEV *Q, *R;
991 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000992 // This SCEV does not seem to simplify: fail the division here.
993 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
994 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000995 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000996 if (R != Zero)
997 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000998 Quotient = Q;
999 }
1000
1001private:
David Majnemer5d2670c2014-11-17 11:27:45 +00001002 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1003 const SCEV *Denominator)
1004 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001005 Zero = SE.getZero(Denominator->getType());
1006 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +00001007
Matthew Simpsonddb4d972015-09-10 18:12:47 +00001008 // We generally do not know how to divide Expr by Denominator. We
1009 // initialize the division to a "cannot divide" state to simplify the rest
1010 // of the code.
1011 cannotDivide(Numerator);
1012 }
1013
1014 // Convenience function for giving up on the division. We set the quotient to
1015 // be equal to zero and the remainder to be equal to the numerator.
1016 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +00001017 Quotient = Zero;
1018 Remainder = Numerator;
1019 }
1020
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001021 ScalarEvolution &SE;
1022 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +00001023};
1024
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001025}
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001026
Chris Lattnerd934c702004-04-02 20:23:17 +00001027//===----------------------------------------------------------------------===//
1028// Simple SCEV method implementations
1029//===----------------------------------------------------------------------===//
1030
Sanjoy Dasf8570812016-05-29 00:38:22 +00001031/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +00001032static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +00001033 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001034 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001035 // Handle the simplest case efficiently.
1036 if (K == 1)
1037 return SE.getTruncateOrZeroExtend(It, ResultTy);
1038
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001039 // We are using the following formula for BC(It, K):
1040 //
1041 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1042 //
Eli Friedman61f67622008-08-04 23:49:06 +00001043 // Suppose, W is the bitwidth of the return value. We must be prepared for
1044 // overflow. Hence, we must assure that the result of our computation is
1045 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1046 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001047 //
Eli Friedman61f67622008-08-04 23:49:06 +00001048 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001049 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001050 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1051 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001052 //
Eli Friedman61f67622008-08-04 23:49:06 +00001053 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001054 //
Eli Friedman61f67622008-08-04 23:49:06 +00001055 // This formula is trivially equivalent to the previous formula. However,
1056 // this formula can be implemented much more efficiently. The trick is that
1057 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1058 // arithmetic. To do exact division in modular arithmetic, all we have
1059 // to do is multiply by the inverse. Therefore, this step can be done at
1060 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001061 //
Eli Friedman61f67622008-08-04 23:49:06 +00001062 // The next issue is how to safely do the division by 2^T. The way this
1063 // is done is by doing the multiplication step at a width of at least W + T
1064 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1065 // when we perform the division by 2^T (which is equivalent to a right shift
1066 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1067 // truncated out after the division by 2^T.
1068 //
1069 // In comparison to just directly using the first formula, this technique
1070 // is much more efficient; using the first formula requires W * K bits,
1071 // but this formula less than W + K bits. Also, the first formula requires
1072 // a division step, whereas this formula only requires multiplies and shifts.
1073 //
1074 // It doesn't matter whether the subtraction step is done in the calculation
1075 // width or the input iteration count's width; if the subtraction overflows,
1076 // the result must be zero anyway. We prefer here to do it in the width of
1077 // the induction variable because it helps a lot for certain cases; CodeGen
1078 // isn't smart enough to ignore the overflow, which leads to much less
1079 // efficient code if the width of the subtraction is wider than the native
1080 // register width.
1081 //
1082 // (It's possible to not widen at all by pulling out factors of 2 before
1083 // the multiplication; for example, K=2 can be calculated as
1084 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1085 // extra arithmetic, so it's not an obvious win, and it gets
1086 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001087
Eli Friedman61f67622008-08-04 23:49:06 +00001088 // Protection from insane SCEVs; this bound is conservative,
1089 // but it probably doesn't matter.
1090 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001091 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001092
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001093 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001094
Eli Friedman61f67622008-08-04 23:49:06 +00001095 // Calculate K! / 2^T and T; we divide out the factors of two before
1096 // multiplying for calculating K! / 2^T to avoid overflow.
1097 // Other overflow doesn't matter because we only care about the bottom
1098 // W bits of the result.
1099 APInt OddFactorial(W, 1);
1100 unsigned T = 1;
1101 for (unsigned i = 3; i <= K; ++i) {
1102 APInt Mult(W, i);
1103 unsigned TwoFactors = Mult.countTrailingZeros();
1104 T += TwoFactors;
Craig Topperfc947bc2017-04-18 17:14:21 +00001105 Mult.lshrInPlace(TwoFactors);
Eli Friedman61f67622008-08-04 23:49:06 +00001106 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001107 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001108
Eli Friedman61f67622008-08-04 23:49:06 +00001109 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001110 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001111
Dan Gohman8b0a4192010-03-01 17:49:51 +00001112 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001113 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001114
1115 // Calculate the multiplicative inverse of K! / 2^T;
1116 // this multiplication factor will perform the exact division by
1117 // K! / 2^T.
1118 APInt Mod = APInt::getSignedMinValue(W+1);
1119 APInt MultiplyFactor = OddFactorial.zext(W+1);
1120 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1121 MultiplyFactor = MultiplyFactor.trunc(W);
1122
1123 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001124 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001125 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001126 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001127 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001128 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001129 Dividend = SE.getMulExpr(Dividend,
1130 SE.getTruncateOrZeroExtend(S, CalculationTy));
1131 }
1132
1133 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001134 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001135
1136 // Truncate the result, and divide by K! / 2^T.
1137
1138 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1139 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001140}
1141
Sanjoy Dasf8570812016-05-29 00:38:22 +00001142/// Return the value of this chain of recurrences at the specified iteration
1143/// number. We can evaluate this recurrence by multiplying each element in the
1144/// chain by the binomial coefficient corresponding to it. In other words, we
1145/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001146///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001147/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001148///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001149/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001150///
Dan Gohmanaf752342009-07-07 17:06:11 +00001151const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001152 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001153 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001154 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001155 // The computation is correct in the face of overflow provided that the
1156 // multiplication is performed _after_ the evaluation of the binomial
1157 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001158 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001159 if (isa<SCEVCouldNotCompute>(Coeff))
1160 return Coeff;
1161
1162 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001163 }
1164 return Result;
1165}
1166
Chris Lattnerd934c702004-04-02 20:23:17 +00001167//===----------------------------------------------------------------------===//
1168// SCEV Expression folder implementations
1169//===----------------------------------------------------------------------===//
1170
Dan Gohmanaf752342009-07-07 17:06:11 +00001171const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001172 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001173 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001174 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001175 assert(isSCEVable(Ty) &&
1176 "This is not a conversion to a SCEVable type!");
1177 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001178
Dan Gohman3a302cb2009-07-13 20:50:19 +00001179 FoldingSetNodeID ID;
1180 ID.AddInteger(scTruncate);
1181 ID.AddPointer(Op);
1182 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001183 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001184 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1185
Dan Gohman3423e722009-06-30 20:13:32 +00001186 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001187 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001188 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001189 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001190
Dan Gohman79af8542009-04-22 16:20:48 +00001191 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001192 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001193 return getTruncateExpr(ST->getOperand(), Ty);
1194
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001195 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001196 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001197 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1198
1199 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001200 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001201 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1202
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001203 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001204 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001205 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1206 SmallVector<const SCEV *, 4> Operands;
1207 bool hasTrunc = false;
1208 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1209 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001210 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1211 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001212 Operands.push_back(S);
1213 }
1214 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001215 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001216 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001217 }
1218
Nick Lewycky5c901f32011-01-19 18:56:00 +00001219 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001220 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001221 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1222 SmallVector<const SCEV *, 4> Operands;
1223 bool hasTrunc = false;
1224 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1225 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001226 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1227 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001228 Operands.push_back(S);
1229 }
1230 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001231 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001232 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001233 }
1234
Dan Gohman5a728c92009-06-18 16:24:47 +00001235 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001236 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001237 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001238 for (const SCEV *Op : AddRec->operands())
1239 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001240 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001241 }
1242
Dan Gohman89dd42a2010-06-25 18:47:08 +00001243 // The cast wasn't folded; create an explicit cast node. We can reuse
1244 // the existing insert position since if we get here, we won't have
1245 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001246 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1247 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001248 UniqueSCEVs.InsertNode(S, IP);
1249 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001250}
1251
Sanjoy Das4153f472015-02-18 01:47:07 +00001252// Get the limit of a recurrence such that incrementing by Step cannot cause
1253// signed overflow as long as the value of the recurrence within the
1254// loop does not exceed this limit before incrementing.
1255static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1259 if (SE->isKnownPositive(Step)) {
1260 *Pred = ICmpInst::ICMP_SLT;
1261 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
Craig Topper01020392017-06-24 23:34:50 +00001262 SE->getSignedRangeMax(Step));
Sanjoy Das4153f472015-02-18 01:47:07 +00001263 }
1264 if (SE->isKnownNegative(Step)) {
1265 *Pred = ICmpInst::ICMP_SGT;
1266 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
Craig Topper01020392017-06-24 23:34:50 +00001267 SE->getSignedRangeMin(Step));
Sanjoy Das4153f472015-02-18 01:47:07 +00001268 }
1269 return nullptr;
1270}
1271
1272// Get the limit of a recurrence such that incrementing by Step cannot cause
1273// unsigned overflow as long as the value of the recurrence within the loop does
1274// not exceed this limit before incrementing.
1275static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1276 ICmpInst::Predicate *Pred,
1277 ScalarEvolution *SE) {
1278 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1279 *Pred = ICmpInst::ICMP_ULT;
1280
1281 return SE->getConstant(APInt::getMinValue(BitWidth) -
Craig Topper01020392017-06-24 23:34:50 +00001282 SE->getUnsignedRangeMax(Step));
Sanjoy Das4153f472015-02-18 01:47:07 +00001283}
1284
1285namespace {
1286
1287struct ExtendOpTraitsBase {
Wei Mi8c405332017-04-17 20:40:05 +00001288 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1289 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001290};
1291
1292// Used to make code generic over signed and unsigned overflow.
1293template <typename ExtendOp> struct ExtendOpTraits {
1294 // Members present:
1295 //
1296 // static const SCEV::NoWrapFlags WrapType;
1297 //
1298 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1299 //
1300 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1301 // ICmpInst::Predicate *Pred,
1302 // ScalarEvolution *SE);
1303};
1304
1305template <>
1306struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1307 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1308
1309 static const GetExtendExprTy GetExtendExpr;
1310
1311 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1312 ICmpInst::Predicate *Pred,
1313 ScalarEvolution *SE) {
1314 return getSignedOverflowLimitForStep(Step, Pred, SE);
1315 }
1316};
1317
Wei Mi8c405332017-04-17 20:40:05 +00001318const ExtendOpTraitsBase::GetExtendExprTy
1319 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1320 &ScalarEvolution::getSignExtendExprCached;
Sanjoy Das4153f472015-02-18 01:47:07 +00001321
1322template <>
1323struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1324 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1325
1326 static const GetExtendExprTy GetExtendExpr;
1327
1328 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1329 ICmpInst::Predicate *Pred,
1330 ScalarEvolution *SE) {
1331 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1332 }
1333};
1334
Wei Mi8c405332017-04-17 20:40:05 +00001335const ExtendOpTraitsBase::GetExtendExprTy
1336 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1337 &ScalarEvolution::getZeroExtendExprCached;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001338}
Sanjoy Das4153f472015-02-18 01:47:07 +00001339
1340// The recurrence AR has been shown to have no signed/unsigned wrap or something
1341// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1342// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1343// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1344// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1345// expression "Step + sext/zext(PreIncAR)" is congruent with
1346// "sext/zext(PostIncAR)"
1347template <typename ExtendOpTy>
1348static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
Wei Mi8c405332017-04-17 20:40:05 +00001349 ScalarEvolution *SE,
1350 ScalarEvolution::ExtendCacheTy &Cache) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001351 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1352 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1353
1354 const Loop *L = AR->getLoop();
1355 const SCEV *Start = AR->getStart();
1356 const SCEV *Step = AR->getStepRecurrence(*SE);
1357
1358 // Check for a simple looking step prior to loop entry.
1359 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1360 if (!SA)
1361 return nullptr;
1362
1363 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1364 // subtraction is expensive. For this purpose, perform a quick and dirty
1365 // difference, by checking for Step in the operand list.
1366 SmallVector<const SCEV *, 4> DiffOps;
1367 for (const SCEV *Op : SA->operands())
1368 if (Op != Step)
1369 DiffOps.push_back(Op);
1370
1371 if (DiffOps.size() == SA->getNumOperands())
1372 return nullptr;
1373
1374 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1375 // `Step`:
1376
1377 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001378 auto PreStartFlags =
1379 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1380 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001381 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1382 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1383
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001384 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1385 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001386 //
1387
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001388 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1389 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1390 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001391 return PreStart;
1392
1393 // 2. Direct overflow check on the step operation's expression.
1394 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1395 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1396 const SCEV *OperandExtendedStart =
Wei Mi8c405332017-04-17 20:40:05 +00001397 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1398 (SE->*GetExtendExpr)(Step, WideTy, Cache));
1399 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001400 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1401 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1402 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1403 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1404 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1405 }
1406 return PreStart;
1407 }
1408
1409 // 3. Loop precondition.
1410 ICmpInst::Predicate Pred;
1411 const SCEV *OverflowLimit =
1412 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1413
1414 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001415 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001416 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001417
Sanjoy Das4153f472015-02-18 01:47:07 +00001418 return nullptr;
1419}
1420
1421// Get the normalized zero or sign extended expression for this AddRec's Start.
1422template <typename ExtendOpTy>
1423static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
Wei Mi8c405332017-04-17 20:40:05 +00001424 ScalarEvolution *SE,
1425 ScalarEvolution::ExtendCacheTy &Cache) {
Sanjoy Das4153f472015-02-18 01:47:07 +00001426 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1427
Wei Mi8c405332017-04-17 20:40:05 +00001428 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001429 if (!PreStart)
Wei Mi8c405332017-04-17 20:40:05 +00001430 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
Sanjoy Das4153f472015-02-18 01:47:07 +00001431
Wei Mi8c405332017-04-17 20:40:05 +00001432 return SE->getAddExpr(
1433 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1434 (SE->*GetExtendExpr)(PreStart, Ty, Cache));
Sanjoy Das4153f472015-02-18 01:47:07 +00001435}
1436
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001437// Try to prove away overflow by looking at "nearby" add recurrences. A
1438// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1439// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1440//
1441// Formally:
1442//
1443// {S,+,X} == {S-T,+,X} + T
1444// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1445//
1446// If ({S-T,+,X} + T) does not overflow ... (1)
1447//
1448// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1449//
1450// If {S-T,+,X} does not overflow ... (2)
1451//
1452// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1453// == {Ext(S-T)+Ext(T),+,Ext(X)}
1454//
1455// If (S-T)+T does not overflow ... (3)
1456//
1457// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1458// == {Ext(S),+,Ext(X)} == LHS
1459//
1460// Thus, if (1), (2) and (3) are true for some T, then
1461// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1462//
1463// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1464// does not overflow" restricted to the 0th iteration. Therefore we only need
1465// to check for (1) and (2).
1466//
1467// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1468// is `Delta` (defined below).
1469//
1470template <typename ExtendOpTy>
1471bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1472 const SCEV *Step,
1473 const Loop *L) {
1474 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1475
1476 // We restrict `Start` to a constant to prevent SCEV from spending too much
1477 // time here. It is correct (but more expensive) to continue with a
1478 // non-constant `Start` and do a general SCEV subtraction to compute
1479 // `PreStart` below.
1480 //
1481 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1482 if (!StartC)
1483 return false;
1484
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001485 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001486
1487 for (unsigned Delta : {-2, -1, 1, 2}) {
1488 const SCEV *PreStart = getConstant(StartAI - Delta);
1489
Sanjoy Das42801102015-10-23 06:57:21 +00001490 FoldingSetNodeID ID;
1491 ID.AddInteger(scAddRecExpr);
1492 ID.AddPointer(PreStart);
1493 ID.AddPointer(Step);
1494 ID.AddPointer(L);
1495 void *IP = nullptr;
1496 const auto *PreAR =
1497 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1498
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001499 // Give up if we don't already have the add recurrence we need because
1500 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001501 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1502 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1503 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1504 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1505 DeltaS, &Pred, this);
1506 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1507 return true;
1508 }
1509 }
1510
1511 return false;
1512}
1513
Wei Mi8c405332017-04-17 20:40:05 +00001514const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1515 // Use the local cache to prevent exponential behavior of
1516 // getZeroExtendExprImpl.
1517 ExtendCacheTy Cache;
1518 return getZeroExtendExprCached(Op, Ty, Cache);
1519}
1520
1521/// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1522/// related entry in the \p Cache, call getZeroExtendExprImpl and save
1523/// the result in the \p Cache.
1524const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1525 ExtendCacheTy &Cache) {
1526 auto It = Cache.find({Op, Ty});
1527 if (It != Cache.end())
1528 return It->second;
1529 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1530 auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1531 assert(InsertResult.second && "Expect the key was not in the cache");
Wei Mi66c4dd22017-04-17 21:00:45 +00001532 (void)InsertResult;
Wei Mi8c405332017-04-17 20:40:05 +00001533 return ZExt;
1534}
1535
1536/// The real implementation of getZeroExtendExpr.
1537const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1538 ExtendCacheTy &Cache) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001539 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001540 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001541 assert(isSCEVable(Ty) &&
1542 "This is not a conversion to a SCEVable type!");
1543 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001544
Dan Gohman3423e722009-06-30 20:13:32 +00001545 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001546 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1547 return getConstant(
Wei Mi8c405332017-04-17 20:40:05 +00001548 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001549
Dan Gohman79af8542009-04-22 16:20:48 +00001550 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001551 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Wei Mi8c405332017-04-17 20:40:05 +00001552 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
Dan Gohman79af8542009-04-22 16:20:48 +00001553
Dan Gohman74a0ba12009-07-13 20:55:53 +00001554 // Before doing any expensive analysis, check to see if we've already
1555 // computed a SCEV for this Op and Ty.
1556 FoldingSetNodeID ID;
1557 ID.AddInteger(scZeroExtend);
1558 ID.AddPointer(Op);
1559 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001560 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001561 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1562
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001563 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1564 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1565 // It's possible the bits taken off by the truncate were all zero bits. If
1566 // so, we should be able to simplify this further.
1567 const SCEV *X = ST->getOperand();
1568 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001569 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1570 unsigned NewBits = getTypeSizeInBits(Ty);
1571 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001572 CR.zextOrTrunc(NewBits)))
1573 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001574 }
1575
Dan Gohman76466372009-04-27 20:16:15 +00001576 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001577 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001578 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001579 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001580 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001581 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001582 const SCEV *Start = AR->getStart();
1583 const SCEV *Step = AR->getStepRecurrence(*this);
1584 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1585 const Loop *L = AR->getLoop();
1586
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001587 if (!AR->hasNoUnsignedWrap()) {
1588 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1590 }
1591
Dan Gohman62ef6a72009-07-25 01:22:26 +00001592 // If we have special knowledge that this addrec won't overflow,
1593 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001594 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001595 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001596 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1597 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001598
Dan Gohman76466372009-04-27 20:16:15 +00001599 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1600 // Note that this serves two purposes: It filters out loops that are
1601 // simply not analyzable, and it covers the case where this code is
1602 // being called from within backedge-taken count analysis, such that
1603 // attempting to ask for the backedge-taken count would likely result
1604 // in infinite recursion. In the later case, the analysis code will
1605 // cope with a conservative value, and it will take care to purge
1606 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001607 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001608 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001609 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001610 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001611
1612 // Check whether the backedge-taken count can be losslessly casted to
1613 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001614 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001615 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001616 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001617 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1618 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001619 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001620 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001621 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Wei Mi8c405332017-04-17 20:40:05 +00001622 const SCEV *ZAdd =
1623 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1624 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001625 const SCEV *WideMaxBECount =
Wei Mi8c405332017-04-17 20:40:05 +00001626 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1627 const SCEV *OperandExtendedAdd = getAddExpr(
1628 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1629 Step, WideTy, Cache)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001630 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001631 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1632 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001633 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001634 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001635 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1636 getZeroExtendExprCached(Step, Ty, Cache), L,
1637 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001638 }
Dan Gohman76466372009-04-27 20:16:15 +00001639 // Similar to above, only this time treat the step value as signed.
1640 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001641 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001642 getAddExpr(WideStart,
1643 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001644 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001645 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001646 // Cache knowledge of AR NW, which is propagated to this AddRec.
1647 // Negative step causes unsigned wrap, but it still can't self-wrap.
1648 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001649 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001650 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001651 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001652 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001653 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001654 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001655 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001656
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001657 // Normally, in the cases we can prove no-overflow via a
1658 // backedge guarding condition, we can also compute a backedge
1659 // taken count for the loop. The exceptions are assumptions and
1660 // guards present in the loop -- SCEV is not great at exploiting
1661 // these to compute max backedge taken counts, but can still use
1662 // these to prove lack of overflow. Use this fact to avoid
1663 // doing extra work that may not pay off.
1664 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001665 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001666 // If the backedge is guarded by a comparison with the pre-inc
1667 // value the addrec is safe. Also, if the entry is guarded by
1668 // a comparison with the start value and the backedge is
1669 // guarded by a comparison with the post-inc value, the addrec
1670 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001671 if (isKnownPositive(Step)) {
1672 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
Craig Topper01020392017-06-24 23:34:50 +00001673 getUnsignedRangeMax(Step));
Dan Gohmane65c9172009-07-13 21:35:55 +00001674 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001675 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001676 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001677 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001678 // Cache knowledge of AR NUW, which is propagated to this
1679 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001680 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001681 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001682 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001683 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1684 getZeroExtendExprCached(Step, Ty, Cache), L,
1685 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001686 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001687 } else if (isKnownNegative(Step)) {
1688 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
Craig Topper01020392017-06-24 23:34:50 +00001689 getSignedRangeMin(Step));
Dan Gohman5f18c542010-05-04 01:11:15 +00001690 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1691 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001692 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001693 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001694 // Cache knowledge of AR NW, which is propagated to this
1695 // AddRec. Negative step causes unsigned wrap, but it
1696 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001697 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1698 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001699 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001701 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001702 }
Dan Gohman76466372009-04-27 20:16:15 +00001703 }
1704 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001705
1706 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1707 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1708 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1710 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001711 }
Dan Gohman76466372009-04-27 20:16:15 +00001712 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001713
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001714 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1715 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001716 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001717 // If the addition does not unsign overflow then we can, by definition,
1718 // commute the zero extension with the addition operation.
1719 SmallVector<const SCEV *, 4> Ops;
1720 for (const auto *Op : SA->operands())
Wei Mi8c405332017-04-17 20:40:05 +00001721 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001722 return getAddExpr(Ops, SCEV::FlagNUW);
1723 }
1724 }
1725
Dan Gohman74a0ba12009-07-13 20:55:53 +00001726 // The cast wasn't folded; create an explicit cast node.
1727 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001728 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001729 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1730 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001731 UniqueSCEVs.InsertNode(S, IP);
1732 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001733}
1734
Wei Mi8c405332017-04-17 20:40:05 +00001735const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1736 // Use the local cache to prevent exponential behavior of
1737 // getSignExtendExprImpl.
1738 ExtendCacheTy Cache;
1739 return getSignExtendExprCached(Op, Ty, Cache);
1740}
1741
1742/// Query \p Cache before calling getSignExtendExprImpl. If there is no
1743/// related entry in the \p Cache, call getSignExtendExprImpl and save
1744/// the result in the \p Cache.
1745const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1746 ExtendCacheTy &Cache) {
1747 auto It = Cache.find({Op, Ty});
1748 if (It != Cache.end())
1749 return It->second;
1750 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1751 auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1752 assert(InsertResult.second && "Expect the key was not in the cache");
Benjamin Kramer61d85bc2017-04-17 21:07:26 +00001753 (void)InsertResult;
Wei Mi8c405332017-04-17 20:40:05 +00001754 return SExt;
1755}
1756
1757/// The real implementation of getSignExtendExpr.
1758const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1759 ExtendCacheTy &Cache) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001760 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001761 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001762 assert(isSCEVable(Ty) &&
1763 "This is not a conversion to a SCEVable type!");
1764 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001765
Dan Gohman3423e722009-06-30 20:13:32 +00001766 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001767 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1768 return getConstant(
Wei Mi8c405332017-04-17 20:40:05 +00001769 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001770
Dan Gohman79af8542009-04-22 16:20:48 +00001771 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001772 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Wei Mi8c405332017-04-17 20:40:05 +00001773 return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
Dan Gohman79af8542009-04-22 16:20:48 +00001774
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001775 // sext(zext(x)) --> zext(x)
1776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1777 return getZeroExtendExpr(SZ->getOperand(), Ty);
1778
Dan Gohman74a0ba12009-07-13 20:55:53 +00001779 // Before doing any expensive analysis, check to see if we've already
1780 // computed a SCEV for this Op and Ty.
1781 FoldingSetNodeID ID;
1782 ID.AddInteger(scSignExtend);
1783 ID.AddPointer(Op);
1784 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001785 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1787
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001788 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1789 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1790 // It's possible the bits taken off by the truncate were all sign bits. If
1791 // so, we should be able to simplify this further.
1792 const SCEV *X = ST->getOperand();
1793 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001794 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1795 unsigned NewBits = getTypeSizeInBits(Ty);
1796 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001797 CR.sextOrTrunc(NewBits)))
1798 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001799 }
1800
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001801 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001802 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001803 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001804 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1805 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001806 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001807 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001808 const APInt &C1 = SC1->getAPInt();
1809 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001810 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001811 C2.ugt(C1) && C2.isPowerOf2())
Wei Mi8c405332017-04-17 20:40:05 +00001812 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1813 getSignExtendExprCached(SMul, Ty, Cache));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001814 }
1815 }
1816 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001817
1818 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001819 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001820 // If the addition does not sign overflow then we can, by definition,
1821 // commute the sign extension with the addition operation.
1822 SmallVector<const SCEV *, 4> Ops;
1823 for (const auto *Op : SA->operands())
Wei Mi8c405332017-04-17 20:40:05 +00001824 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
Sanjoy Dasa060e602015-10-22 19:57:25 +00001825 return getAddExpr(Ops, SCEV::FlagNSW);
1826 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001827 }
Dan Gohman76466372009-04-27 20:16:15 +00001828 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001829 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001830 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001831 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001832 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001833 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001834 const SCEV *Start = AR->getStart();
1835 const SCEV *Step = AR->getStepRecurrence(*this);
1836 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1837 const Loop *L = AR->getLoop();
1838
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001839 if (!AR->hasNoSignedWrap()) {
1840 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1842 }
1843
Dan Gohman62ef6a72009-07-25 01:22:26 +00001844 // If we have special knowledge that this addrec won't overflow,
1845 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001846 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001847 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001848 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1849 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001850
Dan Gohman76466372009-04-27 20:16:15 +00001851 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1852 // Note that this serves two purposes: It filters out loops that are
1853 // simply not analyzable, and it covers the case where this code is
1854 // being called from within backedge-taken count analysis, such that
1855 // attempting to ask for the backedge-taken count would likely result
1856 // in infinite recursion. In the later case, the analysis code will
1857 // cope with a conservative value, and it will take care to purge
1858 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001859 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001860 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001861 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001862 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001863
1864 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001865 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001866 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001867 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001868 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001869 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1870 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001871 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001872 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001873 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Wei Mi8c405332017-04-17 20:40:05 +00001874 const SCEV *SAdd =
1875 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1876 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001877 const SCEV *WideMaxBECount =
Wei Mi8c405332017-04-17 20:40:05 +00001878 getZeroExtendExpr(CastedMaxBECount, WideTy);
1879 const SCEV *OperandExtendedAdd = getAddExpr(
1880 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1881 Step, WideTy, Cache)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001882 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001883 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1884 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001885 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001886 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001887 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1888 getSignExtendExprCached(Step, Ty, Cache), L,
1889 AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001890 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001891 // Similar to above, only this time treat the step value as unsigned.
1892 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001893 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001894 getAddExpr(WideStart,
1895 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001896 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001897 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001898 // If AR wraps around then
1899 //
1900 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1901 // => SAdd != OperandExtendedAdd
1902 //
1903 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1904 // (SAdd == OperandExtendedAdd => AR is NW)
1905
1906 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1907
Dan Gohman8c129d72009-07-16 17:34:36 +00001908 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001909 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001910 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
Sanjoy Das4153f472015-02-18 01:47:07 +00001911 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001912 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001913 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001914 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001915
Sanjoy Das787c2462016-05-11 17:41:26 +00001916 // Normally, in the cases we can prove no-overflow via a
1917 // backedge guarding condition, we can also compute a backedge
1918 // taken count for the loop. The exceptions are assumptions and
1919 // guards present in the loop -- SCEV is not great at exploiting
1920 // these to compute max backedge taken counts, but can still use
1921 // these to prove lack of overflow. Use this fact to avoid
1922 // doing extra work that may not pay off.
1923
1924 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001925 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001926 // If the backedge is guarded by a comparison with the pre-inc
1927 // value the addrec is safe. Also, if the entry is guarded by
1928 // a comparison with the start value and the backedge is
1929 // guarded by a comparison with the post-inc value, the addrec
1930 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001931 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001932 const SCEV *OverflowLimit =
1933 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001934 if (OverflowLimit &&
1935 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1936 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1937 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1938 OverflowLimit)))) {
1939 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1940 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001941 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001942 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1943 getSignExtendExprCached(Step, Ty, Cache), L,
1944 AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001945 }
1946 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001947
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001948 // If Start and Step are constants, check if we can apply this
1949 // transformation:
1950 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001951 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1952 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001953 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001954 const APInt &C1 = SC1->getAPInt();
1955 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001956 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1957 C2.isPowerOf2()) {
Wei Mi8c405332017-04-17 20:40:05 +00001958 Start = getSignExtendExprCached(Start, Ty, Cache);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001959 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1960 AR->getNoWrapFlags());
Wei Mi8c405332017-04-17 20:40:05 +00001961 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001962 }
1963 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001964
1965 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1966 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1967 return getAddRecExpr(
Wei Mi8c405332017-04-17 20:40:05 +00001968 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1969 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001970 }
Dan Gohman76466372009-04-27 20:16:15 +00001971 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001972
Sanjoy Das11ef6062016-03-03 18:31:23 +00001973 // If the input value is provably positive and we could not simplify
1974 // away the sext build a zext instead.
1975 if (isKnownNonNegative(Op))
1976 return getZeroExtendExpr(Op, Ty);
1977
Dan Gohman74a0ba12009-07-13 20:55:53 +00001978 // The cast wasn't folded; create an explicit cast node.
1979 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001980 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001981 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1982 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001983 UniqueSCEVs.InsertNode(S, IP);
1984 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001985}
1986
Dan Gohman8db2edc2009-06-13 15:56:47 +00001987/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1988/// unspecified bits out to the given type.
1989///
Dan Gohmanaf752342009-07-07 17:06:11 +00001990const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001991 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1993 "This is not an extending conversion!");
1994 assert(isSCEVable(Ty) &&
1995 "This is not a conversion to a SCEVable type!");
1996 Ty = getEffectiveSCEVType(Ty);
1997
1998 // Sign-extend negative constants.
1999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002000 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00002001 return getSignExtendExpr(Op, Ty);
2002
2003 // Peel off a truncate cast.
2004 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002005 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00002006 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2007 return getAnyExtendExpr(NewOp, Ty);
2008 return getTruncateOrNoop(NewOp, Ty);
2009 }
2010
2011 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00002012 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00002013 if (!isa<SCEVZeroExtendExpr>(ZExt))
2014 return ZExt;
2015
2016 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00002017 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00002018 if (!isa<SCEVSignExtendExpr>(SExt))
2019 return SExt;
2020
Dan Gohman51ad99d2010-01-21 02:09:26 +00002021 // Force the cast to be folded into the operands of an addrec.
2022 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2023 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00002024 for (const SCEV *Op : AR->operands())
2025 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002026 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002027 }
2028
Dan Gohman8db2edc2009-06-13 15:56:47 +00002029 // If the expression is obviously signed, use the sext cast value.
2030 if (isa<SCEVSMaxExpr>(Op))
2031 return SExt;
2032
2033 // Absent any other information, use the zext cast value.
2034 return ZExt;
2035}
2036
Sanjoy Dasf8570812016-05-29 00:38:22 +00002037/// Process the given Ops list, which is a list of operands to be added under
2038/// the given scale, update the given map. This is a helper function for
2039/// getAddRecExpr. As an example of what it does, given a sequence of operands
2040/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00002041///
Tobias Grosserba49e422014-03-05 10:37:17 +00002042/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00002043///
2044/// where A and B are constants, update the map with these values:
2045///
2046/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2047///
2048/// and add 13 + A*B*29 to AccumulatedConstant.
2049/// This will allow getAddRecExpr to produce this:
2050///
2051/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2052///
2053/// This form often exposes folding opportunities that are hidden in
2054/// the original operand list.
2055///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002056/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00002057/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2058/// the common case where no interesting opportunities are present, and
2059/// is also used as a check to avoid infinite recursion.
2060///
2061static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00002062CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002063 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00002064 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002065 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00002066 const APInt &Scale,
2067 ScalarEvolution &SE) {
2068 bool Interesting = false;
2069
Dan Gohman45073042010-06-18 19:12:32 +00002070 // Iterate over the add operands. They are sorted, with constants first.
2071 unsigned i = 0;
2072 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2073 ++i;
2074 // Pull a buried constant out to the outside.
2075 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2076 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002077 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00002078 }
2079
2080 // Next comes everything else. We're especially interested in multiplies
2081 // here, but they're in the middle, so just visit the rest with one loop.
2082 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002083 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2084 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2085 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002086 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002087 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2088 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002089 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002090 Interesting |=
2091 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002092 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002093 NewScale, SE);
2094 } else {
2095 // A multiplication of a constant with some other value. Update
2096 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002097 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2098 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002099 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002100 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002101 NewOps.push_back(Pair.first->first);
2102 } else {
2103 Pair.first->second += NewScale;
2104 // The map already had an entry for this value, which may indicate
2105 // a folding opportunity.
2106 Interesting = true;
2107 }
2108 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002109 } else {
2110 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002111 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002112 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002113 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002114 NewOps.push_back(Pair.first->first);
2115 } else {
2116 Pair.first->second += Scale;
2117 // The map already had an entry for this value, which may indicate
2118 // a folding opportunity.
2119 Interesting = true;
2120 }
2121 }
2122 }
2123
2124 return Interesting;
2125}
2126
Sanjoy Das81401d42015-01-10 23:41:24 +00002127// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2128// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2129// can't-overflow flags for the operation if possible.
2130static SCEV::NoWrapFlags
2131StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2132 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002133 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002134 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002135 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002136
2137 bool CanAnalyze =
2138 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2139 (void)CanAnalyze;
2140 assert(CanAnalyze && "don't call from other places!");
2141
2142 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2143 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002144 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002145
2146 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002147 auto IsKnownNonNegative = [&](const SCEV *S) {
2148 return SE->isKnownNonNegative(S);
2149 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002150
Sanjoy Das3b827c72015-11-29 23:40:53 +00002151 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002152 Flags =
2153 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002154
Sanjoy Das8f274152015-10-22 19:57:19 +00002155 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2156
2157 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2158 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2159
2160 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2161 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2162
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002163 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002164 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002165 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2166 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002167 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2168 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2169 }
2170 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002171 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2172 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002173 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2174 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2175 }
2176 }
2177
2178 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002179}
2180
Max Kazantsevd8fe3eb2017-05-30 10:54:58 +00002181bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
Max Kazantsev41450322017-05-26 06:47:04 +00002182 if (!isLoopInvariant(S, L))
2183 return false;
2184 // If a value depends on a SCEVUnknown which is defined after the loop, we
2185 // conservatively assume that we cannot calculate it at the loop's entry.
2186 struct FindDominatedSCEVUnknown {
2187 bool Found = false;
2188 const Loop *L;
2189 DominatorTree &DT;
2190 LoopInfo &LI;
2191
2192 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2193 : L(L), DT(DT), LI(LI) {}
2194
2195 bool checkSCEVUnknown(const SCEVUnknown *SU) {
2196 if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2197 if (DT.dominates(L->getHeader(), I->getParent()))
2198 Found = true;
2199 else
2200 assert(DT.dominates(I->getParent(), L->getHeader()) &&
2201 "No dominance relationship between SCEV and loop?");
2202 }
2203 return false;
2204 }
2205
2206 bool follow(const SCEV *S) {
2207 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2208 case scConstant:
2209 return false;
2210 case scAddRecExpr:
2211 case scTruncate:
2212 case scZeroExtend:
2213 case scSignExtend:
2214 case scAddExpr:
2215 case scMulExpr:
2216 case scUMaxExpr:
2217 case scSMaxExpr:
2218 case scUDivExpr:
2219 return true;
2220 case scUnknown:
2221 return checkSCEVUnknown(cast<SCEVUnknown>(S));
2222 case scCouldNotCompute:
2223 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2224 }
2225 return false;
2226 }
2227
2228 bool isDone() { return Found; }
2229 };
2230
2231 FindDominatedSCEVUnknown FSU(L, DT, LI);
2232 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2233 ST.visitAll(S);
2234 return !FSU.Found;
2235}
2236
Sanjoy Dasf8570812016-05-29 00:38:22 +00002237/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002238const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002239 SCEV::NoWrapFlags Flags,
2240 unsigned Depth) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002241 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2242 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002243 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002244 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002245#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002246 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002247 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002248 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002249 "SCEVAddExpr operand types don't match!");
2250#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002251
2252 // Sort by complexity, this groups all similar expression types together.
Max Kazantsevb09b5db2017-05-16 07:27:06 +00002253 GroupByComplexity(Ops, &LI, DT);
Chris Lattnerd934c702004-04-02 20:23:17 +00002254
Sanjoy Das64895612015-10-09 02:44:45 +00002255 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2256
Chris Lattnerd934c702004-04-02 20:23:17 +00002257 // If there are any constants, fold them together.
2258 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002259 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002260 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002261 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002262 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002263 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002264 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002265 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002266 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002267 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002268 }
2269
2270 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002271 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002272 Ops.erase(Ops.begin());
2273 --Idx;
2274 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002275
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002276 if (Ops.size() == 1) return Ops[0];
2277 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002278
Max Kazantsevdc803662017-06-15 11:48:21 +00002279 // Limit recursion calls depth.
2280 if (Depth > MaxArithDepth)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002281 return getOrCreateAddExpr(Ops, Flags);
2282
Dan Gohman15871f22010-08-27 21:39:59 +00002283 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002284 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002285 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002286 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002287 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002288 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002289 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002290 // Scan ahead to count how many equal operands there are.
2291 unsigned Count = 2;
2292 while (i+Count != e && Ops[i+Count] == Ops[i])
2293 ++Count;
2294 // Merge the values into a multiply.
2295 const SCEV *Scale = getConstant(Ty, Count);
Max Kazantsevdc803662017-06-15 11:48:21 +00002296 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman15871f22010-08-27 21:39:59 +00002297 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002298 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002299 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002300 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002301 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002302 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002303 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002304 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002305 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002306
Dan Gohman2e55cc52009-05-08 21:03:19 +00002307 // Check for truncates. If all the operands are truncated from the same
2308 // type, see if factoring out the truncate would permit the result to be
2309 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2310 // if the contents of the resulting outer trunc fold to something simple.
2311 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2312 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002313 Type *DstType = Trunc->getType();
2314 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002315 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002316 bool Ok = true;
2317 // Check all the operands to see if they can be represented in the
2318 // source type of the truncate.
2319 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2320 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2321 if (T->getOperand()->getType() != SrcType) {
2322 Ok = false;
2323 break;
2324 }
2325 LargeOps.push_back(T->getOperand());
2326 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002327 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002328 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002329 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002330 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2331 if (const SCEVTruncateExpr *T =
2332 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2333 if (T->getOperand()->getType() != SrcType) {
2334 Ok = false;
2335 break;
2336 }
2337 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002338 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002339 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002340 } else {
2341 Ok = false;
2342 break;
2343 }
2344 }
2345 if (Ok)
Max Kazantsevdc803662017-06-15 11:48:21 +00002346 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002347 } else {
2348 Ok = false;
2349 break;
2350 }
2351 }
2352 if (Ok) {
2353 // Evaluate the expression in the larger type.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002354 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002355 // If it folds to something simple, use it. Otherwise, don't.
2356 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2357 return getTruncateExpr(Fold, DstType);
2358 }
2359 }
2360
2361 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002362 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2363 ++Idx;
2364
2365 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002366 if (Idx < Ops.size()) {
2367 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002368 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Daniil Fukalovb09dac52017-01-26 13:33:17 +00002369 if (Ops.size() > AddOpsInlineThreshold ||
2370 Add->getNumOperands() > AddOpsInlineThreshold)
2371 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002372 // If we have an add, expand the add operands onto the end of the operands
2373 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002374 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002375 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002376 DeletedAdd = true;
2377 }
2378
2379 // If we deleted at least one add, we added operands to the end of the list,
2380 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002381 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002382 if (DeletedAdd)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002383 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002384 }
2385
2386 // Skip over the add expression until we get to a multiply.
2387 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2388 ++Idx;
2389
Dan Gohman038d02e2009-06-14 22:58:51 +00002390 // Check to see if there are any folding opportunities present with
2391 // operands multiplied by constant values.
2392 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2393 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002394 DenseMap<const SCEV *, APInt> M;
2395 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002396 APInt AccumulatedConstant(BitWidth, 0);
2397 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002398 Ops.data(), Ops.size(),
2399 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002400 struct APIntCompare {
2401 bool operator()(const APInt &LHS, const APInt &RHS) const {
2402 return LHS.ult(RHS);
2403 }
2404 };
2405
Dan Gohman038d02e2009-06-14 22:58:51 +00002406 // Some interesting folding opportunity is present, so its worthwhile to
2407 // re-generate the operands list. Group the operands by constant scale,
2408 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002409 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002410 for (const SCEV *NewOp : NewOps)
2411 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002412 // Re-generate the operands list.
2413 Ops.clear();
2414 if (AccumulatedConstant != 0)
2415 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002416 for (auto &MulOp : MulOpLists)
2417 if (MulOp.first != 0)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002418 Ops.push_back(getMulExpr(
2419 getConstant(MulOp.first),
Max Kazantsevdc803662017-06-15 11:48:21 +00002420 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2421 SCEV::FlagAnyWrap, Depth + 1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002422 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002423 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002424 if (Ops.size() == 1)
2425 return Ops[0];
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002426 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman038d02e2009-06-14 22:58:51 +00002427 }
2428 }
2429
Chris Lattnerd934c702004-04-02 20:23:17 +00002430 // If we are adding something to a multiply expression, make sure the
2431 // something is not already an operand of the multiply. If so, merge it into
2432 // the multiply.
2433 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002434 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002435 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002436 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002437 if (isa<SCEVConstant>(MulOpSCEV))
2438 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002439 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002440 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002441 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002442 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002443 if (Mul->getNumOperands() != 2) {
2444 // If the multiply has more than two operands, we must get the
2445 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002446 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2447 Mul->op_begin()+MulOp);
2448 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Max Kazantsevdc803662017-06-15 11:48:21 +00002449 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002450 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002451 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2452 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Max Kazantsevdc803662017-06-15 11:48:21 +00002453 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2454 SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002455 if (Ops.size() == 2) return OuterMul;
2456 if (AddOp < Idx) {
2457 Ops.erase(Ops.begin()+AddOp);
2458 Ops.erase(Ops.begin()+Idx-1);
2459 } else {
2460 Ops.erase(Ops.begin()+Idx);
2461 Ops.erase(Ops.begin()+AddOp-1);
2462 }
2463 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002464 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002465 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002466
Chris Lattnerd934c702004-04-02 20:23:17 +00002467 // Check this multiply against other multiplies being added together.
2468 for (unsigned OtherMulIdx = Idx+1;
2469 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2470 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002471 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002472 // If MulOp occurs in OtherMul, we can fold the two multiplies
2473 // together.
2474 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2475 OMulOp != e; ++OMulOp)
2476 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2477 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002478 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002479 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002480 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002481 Mul->op_begin()+MulOp);
2482 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Max Kazantsevdc803662017-06-15 11:48:21 +00002483 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002484 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002485 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002486 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002487 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002488 OtherMul->op_begin()+OMulOp);
2489 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Max Kazantsevdc803662017-06-15 11:48:21 +00002490 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002491 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002492 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2493 const SCEV *InnerMulSum =
2494 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Max Kazantsevdc803662017-06-15 11:48:21 +00002495 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2496 SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002497 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002498 Ops.erase(Ops.begin()+Idx);
2499 Ops.erase(Ops.begin()+OtherMulIdx-1);
2500 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002501 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002502 }
2503 }
2504 }
2505 }
2506
2507 // If there are any add recurrences in the operands list, see if any other
2508 // added values are loop invariant. If so, we can fold them into the
2509 // recurrence.
2510 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2511 ++Idx;
2512
2513 // Scan over all recurrences, trying to fold loop invariants into them.
2514 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2515 // Scan all of the other operands to this add and add them to the vector if
2516 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002517 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002518 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002519 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002520 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Max Kazantsevd8fe3eb2017-05-30 10:54:58 +00002521 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002522 LIOps.push_back(Ops[i]);
2523 Ops.erase(Ops.begin()+i);
2524 --i; --e;
2525 }
2526
2527 // If we found some loop invariants, fold them into the recurrence.
2528 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002529 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002530 LIOps.push_back(AddRec->getStart());
2531
Dan Gohmanaf752342009-07-07 17:06:11 +00002532 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002533 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002534 // This follows from the fact that the no-wrap flags on the outer add
2535 // expression are applicable on the 0th iteration, when the add recurrence
2536 // will be equal to its start value.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002537 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002538
Dan Gohman16206132010-06-30 07:16:37 +00002539 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002540 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002541 // Always propagate NW.
2542 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002543 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002544
Chris Lattnerd934c702004-04-02 20:23:17 +00002545 // If all of the other operands were loop invariant, we are done.
2546 if (Ops.size() == 1) return NewRec;
2547
Nick Lewyckydb66b822011-09-06 05:08:09 +00002548 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002549 for (unsigned i = 0;; ++i)
2550 if (Ops[i] == AddRec) {
2551 Ops[i] = NewRec;
2552 break;
2553 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002554 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002555 }
2556
2557 // Okay, if there weren't any loop invariants to be folded, check to see if
2558 // there are multiple AddRec's with the same loop induction variable being
2559 // added together. If so, we can fold them.
2560 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002561 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Max Kazantsevb09b5db2017-05-16 07:27:06 +00002562 ++OtherIdx) {
2563 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2564 // so that the 1st found AddRecExpr is dominated by all others.
2565 assert(DT.dominates(
2566 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2567 AddRec->getLoop()->getHeader()) &&
2568 "AddRecExprs are not sorted in reverse dominance order?");
Dan Gohmanc866bf42010-08-27 20:45:56 +00002569 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2570 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2571 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2572 AddRec->op_end());
2573 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Max Kazantsevb67d3442017-05-17 03:58:42 +00002574 ++OtherIdx) {
2575 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2576 if (OtherAddRec->getLoop() == AddRecLoop) {
2577 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2578 i != e; ++i) {
2579 if (i >= AddRecOps.size()) {
2580 AddRecOps.append(OtherAddRec->op_begin()+i,
2581 OtherAddRec->op_end());
2582 break;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002583 }
Max Kazantsevb67d3442017-05-17 03:58:42 +00002584 SmallVector<const SCEV *, 2> TwoOps = {
2585 AddRecOps[i], OtherAddRec->getOperand(i)};
2586 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002587 }
Max Kazantsevb67d3442017-05-17 03:58:42 +00002588 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2589 }
2590 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002591 // Step size has changed, so we cannot guarantee no self-wraparound.
2592 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002593 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002594 }
Max Kazantsevb09b5db2017-05-16 07:27:06 +00002595 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002596
2597 // Otherwise couldn't fold anything into this recurrence. Move onto the
2598 // next one.
2599 }
2600
2601 // Okay, it looks like we really DO need an add expr. Check to see if we
2602 // already have one, otherwise create a new one.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002603 return getOrCreateAddExpr(Ops, Flags);
2604}
2605
2606const SCEV *
2607ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2608 SCEV::NoWrapFlags Flags) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002609 FoldingSetNodeID ID;
2610 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002611 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2612 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002613 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002614 SCEVAddExpr *S =
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002615 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
Dan Gohman51ad99d2010-01-21 02:09:26 +00002616 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002617 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2618 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002619 S = new (SCEVAllocator)
2620 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002621 UniqueSCEVs.InsertNode(S, IP);
2622 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002623 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002624 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002625}
2626
Max Kazantsevdc803662017-06-15 11:48:21 +00002627const SCEV *
2628ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2629 SCEV::NoWrapFlags Flags) {
2630 FoldingSetNodeID ID;
2631 ID.AddInteger(scMulExpr);
2632 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2633 ID.AddPointer(Ops[i]);
2634 void *IP = nullptr;
2635 SCEVMulExpr *S =
2636 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2637 if (!S) {
2638 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2639 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2640 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2641 O, Ops.size());
2642 UniqueSCEVs.InsertNode(S, IP);
2643 }
2644 S->setNoWrapFlags(Flags);
2645 return S;
2646}
2647
Nick Lewycky287682e2011-10-04 06:51:26 +00002648static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2649 uint64_t k = i*j;
2650 if (j > 1 && k / j != i) Overflow = true;
2651 return k;
2652}
2653
2654/// Compute the result of "n choose k", the binomial coefficient. If an
2655/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002656/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002657static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2658 // We use the multiplicative formula:
2659 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2660 // At each iteration, we take the n-th term of the numeral and divide by the
2661 // (k-n)th term of the denominator. This division will always produce an
2662 // integral result, and helps reduce the chance of overflow in the
2663 // intermediate computations. However, we can still overflow even when the
2664 // final result would fit.
2665
2666 if (n == 0 || n == k) return 1;
2667 if (k > n) return 0;
2668
2669 if (k > n/2)
2670 k = n-k;
2671
2672 uint64_t r = 1;
2673 for (uint64_t i = 1; i <= k; ++i) {
2674 r = umul_ov(r, n-(i-1), Overflow);
2675 r /= i;
2676 }
2677 return r;
2678}
2679
Nick Lewycky05044c22014-12-06 00:45:50 +00002680/// Determine if any of the operands in this SCEV are a constant or if
2681/// any of the add or multiply expressions in this SCEV contain a constant.
2682static bool containsConstantSomewhere(const SCEV *StartExpr) {
2683 SmallVector<const SCEV *, 4> Ops;
2684 Ops.push_back(StartExpr);
2685 while (!Ops.empty()) {
2686 const SCEV *CurrentExpr = Ops.pop_back_val();
2687 if (isa<SCEVConstant>(*CurrentExpr))
2688 return true;
2689
2690 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2691 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002692 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002693 }
2694 }
2695 return false;
2696}
2697
Sanjoy Dasf8570812016-05-29 00:38:22 +00002698/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002699const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Max Kazantsevdc803662017-06-15 11:48:21 +00002700 SCEV::NoWrapFlags Flags,
2701 unsigned Depth) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002702 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2703 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002704 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002705 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002706#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002707 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002708 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002709 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002710 "SCEVMulExpr operand types don't match!");
2711#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002712
2713 // Sort by complexity, this groups all similar expression types together.
Max Kazantsevb09b5db2017-05-16 07:27:06 +00002714 GroupByComplexity(Ops, &LI, DT);
Chris Lattnerd934c702004-04-02 20:23:17 +00002715
Sanjoy Das64895612015-10-09 02:44:45 +00002716 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2717
Max Kazantsevdc803662017-06-15 11:48:21 +00002718 // Limit recursion calls depth.
2719 if (Depth > MaxArithDepth)
2720 return getOrCreateMulExpr(Ops, Flags);
2721
Chris Lattnerd934c702004-04-02 20:23:17 +00002722 // If there are any constants, fold them together.
2723 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002724 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002725
2726 // C1*(C2+V) -> C1*C2 + C1*V
2727 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002728 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2729 // If any of Add's ops are Adds or Muls with a constant,
2730 // apply this transformation as well.
2731 if (Add->getNumOperands() == 2)
2732 if (containsConstantSomewhere(Add))
Max Kazantsevdc803662017-06-15 11:48:21 +00002733 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2734 SCEV::FlagAnyWrap, Depth + 1),
2735 getMulExpr(LHSC, Add->getOperand(1),
2736 SCEV::FlagAnyWrap, Depth + 1),
2737 SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002738
Chris Lattnerd934c702004-04-02 20:23:17 +00002739 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002740 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002741 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002742 ConstantInt *Fold =
2743 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002744 Ops[0] = getConstant(Fold);
2745 Ops.erase(Ops.begin()+1); // Erase the folded element
2746 if (Ops.size() == 1) return Ops[0];
2747 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002748 }
2749
2750 // If we are left with a constant one being multiplied, strip it off.
2751 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2752 Ops.erase(Ops.begin());
2753 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002754 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002755 // If we have a multiply of zero, it will always be zero.
2756 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002757 } else if (Ops[0]->isAllOnesValue()) {
2758 // If we have a mul by -1 of an add, try distributing the -1 among the
2759 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002760 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002761 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2762 SmallVector<const SCEV *, 4> NewOps;
2763 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002764 for (const SCEV *AddOp : Add->operands()) {
Max Kazantsevdc803662017-06-15 11:48:21 +00002765 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2766 Depth + 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002767 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2768 NewOps.push_back(Mul);
2769 }
2770 if (AnyFolded)
Max Kazantsevdc803662017-06-15 11:48:21 +00002771 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
Sanjoy Das63914592015-10-18 00:29:20 +00002772 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002773 // Negation preserves a recurrence's no self-wrap property.
2774 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002775 for (const SCEV *AddRecOp : AddRec->operands())
Max Kazantsevdc803662017-06-15 11:48:21 +00002776 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2777 Depth + 1));
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002778
Andrew Tricke92dcce2011-03-14 17:38:54 +00002779 return getAddRecExpr(Operands, AddRec->getLoop(),
2780 AddRec->getNoWrapFlags(SCEV::FlagNW));
2781 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002782 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002783 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002784
2785 if (Ops.size() == 1)
2786 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002787 }
2788
2789 // Skip over the add expression until we get to a multiply.
2790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2791 ++Idx;
2792
Chris Lattnerd934c702004-04-02 20:23:17 +00002793 // If there are mul operands inline them all into this expression.
2794 if (Idx < Ops.size()) {
2795 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002796 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002797 if (Ops.size() > MulOpsInlineThreshold)
2798 break;
Max Kazantsevdc803662017-06-15 11:48:21 +00002799 // If we have an mul, expand the mul operands onto the end of the
2800 // operands list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002801 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002802 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002803 DeletedMul = true;
2804 }
2805
Max Kazantsevdc803662017-06-15 11:48:21 +00002806 // If we deleted at least one mul, we added operands to the end of the
2807 // list, and they are not necessarily sorted. Recurse to resort and
2808 // resimplify any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002809 if (DeletedMul)
Max Kazantsevdc803662017-06-15 11:48:21 +00002810 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002811 }
2812
2813 // If there are any add recurrences in the operands list, see if any other
2814 // added values are loop invariant. If so, we can fold them into the
2815 // recurrence.
2816 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2817 ++Idx;
2818
2819 // Scan over all recurrences, trying to fold loop invariants into them.
2820 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
Max Kazantsevdc803662017-06-15 11:48:21 +00002821 // Scan all of the other operands to this mul and add them to the vector
2822 // if they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002823 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002824 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002825 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002826 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Max Kazantsevd8fe3eb2017-05-30 10:54:58 +00002827 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002828 LIOps.push_back(Ops[i]);
2829 Ops.erase(Ops.begin()+i);
2830 --i; --e;
2831 }
2832
2833 // If we found some loop invariants, fold them into the recurrence.
2834 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002835 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002836 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002837 NewOps.reserve(AddRec->getNumOperands());
Max Kazantsevdc803662017-06-15 11:48:21 +00002838 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman8f5954f2010-06-17 23:34:09 +00002839 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Max Kazantsevdc803662017-06-15 11:48:21 +00002840 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2841 SCEV::FlagAnyWrap, Depth + 1));
Chris Lattnerd934c702004-04-02 20:23:17 +00002842
Dan Gohman16206132010-06-30 07:16:37 +00002843 // Build the new addrec. Propagate the NUW and NSW flags if both the
2844 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002845 //
2846 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002847 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002848 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2849 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002850
2851 // If all of the other operands were loop invariant, we are done.
2852 if (Ops.size() == 1) return NewRec;
2853
Nick Lewyckydb66b822011-09-06 05:08:09 +00002854 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002855 for (unsigned i = 0;; ++i)
2856 if (Ops[i] == AddRec) {
2857 Ops[i] = NewRec;
2858 break;
2859 }
Max Kazantsevdc803662017-06-15 11:48:21 +00002860 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002861 }
2862
Max Kazantsevdc803662017-06-15 11:48:21 +00002863 // Okay, if there weren't any loop invariants to be folded, check to see
2864 // if there are multiple AddRec's with the same loop induction variable
2865 // being multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002866
2867 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2868 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2869 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2870 // ]]],+,...up to x=2n}.
2871 // Note that the arguments to choose() are always integers with values
2872 // known at compile time, never SCEV objects.
2873 //
2874 // The implementation avoids pointless extra computations when the two
2875 // addrec's are of different length (mathematically, it's equivalent to
2876 // an infinite stream of zeros on the right).
2877 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002878 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002879 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002880 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002881 const SCEVAddRecExpr *OtherAddRec =
2882 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2883 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002884 continue;
2885
Nick Lewycky97756402014-09-01 05:17:15 +00002886 bool Overflow = false;
2887 Type *Ty = AddRec->getType();
2888 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2889 SmallVector<const SCEV*, 7> AddRecOps;
2890 for (int x = 0, xe = AddRec->getNumOperands() +
2891 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002892 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002893 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2894 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2895 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2896 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2897 z < ze && !Overflow; ++z) {
2898 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2899 uint64_t Coeff;
2900 if (LargerThan64Bits)
2901 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2902 else
2903 Coeff = Coeff1*Coeff2;
2904 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2905 const SCEV *Term1 = AddRec->getOperand(y-z);
2906 const SCEV *Term2 = OtherAddRec->getOperand(z);
Max Kazantsevdc803662017-06-15 11:48:21 +00002907 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2908 SCEV::FlagAnyWrap, Depth + 1),
2909 SCEV::FlagAnyWrap, Depth + 1);
Andrew Trick946f76b2012-05-30 03:35:17 +00002910 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002911 }
Nick Lewycky97756402014-09-01 05:17:15 +00002912 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002913 }
Nick Lewycky97756402014-09-01 05:17:15 +00002914 if (!Overflow) {
2915 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2916 SCEV::FlagAnyWrap);
2917 if (Ops.size() == 2) return NewAddRec;
2918 Ops[Idx] = NewAddRec;
2919 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2920 OpsModified = true;
2921 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2922 if (!AddRec)
2923 break;
2924 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002925 }
Nick Lewycky97756402014-09-01 05:17:15 +00002926 if (OpsModified)
Max Kazantsevdc803662017-06-15 11:48:21 +00002927 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002928
2929 // Otherwise couldn't fold anything into this recurrence. Move onto the
2930 // next one.
2931 }
2932
2933 // Okay, it looks like we really DO need an mul expr. Check to see if we
2934 // already have one, otherwise create a new one.
Max Kazantsevdc803662017-06-15 11:48:21 +00002935 return getOrCreateMulExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002936}
2937
Sanjoy Dasf8570812016-05-29 00:38:22 +00002938/// Get a canonical unsigned division expression, or something simpler if
2939/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002940const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2941 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002942 assert(getEffectiveSCEVType(LHS->getType()) ==
2943 getEffectiveSCEVType(RHS->getType()) &&
2944 "SCEVUDivExpr operand types don't match!");
2945
Dan Gohmana30370b2009-05-04 22:02:23 +00002946 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002947 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002948 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002949 // If the denominator is zero, the result of the udiv is undefined. Don't
2950 // try to analyze it, because the resolution chosen here may differ from
2951 // the resolution chosen in other parts of the compiler.
2952 if (!RHSC->getValue()->isZero()) {
2953 // Determine if the division can be folded into the operands of
2954 // its operands.
2955 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002956 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002957 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002958 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002959 // For non-power-of-two values, effectively round the value up to the
2960 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002961 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002962 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002963 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002964 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002965 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2966 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002967 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2968 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002969 const APInt &StepInt = Step->getAPInt();
2970 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002971 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002972 getZeroExtendExpr(AR, ExtTy) ==
2973 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2974 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002975 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002976 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002977 for (const SCEV *Op : AR->operands())
2978 Operands.push_back(getUDivExpr(Op, RHS));
2979 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002980 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002981 /// Get a canonical UDivExpr for a recurrence.
2982 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2983 // We can currently only fold X%N if X is constant.
2984 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2985 if (StartC && !DivInt.urem(StepInt) &&
2986 getZeroExtendExpr(AR, ExtTy) ==
2987 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2988 getZeroExtendExpr(Step, ExtTy),
2989 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002990 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002991 const APInt &StartRem = StartInt.urem(StepInt);
2992 if (StartRem != 0)
2993 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2994 AR->getLoop(), SCEV::FlagNW);
2995 }
2996 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002997 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2998 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2999 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00003000 for (const SCEV *Op : M->operands())
3001 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00003002 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3003 // Find an operand that's safely divisible.
3004 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3005 const SCEV *Op = M->getOperand(i);
3006 const SCEV *Div = getUDivExpr(Op, RHSC);
3007 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3008 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3009 M->op_end());
3010 Operands[i] = Div;
3011 return getMulExpr(Operands);
3012 }
3013 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00003014 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00003015 // (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 +00003016 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00003017 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00003018 for (const SCEV *Op : A->operands())
3019 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00003020 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3021 Operands.clear();
3022 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3023 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3024 if (isa<SCEVUDivExpr>(Op) ||
3025 getMulExpr(Op, RHS) != A->getOperand(i))
3026 break;
3027 Operands.push_back(Op);
3028 }
3029 if (Operands.size() == A->getNumOperands())
3030 return getAddExpr(Operands);
3031 }
3032 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00003033
Dan Gohmanacd700a2010-04-22 01:35:11 +00003034 // Fold if both operands are constant.
3035 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3036 Constant *LHSCV = LHSC->getValue();
3037 Constant *RHSCV = RHSC->getValue();
3038 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3039 RHSCV)));
3040 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003041 }
3042 }
3043
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003044 FoldingSetNodeID ID;
3045 ID.AddInteger(scUDivExpr);
3046 ID.AddPointer(LHS);
3047 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00003048 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003049 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00003050 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3051 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003052 UniqueSCEVs.InsertNode(S, IP);
3053 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003054}
3055
Nick Lewycky31eaca52014-01-27 10:04:03 +00003056static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003057 APInt A = C1->getAPInt().abs();
3058 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00003059 uint32_t ABW = A.getBitWidth();
3060 uint32_t BBW = B.getBitWidth();
3061
3062 if (ABW > BBW)
3063 B = B.zext(ABW);
3064 else if (ABW < BBW)
3065 A = A.zext(BBW);
3066
Craig Topper69f1af22017-05-06 05:22:56 +00003067 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
Nick Lewycky31eaca52014-01-27 10:04:03 +00003068}
3069
Sanjoy Dasf8570812016-05-29 00:38:22 +00003070/// Get a canonical unsigned division expression, or something simpler if
3071/// possible. There is no representation for an exact udiv in SCEV IR, but we
3072/// can attempt to remove factors from the LHS and RHS. We can't do this when
3073/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00003074const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3075 const SCEV *RHS) {
3076 // TODO: we could try to find factors in all sorts of things, but for now we
3077 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3078 // end of this file for inspiration.
3079
3080 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
Eli Friedmanf1f49c82017-01-18 23:56:42 +00003081 if (!Mul || !Mul->hasNoUnsignedWrap())
Nick Lewycky31eaca52014-01-27 10:04:03 +00003082 return getUDivExpr(LHS, RHS);
3083
3084 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3085 // If the mulexpr multiplies by a constant, then that constant must be the
3086 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00003087 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00003088 if (LHSCst == RHSCst) {
3089 SmallVector<const SCEV *, 2> Operands;
3090 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3091 return getMulExpr(Operands);
3092 }
3093
3094 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3095 // that there's a factor provided by one of the other terms. We need to
3096 // check.
3097 APInt Factor = gcd(LHSCst, RHSCst);
3098 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003099 LHSCst =
3100 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3101 RHSCst =
3102 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00003103 SmallVector<const SCEV *, 2> Operands;
3104 Operands.push_back(LHSCst);
3105 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3106 LHS = getMulExpr(Operands);
3107 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00003108 Mul = dyn_cast<SCEVMulExpr>(LHS);
3109 if (!Mul)
3110 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00003111 }
3112 }
3113 }
3114
3115 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3116 if (Mul->getOperand(i) == RHS) {
3117 SmallVector<const SCEV *, 2> Operands;
3118 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3119 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3120 return getMulExpr(Operands);
3121 }
3122 }
3123
3124 return getUDivExpr(LHS, RHS);
3125}
Chris Lattnerd934c702004-04-02 20:23:17 +00003126
Sanjoy Dasf8570812016-05-29 00:38:22 +00003127/// Get an add recurrence expression for the specified loop. Simplify the
3128/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00003129const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3130 const Loop *L,
3131 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003132 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00003133 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00003134 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00003135 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00003136 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003137 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00003138 }
3139
3140 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00003141 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00003142}
3143
Sanjoy Dasf8570812016-05-29 00:38:22 +00003144/// Get an add recurrence expression for the specified loop. Simplify the
3145/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00003146const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00003147ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00003148 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003149 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003150#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003151 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003152 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003153 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003154 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003155 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00003156 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003157 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00003158#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00003159
Dan Gohmanbe928e32008-06-18 16:23:07 +00003160 if (Operands.back()->isZero()) {
3161 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00003162 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00003163 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003164
Dan Gohmancf9c64e2010-02-19 18:49:22 +00003165 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3166 // use that information to infer NUW and NSW flags. However, computing a
3167 // BE count requires calling getAddRecExpr, so we may not yet have a
3168 // meaningful BE count at this point (and if we don't, we'd be stuck
3169 // with a SCEVCouldNotCompute as the cached BE count).
3170
Sanjoy Das81401d42015-01-10 23:41:24 +00003171 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003172
Dan Gohman223a5d22008-08-08 18:33:12 +00003173 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00003174 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00003175 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003176 if (L->contains(NestedLoop)
3177 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3178 : (!NestedLoop->contains(L) &&
3179 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003180 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00003181 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00003182 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00003183 // AddRecs require their operands be loop-invariant with respect to their
3184 // loops. Don't perform this transformation if it would break this
3185 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00003186 bool AllInvariant = all_of(
3187 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003188
Dan Gohmancc030b72009-06-26 22:36:20 +00003189 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003190 // Create a recurrence for the outer loop with the same step size.
3191 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003192 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3193 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003194 SCEV::NoWrapFlags OuterFlags =
3195 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003196
3197 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003198 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3199 return isLoopInvariant(Op, NestedLoop);
3200 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003201
Andrew Trick8b55b732011-03-14 16:50:06 +00003202 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003203 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003204 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003205 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3206 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003207 SCEV::NoWrapFlags InnerFlags =
3208 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003209 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3210 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003211 }
3212 // Reset Operands to its original state.
3213 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003214 }
3215 }
3216
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003217 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3218 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003219 FoldingSetNodeID ID;
3220 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003221 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3222 ID.AddPointer(Operands[i]);
3223 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003224 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003225 SCEVAddRecExpr *S =
3226 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3227 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003228 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3229 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003230 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3231 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003232 UniqueSCEVs.InsertNode(S, IP);
3233 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003234 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003235 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003236}
3237
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003238const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003239ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3240 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3241 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003242 // getSCEV(Base)->getType() has the same address space as Base->getType()
3243 // because SCEV::getType() preserves the address space.
3244 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3245 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3246 // instruction to its SCEV, because the Instruction may be guarded by control
3247 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003248 // context. This can be fixed similarly to how these flags are handled for
3249 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003250 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3251 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003252
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003253 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003254 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003255 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003256 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003257 for (const SCEV *IndexExpr : IndexExprs) {
3258 // Compute the (potentially symbolic) offset in bytes for this index.
3259 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3260 // For a struct, add the member offset.
3261 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3262 unsigned FieldNo = Index->getZExtValue();
3263 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3264
3265 // Add the field offset to the running total offset.
3266 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3267
3268 // Update CurTy to the type of the field at Index.
3269 CurTy = STy->getTypeAtIndex(Index);
3270 } else {
3271 // Update CurTy to its element type.
3272 CurTy = cast<SequentialType>(CurTy)->getElementType();
3273 // For an array, add the element offset, explicitly scaled.
3274 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3275 // Getelementptr indices are signed.
3276 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3277
3278 // Multiply the index by the element size to compute the element offset.
3279 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3280
3281 // Add the element offset to the running total offset.
3282 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3283 }
3284 }
3285
3286 // Add the total offset from all the GEP indices to the base.
3287 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3288}
3289
Dan Gohmanabd17092009-06-24 14:49:00 +00003290const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3291 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003292 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003293 return getSMaxExpr(Ops);
3294}
3295
Dan Gohmanaf752342009-07-07 17:06:11 +00003296const SCEV *
3297ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003298 assert(!Ops.empty() && "Cannot get empty smax!");
3299 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003300#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003301 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003302 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003303 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003304 "SCEVSMaxExpr operand types don't match!");
3305#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003306
3307 // Sort by complexity, this groups all similar expression types together.
Max Kazantsevb09b5db2017-05-16 07:27:06 +00003308 GroupByComplexity(Ops, &LI, DT);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003309
3310 // If there are any constants, fold them together.
3311 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003312 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003313 ++Idx;
3314 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003315 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003316 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003317 ConstantInt *Fold = ConstantInt::get(
3318 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003319 Ops[0] = getConstant(Fold);
3320 Ops.erase(Ops.begin()+1); // Erase the folded element
3321 if (Ops.size() == 1) return Ops[0];
3322 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003323 }
3324
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003325 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003326 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3327 Ops.erase(Ops.begin());
3328 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003329 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3330 // If we have an smax with a constant maximum-int, it will always be
3331 // maximum-int.
3332 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003333 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003334
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003335 if (Ops.size() == 1) return Ops[0];
3336 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003337
3338 // Find the first SMax
3339 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3340 ++Idx;
3341
3342 // Check to see if one of the operands is an SMax. If so, expand its operands
3343 // onto our operand list, and recurse to simplify.
3344 if (Idx < Ops.size()) {
3345 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003346 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003347 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003348 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003349 DeletedSMax = true;
3350 }
3351
3352 if (DeletedSMax)
3353 return getSMaxExpr(Ops);
3354 }
3355
3356 // Okay, check to see if the same value occurs in the operand list twice. If
3357 // so, delete one. Since we sorted the list, these values are required to
3358 // be adjacent.
3359 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003360 // X smax Y smax Y --> X smax Y
3361 // X smax Y --> X, if X is always greater than Y
3362 if (Ops[i] == Ops[i+1] ||
3363 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3364 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3365 --i; --e;
3366 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003367 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3368 --i; --e;
3369 }
3370
3371 if (Ops.size() == 1) return Ops[0];
3372
3373 assert(!Ops.empty() && "Reduced smax down to nothing!");
3374
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003375 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003376 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003377 FoldingSetNodeID ID;
3378 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003379 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3380 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003381 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003382 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003383 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3384 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003385 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3386 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003387 UniqueSCEVs.InsertNode(S, IP);
3388 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003389}
3390
Dan Gohmanabd17092009-06-24 14:49:00 +00003391const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3392 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003393 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003394 return getUMaxExpr(Ops);
3395}
3396
Dan Gohmanaf752342009-07-07 17:06:11 +00003397const SCEV *
3398ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003399 assert(!Ops.empty() && "Cannot get empty umax!");
3400 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003401#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003402 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003403 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003404 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003405 "SCEVUMaxExpr operand types don't match!");
3406#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003407
3408 // Sort by complexity, this groups all similar expression types together.
Max Kazantsevb09b5db2017-05-16 07:27:06 +00003409 GroupByComplexity(Ops, &LI, DT);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003410
3411 // If there are any constants, fold them together.
3412 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003413 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003414 ++Idx;
3415 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003416 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003417 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003418 ConstantInt *Fold = ConstantInt::get(
3419 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003420 Ops[0] = getConstant(Fold);
3421 Ops.erase(Ops.begin()+1); // Erase the folded element
3422 if (Ops.size() == 1) return Ops[0];
3423 LHSC = cast<SCEVConstant>(Ops[0]);
3424 }
3425
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003426 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003427 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3428 Ops.erase(Ops.begin());
3429 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003430 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3431 // If we have an umax with a constant maximum-int, it will always be
3432 // maximum-int.
3433 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003434 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003435
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003436 if (Ops.size() == 1) return Ops[0];
3437 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003438
3439 // Find the first UMax
3440 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3441 ++Idx;
3442
3443 // Check to see if one of the operands is a UMax. If so, expand its operands
3444 // onto our operand list, and recurse to simplify.
3445 if (Idx < Ops.size()) {
3446 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003447 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003448 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003449 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003450 DeletedUMax = true;
3451 }
3452
3453 if (DeletedUMax)
3454 return getUMaxExpr(Ops);
3455 }
3456
3457 // Okay, check to see if the same value occurs in the operand list twice. If
3458 // so, delete one. Since we sorted the list, these values are required to
3459 // be adjacent.
3460 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003461 // X umax Y umax Y --> X umax Y
3462 // X umax Y --> X, if X is always greater than Y
3463 if (Ops[i] == Ops[i+1] ||
3464 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3465 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3466 --i; --e;
3467 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003468 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3469 --i; --e;
3470 }
3471
3472 if (Ops.size() == 1) return Ops[0];
3473
3474 assert(!Ops.empty() && "Reduced umax down to nothing!");
3475
3476 // Okay, it looks like we really DO need a umax expr. Check to see if we
3477 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003478 FoldingSetNodeID ID;
3479 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003480 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3481 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003482 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003483 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003484 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3485 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003486 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3487 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003488 UniqueSCEVs.InsertNode(S, IP);
3489 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003490}
3491
Dan Gohmanabd17092009-06-24 14:49:00 +00003492const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3493 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003494 // ~smax(~x, ~y) == smin(x, y).
3495 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3496}
3497
Dan Gohmanabd17092009-06-24 14:49:00 +00003498const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3499 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003500 // ~umax(~x, ~y) == umin(x, y)
3501 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3502}
3503
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003504const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003505 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003506 // constant expression and then folding it back into a ConstantInt.
3507 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003508 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003509}
3510
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003511const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3512 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003513 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003514 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003515 // constant expression and then folding it back into a ConstantInt.
3516 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003517 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003518 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003519}
3520
Dan Gohmanaf752342009-07-07 17:06:11 +00003521const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003522 // Don't attempt to do anything other than create a SCEVUnknown object
3523 // here. createSCEV only calls getUnknown after checking for all other
3524 // interesting possibilities, and any other code that calls getUnknown
3525 // is doing so in order to hide a value from SCEV canonicalization.
3526
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003527 FoldingSetNodeID ID;
3528 ID.AddInteger(scUnknown);
3529 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003530 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003531 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3532 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3533 "Stale SCEVUnknown in uniquing map!");
3534 return S;
3535 }
3536 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3537 FirstUnknown);
3538 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003539 UniqueSCEVs.InsertNode(S, IP);
3540 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003541}
3542
Chris Lattnerd934c702004-04-02 20:23:17 +00003543//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003544// Basic SCEV Analysis and PHI Idiom Recognition Code
3545//
3546
Sanjoy Dasf8570812016-05-29 00:38:22 +00003547/// Test if values of the given type are analyzable within the SCEV
3548/// framework. This primarily includes integer types, and it can optionally
3549/// include pointer types if the ScalarEvolution class has access to
3550/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003551bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003552 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003553 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003554}
3555
Sanjoy Dasf8570812016-05-29 00:38:22 +00003556/// Return the size in bits of the specified type, for which isSCEVable must
3557/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003558uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003559 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003560 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003561}
3562
Sanjoy Dasf8570812016-05-29 00:38:22 +00003563/// Return a type with the same bitwidth as the given type and which represents
3564/// how SCEV will treat the given type, for which isSCEVable must return
3565/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003566Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003567 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3568
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003569 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003570 return Ty;
3571
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003572 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003573 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003574 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003575}
Chris Lattnerd934c702004-04-02 20:23:17 +00003576
Max Kazantsev2e44d292017-03-31 12:05:30 +00003577Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3578 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3579}
3580
Dan Gohmanaf752342009-07-07 17:06:11 +00003581const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003582 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003583}
3584
Sanjoy Das7d752672015-12-08 04:32:54 +00003585bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003586 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3587 auto *SU = dyn_cast<SCEVUnknown>(S);
3588 return SU && SU->getValue() == nullptr;
3589 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003590
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003591 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003592}
3593
Wei Mia49559b2016-02-04 01:27:38 +00003594bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003595 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003596 if (I != HasRecMap.end())
3597 return I->second;
3598
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003599 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003600 HasRecMap.insert({S, FoundAddRec});
3601 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003602}
3603
Wei Mi785858c2016-08-09 20:37:50 +00003604/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3605/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3606/// offset I, then return {S', I}, else return {\p S, nullptr}.
3607static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3608 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3609 if (!Add)
3610 return {S, nullptr};
3611
3612 if (Add->getNumOperands() != 2)
3613 return {S, nullptr};
3614
3615 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3616 if (!ConstOp)
3617 return {S, nullptr};
3618
3619 return {Add->getOperand(1), ConstOp->getValue()};
3620}
3621
3622/// Return the ValueOffsetPair set for \p S. \p S can be represented
3623/// by the value and offset from any ValueOffsetPair in the set.
3624SetVector<ScalarEvolution::ValueOffsetPair> *
3625ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003626 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3627 if (SI == ExprValueMap.end())
3628 return nullptr;
3629#ifndef NDEBUG
3630 if (VerifySCEVMap) {
3631 // Check there is no dangling Value in the set returned.
3632 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003633 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003634 }
3635#endif
3636 return &SI->second;
3637}
3638
Wei Mi785858c2016-08-09 20:37:50 +00003639/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3640/// cannot be used separately. eraseValueFromMap should be used to remove
3641/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003642void ScalarEvolution::eraseValueFromMap(Value *V) {
3643 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3644 if (I != ValueExprMap.end()) {
3645 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003646 // Remove {V, 0} from the set of ExprValueMap[S]
3647 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3648 SV->remove({V, nullptr});
3649
3650 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3651 const SCEV *Stripped;
3652 ConstantInt *Offset;
3653 std::tie(Stripped, Offset) = splitAddExpr(S);
3654 if (Offset != nullptr) {
3655 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3656 SV->remove({V, Offset});
3657 }
Wei Mia49559b2016-02-04 01:27:38 +00003658 ValueExprMap.erase(V);
3659 }
3660}
3661
Sanjoy Dasf8570812016-05-29 00:38:22 +00003662/// Return an existing SCEV if it exists, otherwise analyze the expression and
3663/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003664const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003665 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003666
Jingyue Wu42f1d672015-07-28 18:22:40 +00003667 const SCEV *S = getExistingSCEV(V);
3668 if (S == nullptr) {
3669 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003670 // During PHI resolution, it is possible to create two SCEVs for the same
3671 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003672 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003673 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003674 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003675 if (Pair.second) {
3676 ExprValueMap[S].insert({V, nullptr});
3677
3678 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3679 // ExprValueMap.
3680 const SCEV *Stripped = S;
3681 ConstantInt *Offset = nullptr;
3682 std::tie(Stripped, Offset) = splitAddExpr(S);
3683 // If stripped is SCEVUnknown, don't bother to save
3684 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3685 // increase the complexity of the expansion code.
3686 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3687 // because it may generate add/sub instead of GEP in SCEV expansion.
3688 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3689 !isa<GetElementPtrInst>(V))
3690 ExprValueMap[Stripped].insert({V, Offset});
3691 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003692 }
3693 return S;
3694}
3695
3696const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3697 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3698
Shuxin Yangefc4c012013-07-08 17:33:13 +00003699 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3700 if (I != ValueExprMap.end()) {
3701 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003702 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003703 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003704 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003705 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003706 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003707 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003708}
3709
Sanjoy Dasf8570812016-05-29 00:38:22 +00003710/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003711///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003712const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3713 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003714 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003715 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003716 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003717
Chris Lattner229907c2011-07-18 04:54:35 +00003718 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003719 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003720 return getMulExpr(
3721 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003722}
3723
Sanjoy Dasf8570812016-05-29 00:38:22 +00003724/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003725const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003726 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003727 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003728 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003729
Chris Lattner229907c2011-07-18 04:54:35 +00003730 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003731 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003732 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003733 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003734 return getMinusSCEV(AllOnes, V);
3735}
3736
Chris Lattnerfc877522011-01-09 22:26:35 +00003737const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Max Kazantsevdc803662017-06-15 11:48:21 +00003738 SCEV::NoWrapFlags Flags,
3739 unsigned Depth) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003740 // Fast path: X - X --> 0.
3741 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003742 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003743
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003744 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3745 // makes it so that we cannot make much use of NUW.
3746 auto AddFlags = SCEV::FlagAnyWrap;
3747 const bool RHSIsNotMinSigned =
Craig Topper01020392017-06-24 23:34:50 +00003748 !getSignedRangeMin(RHS).isMinSignedValue();
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003749 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3750 // Let M be the minimum representable signed value. Then (-1)*RHS
3751 // signed-wraps if and only if RHS is M. That can happen even for
3752 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3753 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3754 // (-1)*RHS, we need to prove that RHS != M.
3755 //
3756 // If LHS is non-negative and we know that LHS - RHS does not
3757 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3758 // either by proving that RHS > M or that LHS >= 0.
3759 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3760 AddFlags = SCEV::FlagNSW;
3761 }
3762 }
3763
3764 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3765 // RHS is NSW and LHS >= 0.
3766 //
3767 // The difficulty here is that the NSW flag may have been proven
3768 // relative to a loop that is to be found in a recurrence in LHS and
3769 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3770 // larger scope than intended.
3771 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3772
Max Kazantsevdc803662017-06-15 11:48:21 +00003773 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003774}
3775
Dan Gohmanaf752342009-07-07 17:06:11 +00003776const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003777ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3778 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003779 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3780 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003781 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003782 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003783 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003784 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003785 return getTruncateExpr(V, Ty);
3786 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003787}
3788
Dan Gohmanaf752342009-07-07 17:06:11 +00003789const SCEV *
3790ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003791 Type *Ty) {
3792 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003793 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3794 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003795 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003796 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003797 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003798 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003799 return getTruncateExpr(V, Ty);
3800 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003801}
3802
Dan Gohmanaf752342009-07-07 17:06:11 +00003803const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003804ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3805 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003806 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3807 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003808 "Cannot noop or zero extend with non-integer arguments!");
3809 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3810 "getNoopOrZeroExtend cannot truncate!");
3811 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3812 return V; // No conversion
3813 return getZeroExtendExpr(V, Ty);
3814}
3815
Dan Gohmanaf752342009-07-07 17:06:11 +00003816const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003817ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3818 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003819 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3820 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003821 "Cannot noop or sign extend with non-integer arguments!");
3822 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3823 "getNoopOrSignExtend cannot truncate!");
3824 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3825 return V; // No conversion
3826 return getSignExtendExpr(V, Ty);
3827}
3828
Dan Gohmanaf752342009-07-07 17:06:11 +00003829const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003830ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3831 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003832 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3833 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003834 "Cannot noop or any extend with non-integer arguments!");
3835 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3836 "getNoopOrAnyExtend cannot truncate!");
3837 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3838 return V; // No conversion
3839 return getAnyExtendExpr(V, Ty);
3840}
3841
Dan Gohmanaf752342009-07-07 17:06:11 +00003842const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003843ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3844 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003845 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3846 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003847 "Cannot truncate or noop with non-integer arguments!");
3848 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3849 "getTruncateOrNoop cannot extend!");
3850 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3851 return V; // No conversion
3852 return getTruncateExpr(V, Ty);
3853}
3854
Dan Gohmanabd17092009-06-24 14:49:00 +00003855const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3856 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003857 const SCEV *PromotedLHS = LHS;
3858 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003859
3860 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3861 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3862 else
3863 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3864
3865 return getUMaxExpr(PromotedLHS, PromotedRHS);
3866}
3867
Dan Gohmanabd17092009-06-24 14:49:00 +00003868const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3869 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003870 const SCEV *PromotedLHS = LHS;
3871 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003872
3873 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3874 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3875 else
3876 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3877
3878 return getUMinExpr(PromotedLHS, PromotedRHS);
3879}
3880
Andrew Trick87716c92011-03-17 23:51:11 +00003881const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3882 // A pointer operand may evaluate to a nonpointer expression, such as null.
3883 if (!V->getType()->isPointerTy())
3884 return V;
3885
3886 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3887 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003888 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003889 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003890 for (const SCEV *NAryOp : NAry->operands()) {
3891 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003892 // Cannot find the base of an expression with multiple pointer operands.
3893 if (PtrOp)
3894 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003895 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003896 }
3897 }
3898 if (!PtrOp)
3899 return V;
3900 return getPointerBase(PtrOp);
3901 }
3902 return V;
3903}
3904
Sanjoy Dasf8570812016-05-29 00:38:22 +00003905/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003906static void
3907PushDefUseChildren(Instruction *I,
3908 SmallVectorImpl<Instruction *> &Worklist) {
3909 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003910 for (User *U : I->users())
3911 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003912}
3913
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003914void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003915 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003916 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003917
Dan Gohman0b89dff2009-07-25 01:13:03 +00003918 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003919 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003920 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003921 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003922 if (!Visited.insert(I).second)
3923 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003924
Sanjoy Das63914592015-10-18 00:29:20 +00003925 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003926 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003927 const SCEV *Old = It->second;
3928
Dan Gohman0b89dff2009-07-25 01:13:03 +00003929 // Short-circuit the def-use traversal if the symbolic name
3930 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003931 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003932 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003933
Dan Gohman0b89dff2009-07-25 01:13:03 +00003934 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003935 // structure, it's a PHI that's in the progress of being computed
3936 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3937 // additional loop trip count information isn't going to change anything.
3938 // In the second case, createNodeForPHI will perform the necessary
3939 // updates on its own when it gets to that point. In the third, we do
3940 // want to forget the SCEVUnknown.
3941 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003942 !isa<SCEVUnknown>(Old) ||
3943 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003944 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003945 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003946 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003947 }
3948
3949 PushDefUseChildren(I, Worklist);
3950 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003951}
Chris Lattnerd934c702004-04-02 20:23:17 +00003952
Benjamin Kramer83709b12015-11-16 09:01:28 +00003953namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003954class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3955public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003956 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003957 ScalarEvolution &SE) {
3958 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003959 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003960 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3961 }
3962
3963 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3964 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3965
3966 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Max Kazantsev627ad0f2017-05-18 08:26:41 +00003967 if (!SE.isLoopInvariant(Expr, L))
Silviu Barangaf91c8072015-10-30 15:02:28 +00003968 Valid = false;
3969 return Expr;
3970 }
3971
3972 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3973 // Only allow AddRecExprs for this loop.
3974 if (Expr->getLoop() == L)
3975 return Expr->getStart();
3976 Valid = false;
3977 return Expr;
3978 }
3979
3980 bool isValid() { return Valid; }
3981
3982private:
3983 const Loop *L;
3984 bool Valid;
3985};
3986
3987class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3988public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003989 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003990 ScalarEvolution &SE) {
3991 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003992 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003993 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3994 }
3995
3996 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3997 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3998
3999 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4000 // Only allow AddRecExprs for this loop.
Max Kazantsev627ad0f2017-05-18 08:26:41 +00004001 if (!SE.isLoopInvariant(Expr, L))
Silviu Barangaf91c8072015-10-30 15:02:28 +00004002 Valid = false;
4003 return Expr;
4004 }
4005
4006 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4007 if (Expr->getLoop() == L && Expr->isAffine())
4008 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4009 Valid = false;
4010 return Expr;
4011 }
4012 bool isValid() { return Valid; }
4013
4014private:
4015 const Loop *L;
4016 bool Valid;
4017};
Benjamin Kramer83709b12015-11-16 09:01:28 +00004018} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00004019
Sanjoy Das724f5cf2016-03-03 18:31:29 +00004020SCEV::NoWrapFlags
4021ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4022 if (!AR->isAffine())
4023 return SCEV::FlagAnyWrap;
4024
4025 typedef OverflowingBinaryOperator OBO;
4026 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4027
4028 if (!AR->hasNoSignedWrap()) {
4029 ConstantRange AddRecRange = getSignedRange(AR);
4030 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4031
4032 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4033 Instruction::Add, IncRange, OBO::NoSignedWrap);
4034 if (NSWRegion.contains(AddRecRange))
4035 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4036 }
4037
4038 if (!AR->hasNoUnsignedWrap()) {
4039 ConstantRange AddRecRange = getUnsignedRange(AR);
4040 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4041
4042 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4043 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4044 if (NUWRegion.contains(AddRecRange))
4045 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4046 }
4047
4048 return Result;
4049}
4050
Sanjoy Das118d9192016-03-31 05:14:22 +00004051namespace {
4052/// Represents an abstract binary operation. This may exist as a
4053/// normal instruction or constant expression, or may have been
4054/// derived from an expression tree.
4055struct BinaryOp {
4056 unsigned Opcode;
4057 Value *LHS;
4058 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004059 bool IsNSW;
4060 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00004061
4062 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4063 /// constant expression.
4064 Operator *Op;
4065
4066 explicit BinaryOp(Operator *Op)
4067 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004068 IsNSW(false), IsNUW(false), Op(Op) {
4069 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4070 IsNSW = OBO->hasNoSignedWrap();
4071 IsNUW = OBO->hasNoUnsignedWrap();
4072 }
4073 }
Sanjoy Das118d9192016-03-31 05:14:22 +00004074
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004075 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4076 bool IsNUW = false)
4077 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4078 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00004079};
4080}
4081
4082
4083/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004084static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00004085 auto *Op = dyn_cast<Operator>(V);
4086 if (!Op)
4087 return None;
4088
4089 // Implementation detail: all the cleverness here should happen without
4090 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4091 // SCEV expressions when possible, and we should not break that.
4092
4093 switch (Op->getOpcode()) {
4094 case Instruction::Add:
4095 case Instruction::Sub:
4096 case Instruction::Mul:
4097 case Instruction::UDiv:
4098 case Instruction::And:
4099 case Instruction::Or:
4100 case Instruction::AShr:
4101 case Instruction::Shl:
4102 return BinaryOp(Op);
4103
4104 case Instruction::Xor:
4105 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
Craig Topperbcfd2d12017-04-20 16:56:25 +00004106 // If the RHS of the xor is a signmask, then this is just an add.
4107 // Instcombine turns add of signmask into xor as a strength reduction step.
4108 if (RHSC->getValue().isSignMask())
Sanjoy Das118d9192016-03-31 05:14:22 +00004109 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4110 return BinaryOp(Op);
4111
4112 case Instruction::LShr:
4113 // Turn logical shift right of a constant into a unsigned divide.
4114 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4115 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4116
4117 // If the shift count is not less than the bitwidth, the result of
4118 // the shift is undefined. Don't try to analyze it, because the
4119 // resolution chosen here may differ from the resolution chosen in
4120 // other parts of the compiler.
4121 if (SA->getValue().ult(BitWidth)) {
4122 Constant *X =
4123 ConstantInt::get(SA->getContext(),
4124 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4125 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4126 }
4127 }
4128 return BinaryOp(Op);
4129
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004130 case Instruction::ExtractValue: {
4131 auto *EVI = cast<ExtractValueInst>(Op);
4132 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4133 break;
4134
4135 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4136 if (!CI)
4137 break;
4138
4139 if (auto *F = CI->getCalledFunction())
4140 switch (F->getIntrinsicID()) {
4141 case Intrinsic::sadd_with_overflow:
4142 case Intrinsic::uadd_with_overflow: {
4143 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4144 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4145 CI->getArgOperand(1));
4146
4147 // Now that we know that all uses of the arithmetic-result component of
4148 // CI are guarded by the overflow check, we can go ahead and pretend
4149 // that the arithmetic is non-overflowing.
4150 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4151 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4152 CI->getArgOperand(1), /* IsNSW = */ true,
4153 /* IsNUW = */ false);
4154 else
4155 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4156 CI->getArgOperand(1), /* IsNSW = */ false,
4157 /* IsNUW*/ true);
4158 }
4159
4160 case Intrinsic::ssub_with_overflow:
4161 case Intrinsic::usub_with_overflow:
4162 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4163 CI->getArgOperand(1));
4164
4165 case Intrinsic::smul_with_overflow:
4166 case Intrinsic::umul_with_overflow:
4167 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4168 CI->getArgOperand(1));
4169 default:
4170 break;
4171 }
4172 }
4173
Sanjoy Das118d9192016-03-31 05:14:22 +00004174 default:
4175 break;
4176 }
4177
4178 return None;
4179}
4180
Michael Zolotukhin37162ad2017-05-03 23:53:38 +00004181/// A helper function for createAddRecFromPHI to handle simple cases.
4182///
4183/// This function tries to find an AddRec expression for the simplest (yet most
4184/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4185/// If it fails, createAddRecFromPHI will use a more general, but slow,
4186/// technique for finding the AddRec expression.
4187const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4188 Value *BEValueV,
4189 Value *StartValueV) {
4190 const Loop *L = LI.getLoopFor(PN->getParent());
4191 assert(L && L->getHeader() == PN->getParent());
4192 assert(BEValueV && StartValueV);
4193
4194 auto BO = MatchBinaryOp(BEValueV, DT);
4195 if (!BO)
4196 return nullptr;
4197
4198 if (BO->Opcode != Instruction::Add)
4199 return nullptr;
4200
4201 const SCEV *Accum = nullptr;
4202 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4203 Accum = getSCEV(BO->RHS);
4204 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4205 Accum = getSCEV(BO->LHS);
4206
4207 if (!Accum)
4208 return nullptr;
4209
4210 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4211 if (BO->IsNUW)
4212 Flags = setFlags(Flags, SCEV::FlagNUW);
4213 if (BO->IsNSW)
4214 Flags = setFlags(Flags, SCEV::FlagNSW);
4215
4216 const SCEV *StartVal = getSCEV(StartValueV);
4217 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4218
4219 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4220
4221 // We can add Flags to the post-inc expression only if we
Michael Zolotukhin3207d302017-05-04 17:42:34 +00004222 // know that it is *undefined behavior* for BEValueV to
Michael Zolotukhin37162ad2017-05-03 23:53:38 +00004223 // overflow.
4224 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4225 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4226 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4227
4228 return PHISCEV;
4229}
4230
Sanjoy Das55015d22015-10-02 23:09:44 +00004231const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4232 const Loop *L = LI.getLoopFor(PN->getParent());
4233 if (!L || L->getHeader() != PN->getParent())
4234 return nullptr;
4235
4236 // The loop may have multiple entrances or multiple exits; we can analyze
4237 // this phi as an addrec if it has a unique entry value and a unique
4238 // backedge value.
4239 Value *BEValueV = nullptr, *StartValueV = nullptr;
4240 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4241 Value *V = PN->getIncomingValue(i);
4242 if (L->contains(PN->getIncomingBlock(i))) {
4243 if (!BEValueV) {
4244 BEValueV = V;
4245 } else if (BEValueV != V) {
4246 BEValueV = nullptr;
4247 break;
4248 }
4249 } else if (!StartValueV) {
4250 StartValueV = V;
4251 } else if (StartValueV != V) {
4252 StartValueV = nullptr;
4253 break;
4254 }
4255 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004256 if (!BEValueV || !StartValueV)
4257 return nullptr;
Sanjoy Das55015d22015-10-02 23:09:44 +00004258
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004259 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4260 "PHI node already processed?");
Michael Zolotukhin37162ad2017-05-03 23:53:38 +00004261
4262 // First, try to find AddRec expression without creating a fictituos symbolic
4263 // value for PN.
4264 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4265 return S;
4266
4267 // Handle PHI node value symbolically.
4268 const SCEV *SymbolicName = getUnknown(PN);
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004269 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004270
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004271 // Using this symbolic name for the PHI, analyze the value coming around
4272 // the back-edge.
4273 const SCEV *BEValue = getSCEV(BEValueV);
Sanjoy Das55015d22015-10-02 23:09:44 +00004274
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004275 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4276 // has a special value for the first iteration of the loop.
4277
4278 // If the value coming around the backedge is an add with the symbolic
4279 // value we just inserted, then we found a simple induction variable!
4280 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4281 // If there is a single occurrence of the symbolic value, replace it
4282 // with a recurrence.
4283 unsigned FoundIndex = Add->getNumOperands();
4284 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4285 if (Add->getOperand(i) == SymbolicName)
4286 if (FoundIndex == e) {
4287 FoundIndex = i;
4288 break;
4289 }
4290
4291 if (FoundIndex != Add->getNumOperands()) {
4292 // Create an add with everything but the specified operand.
4293 SmallVector<const SCEV *, 8> Ops;
Sanjoy Das55015d22015-10-02 23:09:44 +00004294 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004295 if (i != FoundIndex)
4296 Ops.push_back(Add->getOperand(i));
4297 const SCEV *Accum = getAddExpr(Ops);
4298
4299 // This is not a valid addrec if the step amount is varying each
4300 // loop iteration, but is not itself an addrec in this loop.
4301 if (isLoopInvariant(Accum, L) ||
4302 (isa<SCEVAddRecExpr>(Accum) &&
4303 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4304 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4305
4306 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4307 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4308 if (BO->IsNUW)
4309 Flags = setFlags(Flags, SCEV::FlagNUW);
4310 if (BO->IsNSW)
4311 Flags = setFlags(Flags, SCEV::FlagNSW);
4312 }
4313 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4314 // If the increment is an inbounds GEP, then we know the address
4315 // space cannot be wrapped around. We cannot make any guarantee
4316 // about signed or unsigned overflow because pointers are
4317 // unsigned but we may have a negative index from the base
4318 // pointer. We can guarantee that no unsigned wrap occurs if the
4319 // indices form a positive value.
4320 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4321 Flags = setFlags(Flags, SCEV::FlagNW);
4322
4323 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4324 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4325 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohman6635bb22010-04-12 07:49:36 +00004326 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004327
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004328 // We cannot transfer nuw and nsw flags from subtraction
4329 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4330 // for instance.
Dan Gohman6635bb22010-04-12 07:49:36 +00004331 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004332
Sanjoy Das55015d22015-10-02 23:09:44 +00004333 const SCEV *StartVal = getSCEV(StartValueV);
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004334 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4335
4336 // Okay, for the entire analysis of this edge we assumed the PHI
4337 // to be symbolic. We now need to go back and purge all of the
4338 // entries for the scalars that use the symbolic expression.
4339 forgetSymbolicName(PN, SymbolicName);
4340 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4341
4342 // We can add Flags to the post-inc expression only if we
Michael Zolotukhin3207d302017-05-04 17:42:34 +00004343 // know that it is *undefined behavior* for BEValueV to
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004344 // overflow.
4345 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4346 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4347 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4348
4349 return PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00004350 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004351 }
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004352 } else {
4353 // Otherwise, this could be a loop like this:
4354 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4355 // In this case, j = {1,+,1} and BEValue is j.
4356 // Because the other in-value of i (0) fits the evolution of BEValue
4357 // i really is an addrec evolution.
4358 //
4359 // We can generalize this saying that i is the shifted value of BEValue
4360 // by one iteration:
4361 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4362 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4363 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4364 if (Shifted != getCouldNotCompute() &&
4365 Start != getCouldNotCompute()) {
4366 const SCEV *StartVal = getSCEV(StartValueV);
4367 if (Start == StartVal) {
4368 // Okay, for the entire analysis of this edge we assumed the PHI
4369 // to be symbolic. We now need to go back and purge all of the
4370 // entries for the scalars that use the symbolic expression.
4371 forgetSymbolicName(PN, SymbolicName);
4372 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4373 return Shifted;
4374 }
4375 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004376 }
4377
Michael Zolotukhin146a2212017-04-28 22:14:27 +00004378 // Remove the temporary PHI node SCEV that has been inserted while intending
4379 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4380 // as it will prevent later (possibly simpler) SCEV expressions to be added
4381 // to the ValueExprMap.
4382 eraseValueFromMap(PN);
4383
Sanjoy Das55015d22015-10-02 23:09:44 +00004384 return nullptr;
4385}
4386
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004387// Checks if the SCEV S is available at BB. S is considered available at BB
4388// if S can be materialized at BB without introducing a fault.
4389static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4390 BasicBlock *BB) {
4391 struct CheckAvailable {
4392 bool TraversalDone = false;
4393 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004394
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004395 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4396 BasicBlock *BB = nullptr;
4397 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004398
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004399 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4400 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004401
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004402 bool setUnavailable() {
4403 TraversalDone = true;
4404 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004405 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004406 }
4407
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004408 bool follow(const SCEV *S) {
4409 switch (S->getSCEVType()) {
4410 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4411 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004412 // These expressions are available if their operand(s) is/are.
4413 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004414
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004415 case scAddRecExpr: {
4416 // We allow add recurrences that are on the loop BB is in, or some
4417 // outer loop. This guarantees availability because the value of the
4418 // add recurrence at BB is simply the "current" value of the induction
4419 // variable. We can relax this in the future; for instance an add
4420 // recurrence on a sibling dominating loop is also available at BB.
4421 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4422 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004423 return true;
4424
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004425 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004426 }
4427
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004428 case scUnknown: {
4429 // For SCEVUnknown, we check for simple dominance.
4430 const auto *SU = cast<SCEVUnknown>(S);
4431 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004432
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004433 if (isa<Argument>(V))
4434 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004435
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004436 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4437 return false;
4438
4439 return setUnavailable();
4440 }
4441
4442 case scUDivExpr:
4443 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004444 // We do not try to smart about these at all.
4445 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004446 }
4447 llvm_unreachable("switch should be fully covered!");
4448 }
4449
4450 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004451 };
4452
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004453 CheckAvailable CA(L, BB, DT);
4454 SCEVTraversal<CheckAvailable> ST(CA);
4455
4456 ST.visitAll(S);
4457 return CA.Available;
4458}
4459
4460// Try to match a control flow sequence that branches out at BI and merges back
4461// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4462// match.
4463static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4464 Value *&C, Value *&LHS, Value *&RHS) {
4465 C = BI->getCondition();
4466
4467 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4468 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4469
4470 if (!LeftEdge.isSingleEdge())
4471 return false;
4472
4473 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4474
4475 Use &LeftUse = Merge->getOperandUse(0);
4476 Use &RightUse = Merge->getOperandUse(1);
4477
4478 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4479 LHS = LeftUse;
4480 RHS = RightUse;
4481 return true;
4482 }
4483
4484 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4485 LHS = RightUse;
4486 RHS = LeftUse;
4487 return true;
4488 }
4489
4490 return false;
4491}
4492
4493const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004494 auto IsReachable =
4495 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4496 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004497 const Loop *L = LI.getLoopFor(PN->getParent());
4498
Sanjoy Das337d4782015-10-31 23:21:40 +00004499 // We don't want to break LCSSA, even in a SCEV expression tree.
4500 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4501 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4502 return nullptr;
4503
Sanjoy Das55015d22015-10-02 23:09:44 +00004504 // Try to match
4505 //
4506 // br %cond, label %left, label %right
4507 // left:
4508 // br label %merge
4509 // right:
4510 // br label %merge
4511 // merge:
4512 // V = phi [ %x, %left ], [ %y, %right ]
4513 //
4514 // as "select %cond, %x, %y"
4515
4516 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4517 assert(IDom && "At least the entry block should dominate PN");
4518
4519 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4520 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4521
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004522 if (BI && BI->isConditional() &&
4523 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4524 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4525 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004526 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4527 }
4528
4529 return nullptr;
4530}
4531
4532const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4533 if (const SCEV *S = createAddRecFromPHI(PN))
4534 return S;
4535
4536 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4537 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004538
Dan Gohmana9c205c2010-02-25 06:57:05 +00004539 // If the PHI has a single incoming value, follow that value, unless the
4540 // PHI's incoming blocks are in a different loop, in which case doing so
4541 // risks breaking LCSSA form. Instcombine would normally zap these, but
4542 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00004543 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004544 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004545 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004546
Chris Lattnerd934c702004-04-02 20:23:17 +00004547 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004548 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004549}
4550
Sanjoy Das55015d22015-10-02 23:09:44 +00004551const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4552 Value *Cond,
4553 Value *TrueVal,
4554 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004555 // Handle "constant" branch or select. This can occur for instance when a
4556 // loop pass transforms an inner loop and moves on to process the outer loop.
4557 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4558 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4559
Sanjoy Dasd0671342015-10-02 19:39:59 +00004560 // Try to match some simple smax or umax patterns.
4561 auto *ICI = dyn_cast<ICmpInst>(Cond);
4562 if (!ICI)
4563 return getUnknown(I);
4564
4565 Value *LHS = ICI->getOperand(0);
4566 Value *RHS = ICI->getOperand(1);
4567
4568 switch (ICI->getPredicate()) {
4569 case ICmpInst::ICMP_SLT:
4570 case ICmpInst::ICMP_SLE:
4571 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004572 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004573 case ICmpInst::ICMP_SGT:
4574 case ICmpInst::ICMP_SGE:
4575 // a >s b ? a+x : b+x -> smax(a, b)+x
4576 // a >s b ? b+x : a+x -> smin(a, b)+x
4577 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4578 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4579 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4580 const SCEV *LA = getSCEV(TrueVal);
4581 const SCEV *RA = getSCEV(FalseVal);
4582 const SCEV *LDiff = getMinusSCEV(LA, LS);
4583 const SCEV *RDiff = getMinusSCEV(RA, RS);
4584 if (LDiff == RDiff)
4585 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4586 LDiff = getMinusSCEV(LA, RS);
4587 RDiff = getMinusSCEV(RA, LS);
4588 if (LDiff == RDiff)
4589 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4590 }
4591 break;
4592 case ICmpInst::ICMP_ULT:
4593 case ICmpInst::ICMP_ULE:
4594 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004595 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004596 case ICmpInst::ICMP_UGT:
4597 case ICmpInst::ICMP_UGE:
4598 // a >u b ? a+x : b+x -> umax(a, b)+x
4599 // a >u b ? b+x : a+x -> umin(a, b)+x
4600 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4601 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4602 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4603 const SCEV *LA = getSCEV(TrueVal);
4604 const SCEV *RA = getSCEV(FalseVal);
4605 const SCEV *LDiff = getMinusSCEV(LA, LS);
4606 const SCEV *RDiff = getMinusSCEV(RA, RS);
4607 if (LDiff == RDiff)
4608 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4609 LDiff = getMinusSCEV(LA, RS);
4610 RDiff = getMinusSCEV(RA, LS);
4611 if (LDiff == RDiff)
4612 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4613 }
4614 break;
4615 case ICmpInst::ICMP_NE:
4616 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4617 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4618 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4619 const SCEV *One = getOne(I->getType());
4620 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4621 const SCEV *LA = getSCEV(TrueVal);
4622 const SCEV *RA = getSCEV(FalseVal);
4623 const SCEV *LDiff = getMinusSCEV(LA, LS);
4624 const SCEV *RDiff = getMinusSCEV(RA, One);
4625 if (LDiff == RDiff)
4626 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4627 }
4628 break;
4629 case ICmpInst::ICMP_EQ:
4630 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4631 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4632 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4633 const SCEV *One = getOne(I->getType());
4634 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4635 const SCEV *LA = getSCEV(TrueVal);
4636 const SCEV *RA = getSCEV(FalseVal);
4637 const SCEV *LDiff = getMinusSCEV(LA, One);
4638 const SCEV *RDiff = getMinusSCEV(RA, LS);
4639 if (LDiff == RDiff)
4640 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4641 }
4642 break;
4643 default:
4644 break;
4645 }
4646
4647 return getUnknown(I);
4648}
4649
Sanjoy Dasf8570812016-05-29 00:38:22 +00004650/// Expand GEP instructions into add and multiply operations. This allows them
4651/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004652const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004653 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004654 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004655 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004656
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004657 SmallVector<const SCEV *, 4> IndexExprs;
4658 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4659 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004660 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004661}
4662
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004663uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004664 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004665 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004666
Dan Gohmana30370b2009-05-04 22:02:23 +00004667 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004668 return std::min(GetMinTrailingZeros(T->getOperand()),
4669 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004670
Dan Gohmana30370b2009-05-04 22:02:23 +00004671 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004672 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004673 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4674 ? getTypeSizeInBits(E->getType())
4675 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004676 }
4677
Dan Gohmana30370b2009-05-04 22:02:23 +00004678 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004679 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004680 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4681 ? getTypeSizeInBits(E->getType())
4682 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004683 }
4684
Dan Gohmana30370b2009-05-04 22:02:23 +00004685 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004686 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004687 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004688 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004689 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004690 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004691 }
4692
Dan Gohmana30370b2009-05-04 22:02:23 +00004693 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004694 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004695 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4696 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004697 for (unsigned i = 1, e = M->getNumOperands();
4698 SumOpRes != BitWidth && i != e; ++i)
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004699 SumOpRes =
4700 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
Nick Lewycky3783b462007-11-22 07:59:40 +00004701 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004702 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004703
Dan Gohmana30370b2009-05-04 22:02:23 +00004704 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004705 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004706 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004707 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004708 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004709 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004710 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004711
Dan Gohmana30370b2009-05-04 22:02:23 +00004712 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004713 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004714 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004715 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004716 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004717 return MinOpRes;
4718 }
4719
Dan Gohmana30370b2009-05-04 22:02:23 +00004720 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004721 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004722 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004723 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004724 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004725 return MinOpRes;
4726 }
4727
Dan Gohmanc702fc02009-06-19 23:29:04 +00004728 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4729 // For a SCEVUnknown, ask ValueTracking.
Craig Topper8205a1a2017-05-24 16:53:07 +00004730 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
Craig Topper8df66c62017-05-12 17:20:30 +00004731 return Known.countMinTrailingZeros();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004732 }
4733
4734 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004735 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004736}
Chris Lattnerd934c702004-04-02 20:23:17 +00004737
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004738uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4739 auto I = MinTrailingZerosCache.find(S);
4740 if (I != MinTrailingZerosCache.end())
4741 return I->second;
4742
4743 uint32_t Result = GetMinTrailingZerosImpl(S);
4744 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4745 assert(InsertPair.second && "Should insert a new key");
4746 return InsertPair.first->second;
4747}
4748
Sanjoy Dasf8570812016-05-29 00:38:22 +00004749/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004750static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004751 if (Instruction *I = dyn_cast<Instruction>(V))
4752 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4753 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004754
4755 return None;
4756}
4757
Sanjoy Dasf8570812016-05-29 00:38:22 +00004758/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004759/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4760/// with a "cleaner" unsigned (resp. signed) representation.
Craig Topper01020392017-06-24 23:34:50 +00004761const ConstantRange &
4762ScalarEvolution::getRangeRef(const SCEV *S,
4763 ScalarEvolution::RangeSignHint SignHint) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004764 DenseMap<const SCEV *, ConstantRange> &Cache =
4765 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4766 : SignedRanges;
4767
Dan Gohman761065e2010-11-17 02:44:44 +00004768 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004769 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4770 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004771 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004772
4773 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004774 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004775
Dan Gohman85be4332010-01-26 19:19:05 +00004776 unsigned BitWidth = getTypeSizeInBits(S->getType());
4777 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4778
Sanjoy Das91b54772015-03-09 21:43:43 +00004779 // If the value has known zeros, the maximum value will have those known zeros
4780 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004781 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004782 if (TZ != 0) {
4783 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4784 ConservativeResult =
4785 ConstantRange(APInt::getMinValue(BitWidth),
4786 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4787 else
4788 ConservativeResult = ConstantRange(
4789 APInt::getSignedMinValue(BitWidth),
4790 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4791 }
Dan Gohman85be4332010-01-26 19:19:05 +00004792
Dan Gohmane65c9172009-07-13 21:35:55 +00004793 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004794 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004795 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Craig Topper01020392017-06-24 23:34:50 +00004796 X = X.add(getRangeRef(Add->getOperand(i), SignHint));
Sanjoy Das91b54772015-03-09 21:43:43 +00004797 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004798 }
4799
4800 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004801 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004802 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Craig Topper01020392017-06-24 23:34:50 +00004803 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
Sanjoy Das91b54772015-03-09 21:43:43 +00004804 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004805 }
4806
4807 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004808 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004809 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Craig Topper01020392017-06-24 23:34:50 +00004810 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
Sanjoy Das91b54772015-03-09 21:43:43 +00004811 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004812 }
4813
4814 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004815 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004816 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Craig Topper01020392017-06-24 23:34:50 +00004817 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
Sanjoy Das91b54772015-03-09 21:43:43 +00004818 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004819 }
4820
4821 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004822 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
4823 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
Sanjoy Das91b54772015-03-09 21:43:43 +00004824 return setRange(UDiv, SignHint,
4825 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004826 }
4827
4828 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004829 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
Sanjoy Das91b54772015-03-09 21:43:43 +00004830 return setRange(ZExt, SignHint,
4831 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004832 }
4833
4834 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004835 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
Sanjoy Das91b54772015-03-09 21:43:43 +00004836 return setRange(SExt, SignHint,
4837 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004838 }
4839
4840 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Craig Topper01020392017-06-24 23:34:50 +00004841 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
Sanjoy Das91b54772015-03-09 21:43:43 +00004842 return setRange(Trunc, SignHint,
4843 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004844 }
4845
Dan Gohmane65c9172009-07-13 21:35:55 +00004846 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004847 // If there's no unsigned wrap, the value will never be less than its
4848 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004849 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004850 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004851 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004852 ConservativeResult = ConservativeResult.intersectWith(
4853 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004854
Dan Gohman51ad99d2010-01-21 02:09:26 +00004855 // If there's no signed wrap, and all the operands have the same sign or
4856 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004857 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004858 bool AllNonNeg = true;
4859 bool AllNonPos = true;
4860 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4861 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4862 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4863 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004864 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004865 ConservativeResult = ConservativeResult.intersectWith(
4866 ConstantRange(APInt(BitWidth, 0),
4867 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004868 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004869 ConservativeResult = ConservativeResult.intersectWith(
4870 ConstantRange(APInt::getSignedMinValue(BitWidth),
4871 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004872 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004873
4874 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004875 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004876 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004877 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4878 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004879 auto RangeFromAffine = getRangeForAffineAR(
4880 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4881 BitWidth);
4882 if (!RangeFromAffine.isFullSet())
4883 ConservativeResult =
4884 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004885
4886 auto RangeFromFactoring = getRangeViaFactoring(
4887 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4888 BitWidth);
4889 if (!RangeFromFactoring.isFullSet())
4890 ConservativeResult =
4891 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004892 }
Dan Gohmand261d272009-06-24 01:05:09 +00004893 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004894
Craig Topper252682a2017-05-07 16:28:17 +00004895 return setRange(AddRec, SignHint, std::move(ConservativeResult));
Dan Gohmand261d272009-06-24 01:05:09 +00004896 }
4897
Dan Gohmanc702fc02009-06-19 23:29:04 +00004898 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004899 // Check if the IR explicitly contains !range metadata.
4900 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4901 if (MDRange.hasValue())
4902 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4903
Sanjoy Das91b54772015-03-09 21:43:43 +00004904 // Split here to avoid paying the compile-time cost of calling both
4905 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4906 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004907 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004908 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4909 // For a SCEVUnknown, ask ValueTracking.
Craig Topper8205a1a2017-05-24 16:53:07 +00004910 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Craig Topperb45eabc2017-04-26 16:39:58 +00004911 if (Known.One != ~Known.Zero + 1)
Sanjoy Das91b54772015-03-09 21:43:43 +00004912 ConservativeResult =
Craig Topperb45eabc2017-04-26 16:39:58 +00004913 ConservativeResult.intersectWith(ConstantRange(Known.One,
4914 ~Known.Zero + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004915 } else {
4916 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4917 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004918 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004919 if (NS > 1)
4920 ConservativeResult = ConservativeResult.intersectWith(
4921 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4922 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004923 }
4924
Craig Topper252682a2017-05-07 16:28:17 +00004925 return setRange(U, SignHint, std::move(ConservativeResult));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004926 }
4927
Craig Topper252682a2017-05-07 16:28:17 +00004928 return setRange(S, SignHint, std::move(ConservativeResult));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004929}
4930
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004931// Given a StartRange, Step and MaxBECount for an expression compute a range of
4932// values that the expression can take. Initially, the expression has a value
4933// from StartRange and then is changed by Step up to MaxBECount times. Signed
4934// argument defines if we treat Step as signed or unsigned.
4935static ConstantRange getRangeForAffineARHelper(APInt Step,
Craig Topperd6f26392017-05-08 02:29:15 +00004936 const ConstantRange &StartRange,
Craig Topper6c5e22a2017-05-06 06:03:07 +00004937 const APInt &MaxBECount,
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004938 unsigned BitWidth, bool Signed) {
4939 // If either Step or MaxBECount is 0, then the expression won't change, and we
4940 // just need to return the initial range.
4941 if (Step == 0 || MaxBECount == 0)
4942 return StartRange;
4943
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00004944 // If we don't know anything about the initial value (i.e. StartRange is
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004945 // FullRange), then we don't know anything about the final range either.
4946 // Return FullRange.
4947 if (StartRange.isFullSet())
4948 return ConstantRange(BitWidth, /* isFullSet = */ true);
4949
4950 // If Step is signed and negative, then we use its absolute value, but we also
4951 // note that we're moving in the opposite direction.
4952 bool Descending = Signed && Step.isNegative();
4953
4954 if (Signed)
4955 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4956 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4957 // This equations hold true due to the well-defined wrap-around behavior of
4958 // APInt.
4959 Step = Step.abs();
4960
4961 // Check if Offset is more than full span of BitWidth. If it is, the
4962 // expression is guaranteed to overflow.
4963 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4964 return ConstantRange(BitWidth, /* isFullSet = */ true);
4965
4966 // Offset is by how much the expression can change. Checks above guarantee no
4967 // overflow here.
4968 APInt Offset = Step * MaxBECount;
4969
4970 // Minimum value of the final range will match the minimal value of StartRange
4971 // if the expression is increasing and will be decreased by Offset otherwise.
4972 // Maximum value of the final range will match the maximal value of StartRange
4973 // if the expression is decreasing and will be increased by Offset otherwise.
4974 APInt StartLower = StartRange.getLower();
4975 APInt StartUpper = StartRange.getUpper() - 1;
Craig Topper6c5e22a2017-05-06 06:03:07 +00004976 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
4977 : (StartUpper + std::move(Offset));
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004978
4979 // It's possible that the new minimum/maximum value will fall into the initial
4980 // range (due to wrap around). This means that the expression can take any
4981 // value in this bitwidth, and we have to return full range.
4982 if (StartRange.contains(MovedBoundary))
4983 return ConstantRange(BitWidth, /* isFullSet = */ true);
4984
Craig Topper6c5e22a2017-05-06 06:03:07 +00004985 APInt NewLower =
4986 Descending ? std::move(MovedBoundary) : std::move(StartLower);
4987 APInt NewUpper =
4988 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
4989 NewUpper += 1;
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004990
4991 // If we end up with full range, return a proper full range.
Craig Topper6c5e22a2017-05-06 06:03:07 +00004992 if (NewLower == NewUpper)
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004993 return ConstantRange(BitWidth, /* isFullSet = */ true);
4994
4995 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
Craig Topper6c5e22a2017-05-06 06:03:07 +00004996 return ConstantRange(std::move(NewLower), std::move(NewUpper));
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004997}
4998
Sanjoy Dasb765b632016-03-02 00:57:39 +00004999ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5000 const SCEV *Step,
5001 const SCEV *MaxBECount,
5002 unsigned BitWidth) {
5003 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5004 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5005 "Precondition!");
5006
Sanjoy Dasb765b632016-03-02 00:57:39 +00005007 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
Craig Topper01020392017-06-24 23:34:50 +00005008 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
Sanjoy Dasb765b632016-03-02 00:57:39 +00005009
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00005010 // First, consider step signed.
Sanjoy Dasb765b632016-03-02 00:57:39 +00005011 ConstantRange StartSRange = getSignedRange(Start);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00005012 ConstantRange StepSRange = getSignedRange(Step);
Sanjoy Dasb765b632016-03-02 00:57:39 +00005013
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00005014 // If Step can be both positive and negative, we need to find ranges for the
5015 // maximum absolute step values in both directions and union them.
5016 ConstantRange SR =
5017 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5018 MaxBECountValue, BitWidth, /* Signed = */ true);
5019 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5020 StartSRange, MaxBECountValue,
5021 BitWidth, /* Signed = */ true));
Sanjoy Dasb765b632016-03-02 00:57:39 +00005022
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00005023 // Next, consider step unsigned.
5024 ConstantRange UR = getRangeForAffineARHelper(
Craig Topper01020392017-06-24 23:34:50 +00005025 getUnsignedRangeMax(Step), getUnsignedRange(Start),
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00005026 MaxBECountValue, BitWidth, /* Signed = */ false);
5027
5028 // Finally, intersect signed and unsigned ranges.
5029 return SR.intersectWith(UR);
Sanjoy Dasb765b632016-03-02 00:57:39 +00005030}
5031
Sanjoy Dasbf730982016-03-02 00:57:54 +00005032ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5033 const SCEV *Step,
5034 const SCEV *MaxBECount,
5035 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00005036 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5037 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5038
5039 struct SelectPattern {
5040 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005041 APInt TrueValue;
5042 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00005043
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005044 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5045 const SCEV *S) {
5046 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00005047 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005048
5049 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5050 "Should be!");
5051
Sanjoy Das97d19bd2016-03-09 01:51:02 +00005052 // Peel off a constant offset:
5053 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5054 // In the future we could consider being smarter here and handle
5055 // {Start+Step,+,Step} too.
5056 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5057 return;
5058
5059 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5060 S = SA->getOperand(1);
5061 }
5062
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005063 // Peel off a cast operation
5064 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5065 CastOp = SCast->getSCEVType();
5066 S = SCast->getOperand();
5067 }
5068
Sanjoy Dasbf730982016-03-02 00:57:54 +00005069 using namespace llvm::PatternMatch;
5070
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005071 auto *SU = dyn_cast<SCEVUnknown>(S);
5072 const APInt *TrueVal, *FalseVal;
5073 if (!SU ||
5074 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5075 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00005076 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005077 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00005078 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005079
5080 TrueValue = *TrueVal;
5081 FalseValue = *FalseVal;
5082
5083 // Re-apply the cast we peeled off earlier
5084 if (CastOp.hasValue())
5085 switch (*CastOp) {
5086 default:
5087 llvm_unreachable("Unknown SCEV cast type!");
5088
5089 case scTruncate:
5090 TrueValue = TrueValue.trunc(BitWidth);
5091 FalseValue = FalseValue.trunc(BitWidth);
5092 break;
5093 case scZeroExtend:
5094 TrueValue = TrueValue.zext(BitWidth);
5095 FalseValue = FalseValue.zext(BitWidth);
5096 break;
5097 case scSignExtend:
5098 TrueValue = TrueValue.sext(BitWidth);
5099 FalseValue = FalseValue.sext(BitWidth);
5100 break;
5101 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00005102
5103 // Re-apply the constant offset we peeled off earlier
5104 TrueValue += Offset;
5105 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00005106 }
5107
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005108 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00005109 };
5110
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005111 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00005112 if (!StartPattern.isRecognized())
5113 return ConstantRange(BitWidth, /* isFullSet = */ true);
5114
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005115 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00005116 if (!StepPattern.isRecognized())
5117 return ConstantRange(BitWidth, /* isFullSet = */ true);
5118
5119 if (StartPattern.Condition != StepPattern.Condition) {
5120 // We don't handle this case today; but we could, by considering four
5121 // possibilities below instead of two. I'm not sure if there are cases where
5122 // that will help over what getRange already does, though.
5123 return ConstantRange(BitWidth, /* isFullSet = */ true);
5124 }
5125
5126 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5127 // construct arbitrary general SCEV expressions here. This function is called
5128 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5129 // say) can end up caching a suboptimal value.
5130
Sanjoy Das6b017a12016-03-02 02:56:29 +00005131 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5132 // C2352 and C2512 (otherwise it isn't needed).
5133
Sanjoy Das97d19bd2016-03-09 01:51:02 +00005134 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005135 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00005136 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00005137 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00005138
Sanjoy Das1168f932016-03-02 02:34:20 +00005139 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00005140 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00005141 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00005142 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00005143
5144 return TrueRange.unionWith(FalseRange);
5145}
5146
Jingyue Wu42f1d672015-07-28 18:22:40 +00005147SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005148 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005149 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5150
5151 // Return early if there are no flags to propagate to the SCEV.
5152 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5153 if (BinOp->hasNoUnsignedWrap())
5154 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5155 if (BinOp->hasNoSignedWrap())
5156 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00005157 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00005158 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005159
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005160 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5161}
5162
5163bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5164 // Here we check that I is in the header of the innermost loop containing I,
5165 // since we only deal with instructions in the loop header. The actual loop we
5166 // need to check later will come from an add recurrence, but getting that
5167 // requires computing the SCEV of the operands, which can be expensive. This
5168 // check we can do cheaply to rule out some cases early.
5169 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00005170 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005171 InnermostContainingLoop->getHeader() != I->getParent())
5172 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005173
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005174 // Only proceed if we can prove that I does not yield poison.
Sanjoy Das08989c72017-04-30 19:41:19 +00005175 if (!programUndefinedIfFullPoison(I))
5176 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005177
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005178 // At this point we know that if I is executed, then it does not wrap
5179 // according to at least one of NSW or NUW. If I is not executed, then we do
5180 // not know if the calculation that I represents would wrap. Multiple
5181 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00005182 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5183 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005184 // that guarantee for cases where I is not executed. So we need to find the
5185 // loop that I is considered in relation to and prove that I is executed for
5186 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00005187 // calculates does not wrap anywhere in the loop, so then we can apply the
5188 // flags to the SCEV.
5189 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005190 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5191 // from different loops, so that we know which loop to prove that I is
5192 // executed in.
5193 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00005194 // I could be an extractvalue from a call to an overflow intrinsic.
5195 // TODO: We can do better here in some cases.
5196 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5197 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005198 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00005199 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005200 bool AllOtherOpsLoopInvariant = true;
5201 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5202 ++OtherOpIndex) {
5203 if (OtherOpIndex != OpIndex) {
5204 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5205 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5206 AllOtherOpsLoopInvariant = false;
5207 break;
5208 }
5209 }
5210 }
5211 if (AllOtherOpsLoopInvariant &&
5212 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5213 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005214 }
5215 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005216 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005217}
5218
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005219bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5220 // If we know that \c I can never be poison period, then that's enough.
5221 if (isSCEVExprNeverPoison(I))
5222 return true;
5223
5224 // For an add recurrence specifically, we assume that infinite loops without
5225 // side effects are undefined behavior, and then reason as follows:
5226 //
5227 // If the add recurrence is poison in any iteration, it is poison on all
5228 // future iterations (since incrementing poison yields poison). If the result
5229 // of the add recurrence is fed into the loop latch condition and the loop
5230 // does not contain any throws or exiting blocks other than the latch, we now
5231 // have the ability to "choose" whether the backedge is taken or not (by
5232 // choosing a sufficiently evil value for the poison feeding into the branch)
5233 // for every iteration including and after the one in which \p I first became
5234 // poison. There are two possibilities (let's call the iteration in which \p
5235 // I first became poison as K):
5236 //
5237 // 1. In the set of iterations including and after K, the loop body executes
5238 // no side effects. In this case executing the backege an infinte number
5239 // of times will yield undefined behavior.
5240 //
5241 // 2. In the set of iterations including and after K, the loop body executes
5242 // at least one side effect. In this case, that specific instance of side
5243 // effect is control dependent on poison, which also yields undefined
5244 // behavior.
5245
5246 auto *ExitingBB = L->getExitingBlock();
5247 auto *LatchBB = L->getLoopLatch();
5248 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5249 return false;
5250
5251 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005252 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005253
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005254 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5255 // things that are known to be fully poison under that assumption go on the
5256 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005257 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005258 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005259
5260 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00005261 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005262 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005263
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005264 for (auto *PoisonUser : Poison->users()) {
5265 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5266 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5267 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5268 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005269 assert(BI->isConditional() && "Only possibility!");
5270 if (BI->getParent() == LatchBB) {
5271 LatchControlDependentOnPoison = true;
5272 break;
5273 }
5274 }
5275 }
5276 }
5277
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005278 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5279}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005280
Sanjoy Das5603fc02016-09-26 02:44:07 +00005281ScalarEvolution::LoopProperties
5282ScalarEvolution::getLoopProperties(const Loop *L) {
5283 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005284
Sanjoy Das5603fc02016-09-26 02:44:07 +00005285 auto Itr = LoopPropertiesCache.find(L);
5286 if (Itr == LoopPropertiesCache.end()) {
5287 auto HasSideEffects = [](Instruction *I) {
5288 if (auto *SI = dyn_cast<StoreInst>(I))
5289 return !SI->isSimple();
5290
5291 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005292 };
5293
Sanjoy Das5603fc02016-09-26 02:44:07 +00005294 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5295 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005296
Sanjoy Das5603fc02016-09-26 02:44:07 +00005297 for (auto *BB : L->getBlocks())
5298 for (auto &I : *BB) {
5299 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5300 LP.HasNoAbnormalExits = false;
5301 if (HasSideEffects(&I))
5302 LP.HasNoSideEffects = false;
5303 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5304 break; // We're already as pessimistic as we can get.
5305 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005306
Sanjoy Das5603fc02016-09-26 02:44:07 +00005307 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005308 assert(InsertPair.second && "We just checked!");
5309 Itr = InsertPair.first;
5310 }
5311
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005312 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005313}
5314
Dan Gohmanaf752342009-07-07 17:06:11 +00005315const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005316 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005317 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005318
Dan Gohman69451a02010-03-09 23:46:50 +00005319 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005320 // Don't attempt to analyze instructions in blocks that aren't
5321 // reachable. Such instructions don't matter, and they aren't required
5322 // to obey basic rules for definitions dominating uses which this
5323 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005324 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005325 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005326 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005327 return getConstant(CI);
5328 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005329 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005330 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005331 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005332 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005333 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005334
Dan Gohman80ca01c2009-07-17 20:47:02 +00005335 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005336 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005337 switch (BO->Opcode) {
5338 case Instruction::Add: {
5339 // The simple thing to do would be to just call getSCEV on both operands
5340 // and call getAddExpr with the result. However if we're looking at a
5341 // bunch of things all added together, this can be quite inefficient,
5342 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5343 // Instead, gather up all the operands and make a single getAddExpr call.
5344 // LLVM IR canonical form means we need only traverse the left operands.
5345 SmallVector<const SCEV *, 4> AddOps;
5346 do {
5347 if (BO->Op) {
5348 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5349 AddOps.push_back(OpSCEV);
5350 break;
5351 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005352
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005353 // If a NUW or NSW flag can be applied to the SCEV for this
5354 // addition, then compute the SCEV for this addition by itself
5355 // with a separate call to getAddExpr. We need to do that
5356 // instead of pushing the operands of the addition onto AddOps,
5357 // since the flags are only known to apply to this particular
5358 // addition - they may not apply to other additions that can be
5359 // formed with operands from AddOps.
5360 const SCEV *RHS = getSCEV(BO->RHS);
5361 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5362 if (Flags != SCEV::FlagAnyWrap) {
5363 const SCEV *LHS = getSCEV(BO->LHS);
5364 if (BO->Opcode == Instruction::Sub)
5365 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5366 else
5367 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5368 break;
5369 }
Dan Gohman36bad002009-09-17 18:05:20 +00005370 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005371
5372 if (BO->Opcode == Instruction::Sub)
5373 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5374 else
5375 AddOps.push_back(getSCEV(BO->RHS));
5376
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005377 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005378 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5379 NewBO->Opcode != Instruction::Sub)) {
5380 AddOps.push_back(getSCEV(BO->LHS));
5381 break;
5382 }
5383 BO = NewBO;
5384 } while (true);
5385
5386 return getAddExpr(AddOps);
5387 }
5388
5389 case Instruction::Mul: {
5390 SmallVector<const SCEV *, 4> MulOps;
5391 do {
5392 if (BO->Op) {
5393 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5394 MulOps.push_back(OpSCEV);
5395 break;
5396 }
5397
5398 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5399 if (Flags != SCEV::FlagAnyWrap) {
5400 MulOps.push_back(
5401 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5402 break;
5403 }
5404 }
5405
5406 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005407 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005408 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5409 MulOps.push_back(getSCEV(BO->LHS));
5410 break;
5411 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005412 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005413 } while (true);
5414
5415 return getMulExpr(MulOps);
5416 }
5417 case Instruction::UDiv:
5418 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5419 case Instruction::Sub: {
5420 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5421 if (BO->Op)
5422 Flags = getNoWrapFlagsFromUB(BO->Op);
5423 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5424 }
5425 case Instruction::And:
5426 // For an expression like x&255 that merely masks off the high bits,
5427 // use zext(trunc(x)) as the SCEV expression.
5428 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5429 if (CI->isNullValue())
5430 return getSCEV(BO->RHS);
5431 if (CI->isAllOnesValue())
5432 return getSCEV(BO->LHS);
5433 const APInt &A = CI->getValue();
5434
5435 // Instcombine's ShrinkDemandedConstant may strip bits out of
5436 // constants, obscuring what would otherwise be a low-bits mask.
5437 // Use computeKnownBits to compute what ShrinkDemandedConstant
5438 // knew about to reconstruct a low-bits mask value.
5439 unsigned LZ = A.countLeadingZeros();
5440 unsigned TZ = A.countTrailingZeros();
5441 unsigned BitWidth = A.getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00005442 KnownBits Known(BitWidth);
5443 computeKnownBits(BO->LHS, Known, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005444 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005445
5446 APInt EffectiveMask =
5447 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
Craig Topperb45eabc2017-04-26 16:39:58 +00005448 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005449 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5450 const SCEV *LHS = getSCEV(BO->LHS);
5451 const SCEV *ShiftedLHS = nullptr;
5452 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5453 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5454 // For an expression like (x * 8) & 8, simplify the multiply.
5455 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5456 unsigned GCD = std::min(MulZeros, TZ);
5457 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5458 SmallVector<const SCEV*, 4> MulOps;
5459 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5460 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5461 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5462 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5463 }
5464 }
5465 if (!ShiftedLHS)
5466 ShiftedLHS = getUDivExpr(LHS, MulCount);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005467 return getMulExpr(
5468 getZeroExtendExpr(
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005469 getTruncateExpr(ShiftedLHS,
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005470 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5471 BO->LHS->getType()),
5472 MulCount);
5473 }
Dan Gohman36bad002009-09-17 18:05:20 +00005474 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005475 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005476
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005477 case Instruction::Or:
Eli Friedmand0e6ae562017-04-20 23:59:05 +00005478 // If the RHS of the Or is a constant, we may have something like:
5479 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5480 // optimizations will transparently handle this case.
5481 //
5482 // In order for this transformation to be safe, the LHS must be of the
5483 // form X*(2^n) and the Or constant must be less than 2^n.
5484 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5485 const SCEV *LHS = getSCEV(BO->LHS);
5486 const APInt &CIVal = CI->getValue();
5487 if (GetMinTrailingZeros(LHS) >=
5488 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5489 // Build a plain add SCEV.
5490 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5491 // If the LHS of the add was an addrec and it has no-wrap flags,
5492 // transfer the no-wrap flags, since an or won't introduce a wrap.
5493 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5494 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5495 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5496 OldAR->getNoWrapFlags());
5497 }
5498 return S;
5499 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005500 }
5501 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005502
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005503 case Instruction::Xor:
5504 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5505 // If the RHS of xor is -1, then this is a not operation.
5506 if (CI->isAllOnesValue())
5507 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005508
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005509 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5510 // This is a variant of the check for xor with -1, and it handles
5511 // the case where instcombine has trimmed non-demanded bits out
5512 // of an xor with -1.
5513 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5514 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5515 if (LBO->getOpcode() == Instruction::And &&
5516 LCI->getValue() == CI->getValue())
5517 if (const SCEVZeroExtendExpr *Z =
5518 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5519 Type *UTy = BO->LHS->getType();
5520 const SCEV *Z0 = Z->getOperand();
5521 Type *Z0Ty = Z0->getType();
5522 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005523
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005524 // If C is a low-bits mask, the zero extend is serving to
5525 // mask off the high bits. Complement the operand and
5526 // re-apply the zext.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005527 if (CI->getValue().isMask(Z0TySize))
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005528 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5529
5530 // If C is a single bit, it may be in the sign-bit position
5531 // before the zero-extend. In this case, represent the xor
5532 // using an add, which is equivalent, and re-apply the zext.
5533 APInt Trunc = CI->getValue().trunc(Z0TySize);
5534 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Craig Topperbcfd2d12017-04-20 16:56:25 +00005535 Trunc.isSignMask())
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005536 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5537 UTy);
5538 }
5539 }
5540 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005541
5542 case Instruction::Shl:
5543 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005544 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5545 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005546
5547 // If the shift count is not less than the bitwidth, the result of
5548 // the shift is undefined. Don't try to analyze it, because the
5549 // resolution chosen here may differ from the resolution chosen in
5550 // other parts of the compiler.
5551 if (SA->getValue().uge(BitWidth))
5552 break;
5553
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005554 // It is currently not resolved how to interpret NSW for left
5555 // shift by BitWidth - 1, so we avoid applying flags in that
5556 // case. Remove this check (or this comment) once the situation
5557 // is resolved. See
5558 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5559 // and http://reviews.llvm.org/D8890 .
5560 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005561 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5562 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005563
Owen Andersonedb4a702009-07-24 23:12:02 +00005564 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005565 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005566 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005567 }
5568 break;
5569
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005570 case Instruction::AShr:
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005571 // AShr X, C, where C is a constant.
5572 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5573 if (!CI)
5574 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005575
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005576 Type *OuterTy = BO->LHS->getType();
5577 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5578 // If the shift count is not less than the bitwidth, the result of
5579 // the shift is undefined. Don't try to analyze it, because the
5580 // resolution chosen here may differ from the resolution chosen in
5581 // other parts of the compiler.
5582 if (CI->getValue().uge(BitWidth))
5583 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005584
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005585 if (CI->isNullValue())
5586 return getSCEV(BO->LHS); // shift by zero --> noop
5587
5588 uint64_t AShrAmt = CI->getZExtValue();
5589 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5590
5591 Operator *L = dyn_cast<Operator>(BO->LHS);
5592 if (L && L->getOpcode() == Instruction::Shl) {
5593 // X = Shl A, n
5594 // Y = AShr X, m
5595 // Both n and m are constant.
5596
5597 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5598 if (L->getOperand(1) == BO->RHS)
5599 // For a two-shift sext-inreg, i.e. n = m,
5600 // use sext(trunc(x)) as the SCEV expression.
5601 return getSignExtendExpr(
5602 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5603
5604 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5605 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5606 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5607 if (ShlAmt > AShrAmt) {
5608 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5609 // expression. We already checked that ShlAmt < BitWidth, so
5610 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5611 // ShlAmt - AShrAmt < Amt.
5612 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5613 ShlAmt - AShrAmt);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005614 return getSignExtendExpr(
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005615 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5616 getConstant(Mul)), OuterTy);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005617 }
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005618 }
5619 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005620 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005621 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005622 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005623
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005624 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005625 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005626 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005627
5628 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005629 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005630
5631 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005632 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005633
5634 case Instruction::BitCast:
5635 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005636 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005637 return getSCEV(U->getOperand(0));
5638 break;
5639
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005640 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5641 // lead to pointer expressions which cannot safely be expanded to GEPs,
5642 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5643 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005644
Dan Gohmanee750d12009-05-08 20:26:55 +00005645 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005646 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005647
Dan Gohman05e89732008-06-22 19:56:46 +00005648 case Instruction::PHI:
5649 return createNodeForPHI(cast<PHINode>(U));
5650
5651 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005652 // U can also be a select constant expr, which let fall through. Since
5653 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5654 // constant expressions cannot have instructions as operands, we'd have
5655 // returned getUnknown for a select constant expressions anyway.
5656 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005657 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5658 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005659 break;
5660
5661 case Instruction::Call:
5662 case Instruction::Invoke:
5663 if (Value *RV = CallSite(U).getReturnedArgOperand())
5664 return getSCEV(RV);
5665 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005666 }
5667
Dan Gohmanc8e23622009-04-21 23:15:49 +00005668 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005669}
5670
5671
5672
5673//===----------------------------------------------------------------------===//
5674// Iteration Count Computation Code
5675//
5676
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005677static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5678 if (!ExitCount)
5679 return 0;
5680
5681 ConstantInt *ExitConst = ExitCount->getValue();
5682
5683 // Guard against huge trip counts.
5684 if (ExitConst->getValue().getActiveBits() > 32)
5685 return 0;
5686
5687 // In case of integer overflow, this returns 0, which is correct.
5688 return ((unsigned)ExitConst->getZExtValue()) + 1;
5689}
5690
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005691unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005692 if (BasicBlock *ExitingBB = L->getExitingBlock())
5693 return getSmallConstantTripCount(L, ExitingBB);
5694
5695 // No trip count information for multiple exits.
5696 return 0;
5697}
5698
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005699unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005700 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005701 assert(ExitingBlock && "Must pass a non-null exiting block!");
5702 assert(L->isLoopExiting(ExitingBlock) &&
5703 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005704 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005705 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005706 return getConstantTripCount(ExitCount);
5707}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005708
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005709unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005710 const auto *MaxExitCount =
5711 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5712 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005713}
5714
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005715unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005716 if (BasicBlock *ExitingBB = L->getExitingBlock())
5717 return getSmallConstantTripMultiple(L, ExitingBB);
5718
5719 // No trip multiple information for multiple exits.
5720 return 0;
5721}
5722
Sanjoy Dasf8570812016-05-29 00:38:22 +00005723/// Returns the largest constant divisor of the trip count of this loop as a
5724/// normal unsigned value, if possible. This means that the actual trip count is
5725/// always a multiple of the returned value (don't forget the trip count could
5726/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005727///
5728/// Returns 1 if the trip count is unknown or not guaranteed to be the
5729/// multiple of a constant (which is also the case if the trip count is simply
5730/// constant, use getSmallConstantTripCount for that case), Will also return 1
5731/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005732///
5733/// As explained in the comments for getSmallConstantTripCount, this assumes
5734/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005735unsigned
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005736ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005737 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005738 assert(ExitingBlock && "Must pass a non-null exiting block!");
5739 assert(L->isLoopExiting(ExitingBlock) &&
5740 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005741 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005742 if (ExitCount == getCouldNotCompute())
5743 return 1;
5744
5745 // Get the trip count from the BE count by adding 1.
Eli Friedmanb1578d32017-03-20 20:25:46 +00005746 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005747
Eli Friedmanb1578d32017-03-20 20:25:46 +00005748 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5749 if (!TC)
5750 // Attempt to factor more general cases. Returns the greatest power of
5751 // two divisor. If overflow happens, the trip count expression is still
5752 // divisible by the greatest power of 2 divisor returned.
5753 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005754
Eli Friedmanb1578d32017-03-20 20:25:46 +00005755 ConstantInt *Result = TC->getValue();
Andrew Trick2b6860f2011-08-11 23:36:16 +00005756
Hal Finkel30bd9342012-10-24 19:46:44 +00005757 // Guard against huge trip counts (this requires checking
5758 // for zero to handle the case where the trip count == -1 and the
5759 // addition wraps).
5760 if (!Result || Result->getValue().getActiveBits() > 32 ||
5761 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005762 return 1;
5763
5764 return (unsigned)Result->getZExtValue();
5765}
5766
Sanjoy Dasf8570812016-05-29 00:38:22 +00005767/// Get the expression for the number of loop iterations for which this loop is
5768/// guaranteed not to exit via ExitingBlock. Otherwise return
5769/// SCEVCouldNotCompute.
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005770const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5771 BasicBlock *ExitingBlock) {
Andrew Trick77c55422011-08-02 04:23:35 +00005772 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005773}
5774
Silviu Baranga6f444df2016-04-08 14:29:09 +00005775const SCEV *
5776ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5777 SCEVUnionPredicate &Preds) {
5778 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5779}
5780
Dan Gohmanaf752342009-07-07 17:06:11 +00005781const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005782 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005783}
5784
Sanjoy Dasf8570812016-05-29 00:38:22 +00005785/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5786/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005787const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005788 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005789}
5790
John Brawn84b21832016-10-21 11:08:48 +00005791bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5792 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5793}
5794
Sanjoy Dasf8570812016-05-29 00:38:22 +00005795/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005796static void
5797PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5798 BasicBlock *Header = L->getHeader();
5799
5800 // Push all Loop-header PHIs onto the Worklist stack.
5801 for (BasicBlock::iterator I = Header->begin();
5802 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5803 Worklist.push_back(PN);
5804}
5805
Dan Gohman2b8da352009-04-30 20:47:05 +00005806const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005807ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5808 auto &BTI = getBackedgeTakenInfo(L);
5809 if (BTI.hasFullInfo())
5810 return BTI;
5811
5812 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5813
5814 if (!Pair.second)
5815 return Pair.first->second;
5816
5817 BackedgeTakenInfo Result =
5818 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5819
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005820 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005821}
5822
5823const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005824ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005825 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005826 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005827 // update the value. The temporary CouldNotCompute value tells SCEV
5828 // code elsewhere that it shouldn't attempt to request a new
5829 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005830 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005831 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005832 if (!Pair.second)
5833 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005834
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005835 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005836 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5837 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005838 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005839
5840 if (Result.getExact(this) != getCouldNotCompute()) {
5841 assert(isLoopInvariant(Result.getExact(this), L) &&
5842 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005843 "Computed backedge-taken count isn't loop invariant for loop!");
5844 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005845 }
5846 else if (Result.getMax(this) == getCouldNotCompute() &&
5847 isa<PHINode>(L->getHeader()->begin())) {
5848 // Only count loops that have phi nodes as not being computable.
5849 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005850 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005851
Chris Lattnera337f5e2011-01-09 02:16:18 +00005852 // Now that we know more about the trip count for this loop, forget any
5853 // existing SCEV values for PHI nodes in this loop since they are only
5854 // conservative estimates made without the benefit of trip count
5855 // information. This is similar to the code in forgetLoop, except that
5856 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005857 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005858 SmallVector<Instruction *, 16> Worklist;
5859 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005860
Chris Lattnera337f5e2011-01-09 02:16:18 +00005861 SmallPtrSet<Instruction *, 8> Visited;
5862 while (!Worklist.empty()) {
5863 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005864 if (!Visited.insert(I).second)
5865 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005866
Chris Lattnera337f5e2011-01-09 02:16:18 +00005867 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005868 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005869 if (It != ValueExprMap.end()) {
5870 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005871
Chris Lattnera337f5e2011-01-09 02:16:18 +00005872 // SCEVUnknown for a PHI either means that it has an unrecognized
5873 // structure, or it's a PHI that's in the progress of being computed
5874 // by createNodeForPHI. In the former case, additional loop trip
5875 // count information isn't going to change anything. In the later
5876 // case, createNodeForPHI will perform the necessary updates on its
5877 // own when it gets to that point.
5878 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005879 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005880 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005881 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005882 if (PHINode *PN = dyn_cast<PHINode>(I))
5883 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005884 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005885
5886 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005887 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005888 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005889
5890 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005891 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005892 // recusive call to getBackedgeTakenInfo (on a different
5893 // loop), which would invalidate the iterator computed
5894 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005895 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005896}
5897
Dan Gohman880c92a2009-10-31 15:04:55 +00005898void ScalarEvolution::forgetLoop(const Loop *L) {
5899 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005900 auto RemoveLoopFromBackedgeMap =
5901 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5902 auto BTCPos = Map.find(L);
5903 if (BTCPos != Map.end()) {
5904 BTCPos->second.clear();
5905 Map.erase(BTCPos);
5906 }
5907 };
5908
5909 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5910 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005911
Dan Gohman880c92a2009-10-31 15:04:55 +00005912 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005913 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005914 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005915
Dan Gohmandc191042009-07-08 19:23:34 +00005916 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005917 while (!Worklist.empty()) {
5918 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005919 if (!Visited.insert(I).second)
5920 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005921
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005922 ValueExprMapType::iterator It =
5923 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005924 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005925 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005926 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005927 if (PHINode *PN = dyn_cast<PHINode>(I))
5928 ConstantEvolutionLoopExitValue.erase(PN);
5929 }
5930
5931 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005932 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005933
5934 // Forget all contained loops too, to avoid dangling entries in the
5935 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005936 for (Loop *I : *L)
5937 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005938
Sanjoy Das5603fc02016-09-26 02:44:07 +00005939 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005940}
5941
Eric Christopheref6d5932010-07-29 01:25:38 +00005942void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005943 Instruction *I = dyn_cast<Instruction>(V);
5944 if (!I) return;
5945
5946 // Drop information about expressions based on loop-header PHIs.
5947 SmallVector<Instruction *, 16> Worklist;
5948 Worklist.push_back(I);
5949
5950 SmallPtrSet<Instruction *, 8> Visited;
5951 while (!Worklist.empty()) {
5952 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005953 if (!Visited.insert(I).second)
5954 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005955
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005956 ValueExprMapType::iterator It =
5957 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005958 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005959 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005960 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005961 if (PHINode *PN = dyn_cast<PHINode>(I))
5962 ConstantEvolutionLoopExitValue.erase(PN);
5963 }
5964
5965 PushDefUseChildren(I, Worklist);
5966 }
5967}
5968
Sanjoy Dasf8570812016-05-29 00:38:22 +00005969/// Get the exact loop backedge taken count considering all loop exits. A
5970/// computable result can only be returned for loops with a single exit.
5971/// Returning the minimum taken count among all exits is incorrect because one
5972/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5973/// the limit of each loop test is never skipped. This is a valid assumption as
5974/// long as the loop exits via that test. For precise results, it is the
5975/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005976/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005977const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005978ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5979 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005980 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005981 if (!isComplete() || ExitNotTaken.empty())
5982 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005983
Craig Topper9f008862014-04-15 04:59:12 +00005984 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005985 for (auto &ENT : ExitNotTaken) {
5986 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005987
5988 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005989 BECount = ENT.ExactNotTaken;
5990 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005991 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005992 if (Preds && !ENT.hasAlwaysTruePredicate())
5993 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005994
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005995 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005996 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005997 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005998
Andrew Trickbbb226a2011-09-02 21:20:46 +00005999 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00006000 return BECount;
6001}
6002
Sanjoy Dasf8570812016-05-29 00:38:22 +00006003/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006004const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00006005ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006006 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00006007 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00006008 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00006009 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00006010
Andrew Trick3ca3f982011-07-26 17:19:55 +00006011 return SE->getCouldNotCompute();
6012}
6013
6014/// getMax - Get the max backedge taken count for the loop.
6015const SCEV *
6016ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00006017 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6018 return !ENT.hasAlwaysTruePredicate();
6019 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00006020
Sanjoy Das73268612016-09-26 01:10:22 +00006021 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6022 return SE->getCouldNotCompute();
6023
Sanjoy Das036dda22017-05-22 06:46:04 +00006024 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6025 "No point in having a non-constant max backedge taken count!");
Sanjoy Das73268612016-09-26 01:10:22 +00006026 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00006027}
6028
John Brawn84b21832016-10-21 11:08:48 +00006029bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6030 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6031 return !ENT.hasAlwaysTruePredicate();
6032 };
6033 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6034}
6035
Andrew Trick9093e152013-03-26 03:14:53 +00006036bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6037 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00006038 if (getMax() && getMax() != SE->getCouldNotCompute() &&
6039 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00006040 return true;
6041
Silviu Baranga6f444df2016-04-08 14:29:09 +00006042 for (auto &ENT : ExitNotTaken)
6043 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6044 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00006045 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006046
Andrew Trick9093e152013-03-26 03:14:53 +00006047 return false;
6048}
6049
Sanjoy Dasf6f6fb92017-05-15 04:22:09 +00006050ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
Sanjoy Das036dda22017-05-22 06:46:04 +00006051 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {
6052 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6053 isa<SCEVConstant>(MaxNotTaken)) &&
6054 "No point in having a non-constant max backedge taken count!");
6055}
Sanjoy Dasf6f6fb92017-05-15 04:22:09 +00006056
6057ScalarEvolution::ExitLimit::ExitLimit(
6058 const SCEV *E, const SCEV *M, bool MaxOrZero,
6059 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6060 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6061 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6062 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6063 "Exact is not allowed to be less precise than Max");
Sanjoy Das036dda22017-05-22 06:46:04 +00006064 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6065 isa<SCEVConstant>(MaxNotTaken)) &&
6066 "No point in having a non-constant max backedge taken count!");
Sanjoy Dasf6f6fb92017-05-15 04:22:09 +00006067 for (auto *PredSet : PredSetList)
6068 for (auto *P : *PredSet)
6069 addPredicate(P);
6070}
6071
6072ScalarEvolution::ExitLimit::ExitLimit(
6073 const SCEV *E, const SCEV *M, bool MaxOrZero,
6074 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
Sanjoy Das036dda22017-05-22 06:46:04 +00006075 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6076 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6077 isa<SCEVConstant>(MaxNotTaken)) &&
6078 "No point in having a non-constant max backedge taken count!");
6079}
Sanjoy Dasf6f6fb92017-05-15 04:22:09 +00006080
6081ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6082 bool MaxOrZero)
Sanjoy Das036dda22017-05-22 06:46:04 +00006083 : ExitLimit(E, M, MaxOrZero, None) {
6084 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6085 isa<SCEVConstant>(MaxNotTaken)) &&
6086 "No point in having a non-constant max backedge taken count!");
6087}
Sanjoy Dasf6f6fb92017-05-15 04:22:09 +00006088
Andrew Trick3ca3f982011-07-26 17:19:55 +00006089/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6090/// computable exit into a persistent ExitNotTakenInfo array.
6091ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00006092 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6093 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00006094 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6095 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00006096 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00006097 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00006098 std::transform(
6099 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00006100 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00006101 BasicBlock *ExitBB = EEI.first;
6102 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00006103 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00006104 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00006105
6106 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6107 for (auto *Pred : EL.Predicates)
6108 Predicate->add(Pred);
6109
6110 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00006111 });
Sanjoy Das036dda22017-05-22 06:46:04 +00006112 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6113 "No point in having a non-constant max backedge taken count!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00006114}
6115
Sanjoy Dasf8570812016-05-29 00:38:22 +00006116/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006117void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00006118 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00006119}
6120
Sanjoy Dasf8570812016-05-29 00:38:22 +00006121/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00006122ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00006123ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6124 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00006125 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00006126 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00006127
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00006128 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6129
6130 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00006131 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00006132 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00006133 const SCEV *MustExitMaxBECount = nullptr;
6134 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00006135 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00006136
6137 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6138 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006139 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00006140 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00006141 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00006142 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6143
Sanjoy Dasf0022122016-09-28 17:14:58 +00006144 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00006145 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00006146
6147 // 1. For each exit that can be computed, add an entry to ExitCounts.
6148 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006149 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00006150 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00006151 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006152 CouldComputeBECount = false;
6153 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00006154 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006155
Andrew Trick839e30b2014-05-23 19:47:13 +00006156 // 2. Derive the loop's MaxBECount from each exit's max number of
6157 // non-exiting iterations. Partition the loop exits into two kinds:
6158 // LoopMustExits and LoopMayExits.
6159 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006160 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6161 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006162 // MaxBECount is the minimum EL.MaxNotTaken of computable
6163 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6164 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6165 // computable EL.MaxNotTaken.
6166 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006167 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00006168 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006169 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00006170 MustExitMaxOrZero = EL.MaxOrZero;
6171 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00006172 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006173 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00006174 }
Andrew Trick839e30b2014-05-23 19:47:13 +00006175 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006176 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6177 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00006178 else {
6179 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006180 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00006181 }
Andrew Trick90c7a102011-11-16 00:52:40 +00006182 }
Dan Gohman96212b62009-06-22 00:31:57 +00006183 }
Andrew Trick839e30b2014-05-23 19:47:13 +00006184 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6185 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00006186 // The loop backedge will be taken the maximum or zero times if there's
6187 // a single exit that must be taken the maximum or zero times.
6188 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00006189 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00006190 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00006191}
6192
Andrew Trick3ca3f982011-07-26 17:19:55 +00006193ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00006194ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6195 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00006196
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006197 // Okay, we've chosen an exiting block. See what condition causes us to exit
6198 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00006199 // lead to the loop header.
6200 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00006201 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00006202 for (auto *SBB : successors(ExitingBlock))
6203 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006204 if (Exit) // Multiple exit successors.
6205 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00006206 Exit = SBB;
6207 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006208 MustExecuteLoopHeader = false;
6209 }
Dan Gohmance973df2009-06-24 04:48:43 +00006210
Chris Lattner18954852007-01-07 02:24:26 +00006211 // At this point, we know we have a conditional branch that determines whether
6212 // the loop is exited. However, we don't know if the branch is executed each
6213 // time through the loop. If not, then the execution count of the branch will
6214 // not be equal to the trip count of the loop.
6215 //
6216 // Currently we check for this by checking to see if the Exit branch goes to
6217 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00006218 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00006219 // loop header. This is common for un-rotated loops.
6220 //
6221 // If both of those tests fail, walk up the unique predecessor chain to the
6222 // header, stopping if there is an edge that doesn't exit the loop. If the
6223 // header is reached, the execution count of the branch will be equal to the
6224 // trip count of the loop.
6225 //
6226 // More extensive analysis could be done to handle more cases here.
6227 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00006228 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00006229 // The simple checks failed, try climbing the unique predecessor chain
6230 // up to the header.
6231 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00006232 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00006233 BasicBlock *Pred = BB->getUniquePredecessor();
6234 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006235 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006236 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00006237 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00006238 if (PredSucc == BB)
6239 continue;
6240 // If the predecessor has a successor that isn't BB and isn't
6241 // outside the loop, assume the worst.
6242 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006243 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006244 }
6245 if (Pred == L->getHeader()) {
6246 Ok = true;
6247 break;
6248 }
6249 BB = Pred;
6250 }
6251 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006252 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006253 }
6254
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006255 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006256 TerminatorInst *Term = ExitingBlock->getTerminator();
6257 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6258 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6259 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006260 return computeExitLimitFromCond(
6261 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6262 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006263 }
6264
6265 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006266 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006267 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006268
6269 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006270}
6271
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006272ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6273 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6274 bool ControlsExit, bool AllowPredicates) {
6275 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6276 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6277 ControlsExit, AllowPredicates);
6278}
6279
6280Optional<ScalarEvolution::ExitLimit>
6281ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6282 BasicBlock *TBB, BasicBlock *FBB,
6283 bool ControlsExit, bool AllowPredicates) {
Sanjoy Das25972aa2017-04-24 00:46:40 +00006284 (void)this->L;
6285 (void)this->TBB;
6286 (void)this->FBB;
6287 (void)this->AllowPredicates;
6288
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006289 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6290 this->AllowPredicates == AllowPredicates &&
6291 "Variance in assumed invariant key components!");
6292 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6293 if (Itr == TripCountMap.end())
6294 return None;
6295 return Itr->second;
6296}
6297
6298void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6299 BasicBlock *TBB, BasicBlock *FBB,
6300 bool ControlsExit,
6301 bool AllowPredicates,
6302 const ExitLimit &EL) {
6303 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6304 this->AllowPredicates == AllowPredicates &&
6305 "Variance in assumed invariant key components!");
6306
6307 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6308 assert(InsertResult.second && "Expected successful insertion!");
Sanjoy Das25972aa2017-04-24 00:46:40 +00006309 (void)InsertResult;
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006310}
6311
6312ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6313 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6314 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6315
6316 if (auto MaybeEL =
6317 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6318 return *MaybeEL;
6319
6320 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6321 ControlsExit, AllowPredicates);
6322 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6323 return EL;
6324}
6325
6326ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6327 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6328 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006329 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00006330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6331 if (BO->getOpcode() == Instruction::And) {
6332 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00006333 bool EitherMayExit = L->contains(TBB);
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006334 ExitLimit EL0 = computeExitLimitFromCondCached(
6335 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6336 AllowPredicates);
6337 ExitLimit EL1 = computeExitLimitFromCondCached(
6338 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6339 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006340 const SCEV *BECount = getCouldNotCompute();
6341 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006342 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006343 // Both conditions must be true for the loop to continue executing.
6344 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006345 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6346 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006347 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006348 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006349 BECount =
6350 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6351 if (EL0.MaxNotTaken == getCouldNotCompute())
6352 MaxBECount = EL1.MaxNotTaken;
6353 else if (EL1.MaxNotTaken == getCouldNotCompute())
6354 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006355 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006356 MaxBECount =
6357 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006358 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006359 // Both conditions must be true at the same time for the loop to exit.
6360 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006361 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006362 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6363 MaxBECount = EL0.MaxNotTaken;
6364 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6365 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006366 }
6367
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006368 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6369 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006370 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6371 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6372 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006373 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6374 !isa<SCEVCouldNotCompute>(BECount))
Craig Topper01020392017-06-24 23:34:50 +00006375 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006376
John Brawn84b21832016-10-21 11:08:48 +00006377 return ExitLimit(BECount, MaxBECount, false,
6378 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006379 }
6380 if (BO->getOpcode() == Instruction::Or) {
6381 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00006382 bool EitherMayExit = L->contains(FBB);
Sanjoy Dasbdbc4932017-04-24 00:09:46 +00006383 ExitLimit EL0 = computeExitLimitFromCondCached(
6384 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6385 AllowPredicates);
6386 ExitLimit EL1 = computeExitLimitFromCondCached(
6387 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6388 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006389 const SCEV *BECount = getCouldNotCompute();
6390 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006391 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006392 // Both conditions must be false for the loop to continue executing.
6393 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006394 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6395 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006396 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006397 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006398 BECount =
6399 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6400 if (EL0.MaxNotTaken == getCouldNotCompute())
6401 MaxBECount = EL1.MaxNotTaken;
6402 else if (EL1.MaxNotTaken == getCouldNotCompute())
6403 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006404 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006405 MaxBECount =
6406 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006407 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006408 // Both conditions must be false at the same time for the loop to exit.
6409 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006410 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006411 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6412 MaxBECount = EL0.MaxNotTaken;
6413 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6414 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006415 }
6416
John Brawn84b21832016-10-21 11:08:48 +00006417 return ExitLimit(BECount, MaxBECount, false,
6418 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006419 }
6420 }
6421
6422 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006423 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006424 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6425 ExitLimit EL =
6426 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6427 if (EL.hasFullInfo() || !AllowPredicates)
6428 return EL;
6429
6430 // Try again, but use SCEV predicates this time.
6431 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6432 /*AllowPredicates=*/true);
6433 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006434
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006435 // Check for a constant condition. These are normally stripped out by
6436 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6437 // preserve the CFG and is temporarily leaving constant conditions
6438 // in place.
6439 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6440 if (L->contains(FBB) == !CI->getZExtValue())
6441 // The backedge is always taken.
6442 return getCouldNotCompute();
6443 else
6444 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006445 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006446 }
6447
Eli Friedmanebf98b02009-05-09 12:32:42 +00006448 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006449 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006450}
6451
Andrew Trick3ca3f982011-07-26 17:19:55 +00006452ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006453ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006454 ICmpInst *ExitCond,
6455 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006456 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006457 bool ControlsExit,
6458 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006459
Reid Spencer266e42b2006-12-23 06:05:41 +00006460 // If the condition was exit on true, convert the condition to exit on false
6461 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006462 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006463 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006464 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006465 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006466
6467 // Handle common loops like: for (X = "string"; *X; ++X)
6468 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6469 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006470 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006471 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006472 if (ItCnt.hasAnyInfo())
6473 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006474 }
6475
Dan Gohmanaf752342009-07-07 17:06:11 +00006476 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6477 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006478
6479 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006480 LHS = getSCEVAtScope(LHS, L);
6481 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006482
Dan Gohmance973df2009-06-24 04:48:43 +00006483 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006484 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006485 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006486 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006487 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006488 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006489 }
6490
Dan Gohman81585c12010-05-03 16:35:17 +00006491 // Simplify the operands before analyzing them.
6492 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6493
Chris Lattnerd934c702004-04-02 20:23:17 +00006494 // If we have a comparison of a chrec against a constant, try to use value
6495 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006496 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6497 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006498 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006499 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006500 ConstantRange CompRange =
6501 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006502
Dan Gohmanaf752342009-07-07 17:06:11 +00006503 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006504 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006505 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006506
Chris Lattnerd934c702004-04-02 20:23:17 +00006507 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006508 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006509 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006510 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006511 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006512 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006513 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006514 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006515 case ICmpInst::ICMP_EQ: { // while (X == Y)
6516 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006517 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006518 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006519 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006520 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006521 case ICmpInst::ICMP_SLT:
6522 case ICmpInst::ICMP_ULT: { // while (X < Y)
6523 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006524 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006525 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006526 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006527 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006528 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006529 case ICmpInst::ICMP_SGT:
6530 case ICmpInst::ICMP_UGT: { // while (X > Y)
6531 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006532 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006533 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006534 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006535 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006536 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006537 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006538 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006539 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006540 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006541
6542 auto *ExhaustiveCount =
6543 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6544
6545 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6546 return ExhaustiveCount;
6547
6548 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6549 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006550}
6551
Benjamin Kramer5a188542014-02-11 15:44:32 +00006552ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006553ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006554 SwitchInst *Switch,
6555 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006556 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006557 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6558
6559 // Give up if the exit is the default dest of a switch.
6560 if (Switch->getDefaultDest() == ExitingBlock)
6561 return getCouldNotCompute();
6562
6563 assert(L->contains(Switch->getDefaultDest()) &&
6564 "Default case must not exit the loop!");
6565 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6566 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6567
6568 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006569 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006570 if (EL.hasAnyInfo())
6571 return EL;
6572
6573 return getCouldNotCompute();
6574}
6575
Chris Lattnerec901cc2004-10-12 01:49:27 +00006576static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006577EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6578 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006579 const SCEV *InVal = SE.getConstant(C);
6580 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006581 assert(isa<SCEVConstant>(Val) &&
6582 "Evaluation of SCEV at constant didn't fold correctly?");
6583 return cast<SCEVConstant>(Val)->getValue();
6584}
6585
Sanjoy Dasf8570812016-05-29 00:38:22 +00006586/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6587/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006588ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006589ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006590 LoadInst *LI,
6591 Constant *RHS,
6592 const Loop *L,
6593 ICmpInst::Predicate predicate) {
6594
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006595 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006596
6597 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006598 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006599 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006600 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006601
6602 // Make sure that it is really a constant global we are gepping, with an
6603 // initializer, and make sure the first IDX is really 0.
6604 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006605 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006606 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6607 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006608 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006609
6610 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006611 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006612 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006613 unsigned VarIdxNum = 0;
6614 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6615 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6616 Indexes.push_back(CI);
6617 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006618 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006619 VarIdx = GEP->getOperand(i);
6620 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006621 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006622 }
6623
Andrew Trick7004e4b2012-03-26 22:33:59 +00006624 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6625 if (!VarIdx)
6626 return getCouldNotCompute();
6627
Chris Lattnerec901cc2004-10-12 01:49:27 +00006628 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6629 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006630 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006631 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006632
6633 // We can only recognize very limited forms of loop index expressions, in
6634 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006635 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006636 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006637 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6638 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006639 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006640
6641 unsigned MaxSteps = MaxBruteForceIterations;
6642 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006643 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006644 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006645 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006646
6647 // Form the GEP offset.
6648 Indexes[VarIdxNum] = Val;
6649
Chris Lattnere166a852012-01-24 05:49:24 +00006650 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6651 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006652 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006653
6654 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006655 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006656 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006657 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006658 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006659 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006660 }
6661 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006662 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006663}
6664
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006665ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6666 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6667 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6668 if (!RHS)
6669 return getCouldNotCompute();
6670
6671 const BasicBlock *Latch = L->getLoopLatch();
6672 if (!Latch)
6673 return getCouldNotCompute();
6674
6675 const BasicBlock *Predecessor = L->getLoopPredecessor();
6676 if (!Predecessor)
6677 return getCouldNotCompute();
6678
6679 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6680 // Return LHS in OutLHS and shift_opt in OutOpCode.
6681 auto MatchPositiveShift =
6682 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6683
6684 using namespace PatternMatch;
6685
6686 ConstantInt *ShiftAmt;
6687 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6688 OutOpCode = Instruction::LShr;
6689 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6690 OutOpCode = Instruction::AShr;
6691 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6692 OutOpCode = Instruction::Shl;
6693 else
6694 return false;
6695
6696 return ShiftAmt->getValue().isStrictlyPositive();
6697 };
6698
6699 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6700 //
6701 // loop:
6702 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6703 // %iv.shifted = lshr i32 %iv, <positive constant>
6704 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006705 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006706 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6707 auto MatchShiftRecurrence =
6708 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6709 Optional<Instruction::BinaryOps> PostShiftOpCode;
6710
6711 {
6712 Instruction::BinaryOps OpC;
6713 Value *V;
6714
6715 // If we encounter a shift instruction, "peel off" the shift operation,
6716 // and remember that we did so. Later when we inspect %iv's backedge
6717 // value, we will make sure that the backedge value uses the same
6718 // operation.
6719 //
6720 // Note: the peeled shift operation does not have to be the same
6721 // instruction as the one feeding into the PHI's backedge value. We only
6722 // really care about it being the same *kind* of shift instruction --
6723 // that's all that is required for our later inferences to hold.
6724 if (MatchPositiveShift(LHS, V, OpC)) {
6725 PostShiftOpCode = OpC;
6726 LHS = V;
6727 }
6728 }
6729
6730 PNOut = dyn_cast<PHINode>(LHS);
6731 if (!PNOut || PNOut->getParent() != L->getHeader())
6732 return false;
6733
6734 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6735 Value *OpLHS;
6736
6737 return
6738 // The backedge value for the PHI node must be a shift by a positive
6739 // amount
6740 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6741
6742 // of the PHI node itself
6743 OpLHS == PNOut &&
6744
6745 // and the kind of shift should be match the kind of shift we peeled
6746 // off, if any.
6747 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6748 };
6749
6750 PHINode *PN;
6751 Instruction::BinaryOps OpCode;
6752 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6753 return getCouldNotCompute();
6754
6755 const DataLayout &DL = getDataLayout();
6756
6757 // The key rationale for this optimization is that for some kinds of shift
6758 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6759 // within a finite number of iterations. If the condition guarding the
6760 // backedge (in the sense that the backedge is taken if the condition is true)
6761 // is false for the value the shift recurrence stabilizes to, then we know
6762 // that the backedge is taken only a finite number of times.
6763
6764 ConstantInt *StableValue = nullptr;
6765 switch (OpCode) {
6766 default:
6767 llvm_unreachable("Impossible case!");
6768
6769 case Instruction::AShr: {
6770 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6771 // bitwidth(K) iterations.
6772 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
Craig Topper1a36b7d2017-05-15 06:39:41 +00006773 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
6774 Predecessor->getTerminator(), &DT);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006775 auto *Ty = cast<IntegerType>(RHS->getType());
Craig Topper1a36b7d2017-05-15 06:39:41 +00006776 if (Known.isNonNegative())
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006777 StableValue = ConstantInt::get(Ty, 0);
Craig Topper1a36b7d2017-05-15 06:39:41 +00006778 else if (Known.isNegative())
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006779 StableValue = ConstantInt::get(Ty, -1, true);
6780 else
6781 return getCouldNotCompute();
6782
6783 break;
6784 }
6785 case Instruction::LShr:
6786 case Instruction::Shl:
6787 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6788 // stabilize to 0 in at most bitwidth(K) iterations.
6789 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6790 break;
6791 }
6792
6793 auto *Result =
6794 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6795 assert(Result->getType()->isIntegerTy(1) &&
6796 "Otherwise cannot be an operand to a branch instruction");
6797
6798 if (Result->isZeroValue()) {
6799 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6800 const SCEV *UpperBound =
6801 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006802 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006803 }
6804
6805 return getCouldNotCompute();
6806}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006807
Sanjoy Dasf8570812016-05-29 00:38:22 +00006808/// Return true if we can constant fold an instruction of the specified type,
6809/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006810static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006811 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006812 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6813 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006814 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006815
Chris Lattnerdd730472004-04-17 22:58:41 +00006816 if (const CallInst *CI = dyn_cast<CallInst>(I))
6817 if (const Function *F = CI->getCalledFunction())
Andrew Kaylor647025f2017-06-09 23:18:11 +00006818 return canConstantFoldCallTo(CI, F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006819 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006820}
6821
Andrew Trick3a86ba72011-10-05 03:25:31 +00006822/// Determine whether this instruction can constant evolve within this loop
6823/// assuming its operands can all constant evolve.
6824static bool canConstantEvolve(Instruction *I, const Loop *L) {
6825 // An instruction outside of the loop can't be derived from a loop PHI.
6826 if (!L->contains(I)) return false;
6827
6828 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006829 // We don't currently keep track of the control flow needed to evaluate
6830 // PHIs, so we cannot handle PHIs inside of loops.
6831 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006832 }
6833
6834 // If we won't be able to constant fold this expression even if the operands
6835 // are constants, bail early.
6836 return CanConstantFold(I);
6837}
6838
6839/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6840/// recursing through each instruction operand until reaching a loop header phi.
6841static PHINode *
6842getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Michael Liao468fb742017-01-13 18:28:30 +00006843 DenseMap<Instruction *, PHINode *> &PHIMap,
6844 unsigned Depth) {
6845 if (Depth > MaxConstantEvolvingDepth)
6846 return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006847
6848 // Otherwise, we can evaluate this instruction if all of its operands are
6849 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006850 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006851 for (Value *Op : UseInst->operands()) {
6852 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006853
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006854 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006855 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006856
6857 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006858 if (!P)
6859 // If this operand is already visited, reuse the prior result.
6860 // We may have P != PHI if this is the deepest point at which the
6861 // inconsistent paths meet.
6862 P = PHIMap.lookup(OpInst);
6863 if (!P) {
6864 // Recurse and memoize the results, whether a phi is found or not.
6865 // This recursive call invalidates pointers into PHIMap.
Michael Liao468fb742017-01-13 18:28:30 +00006866 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006867 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006868 }
Craig Topper9f008862014-04-15 04:59:12 +00006869 if (!P)
6870 return nullptr; // Not evolving from PHI
6871 if (PHI && PHI != P)
6872 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006873 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006874 }
6875 // This is a expression evolving from a constant PHI!
6876 return PHI;
6877}
6878
Chris Lattnerdd730472004-04-17 22:58:41 +00006879/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6880/// in the loop that V is derived from. We allow arbitrary operations along the
6881/// way, but the operands of an operation must either be constants or a value
6882/// derived from a constant PHI. If this expression does not fit with these
6883/// constraints, return null.
6884static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006885 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006886 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006887
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006888 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006889 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006890
Andrew Trick3a86ba72011-10-05 03:25:31 +00006891 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006892 DenseMap<Instruction *, PHINode *> PHIMap;
Michael Liao468fb742017-01-13 18:28:30 +00006893 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
Chris Lattnerdd730472004-04-17 22:58:41 +00006894}
6895
6896/// EvaluateExpression - Given an expression that passes the
6897/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6898/// in the loop has the value PHIVal. If we can't fold this expression for some
6899/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006900static Constant *EvaluateExpression(Value *V, const Loop *L,
6901 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006902 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006903 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006904 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006905 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006906 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006907 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006908
Andrew Trick3a86ba72011-10-05 03:25:31 +00006909 if (Constant *C = Vals.lookup(I)) return C;
6910
Nick Lewyckya6674c72011-10-22 19:58:20 +00006911 // An instruction inside the loop depends on a value outside the loop that we
6912 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006913 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006914
6915 // An unmapped PHI can be due to a branch or another loop inside this loop,
6916 // or due to this not being the initial iteration through a loop where we
6917 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006918 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006919
Dan Gohmanf820bd32010-06-22 13:15:46 +00006920 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006921
6922 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006923 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6924 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006925 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006926 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006927 continue;
6928 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006929 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006930 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006931 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006932 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006933 }
6934
Nick Lewyckya6674c72011-10-22 19:58:20 +00006935 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006936 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006937 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006938 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6939 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006940 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006941 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006942 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006943}
6944
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006945
6946// If every incoming value to PN except the one for BB is a specific Constant,
6947// return that, else return nullptr.
6948static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6949 Constant *IncomingVal = nullptr;
6950
6951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6952 if (PN->getIncomingBlock(i) == BB)
6953 continue;
6954
6955 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6956 if (!CurrentVal)
6957 return nullptr;
6958
6959 if (IncomingVal != CurrentVal) {
6960 if (IncomingVal)
6961 return nullptr;
6962 IncomingVal = CurrentVal;
6963 }
6964 }
6965
6966 return IncomingVal;
6967}
6968
Chris Lattnerdd730472004-04-17 22:58:41 +00006969/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6970/// in the header of its containing loop, we know the loop executes a
6971/// constant number of times, and the PHI node is just a recurrence
6972/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006973Constant *
6974ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006975 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006976 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006977 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006978 if (I != ConstantEvolutionLoopExitValue.end())
6979 return I->second;
6980
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006981 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006982 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006983
6984 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6985
Andrew Trick3a86ba72011-10-05 03:25:31 +00006986 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006987 BasicBlock *Header = L->getHeader();
6988 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006989
Sanjoy Dasdd709962015-10-08 18:28:36 +00006990 BasicBlock *Latch = L->getLoopLatch();
6991 if (!Latch)
6992 return nullptr;
6993
Sanjoy Das4493b402015-10-07 17:38:25 +00006994 for (auto &I : *Header) {
6995 PHINode *PHI = dyn_cast<PHINode>(&I);
6996 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006997 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006998 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006999 CurrentIterVals[PHI] = StartCST;
7000 }
7001 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00007002 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00007003
Sanjoy Dasdd709962015-10-08 18:28:36 +00007004 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00007005
7006 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00007007 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00007008 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00007009
Dan Gohman0bddac12009-02-24 18:55:53 +00007010 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00007011 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00007012 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00007013 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007014 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00007015 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00007016
Nick Lewyckya6674c72011-10-22 19:58:20 +00007017 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00007018 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00007019 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00007020 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007021 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00007022 if (!NextPHI)
7023 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00007024 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007025
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007026 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7027
Nick Lewyckya6674c72011-10-22 19:58:20 +00007028 // Also evaluate the other PHI nodes. However, we don't get to stop if we
7029 // cease to be able to evaluate one of them or if they stop evolving,
7030 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00007031 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00007032 for (const auto &I : CurrentIterVals) {
7033 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00007034 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00007035 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00007036 }
7037 // We use two distinct loops because EvaluateExpression may invalidate any
7038 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00007039 for (const auto &I : PHIsToCompute) {
7040 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007041 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007042 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00007043 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007044 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007045 }
Sanjoy Das4493b402015-10-07 17:38:25 +00007046 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007047 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007048 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007049
7050 // If all entries in CurrentIterVals == NextIterVals then we can stop
7051 // iterating, the loop can't continue to change.
7052 if (StoppedEvolving)
7053 return RetVal = CurrentIterVals[PN];
7054
Andrew Trick3a86ba72011-10-05 03:25:31 +00007055 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00007056 }
7057}
7058
Sanjoy Das413dbbb2015-10-08 18:46:59 +00007059const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00007060 Value *Cond,
7061 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00007062 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00007063 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00007064
Dan Gohman866971e2010-06-19 14:17:24 +00007065 // If the loop is canonicalized, the PHI will have exactly two entries.
7066 // That's the only form we support here.
7067 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7068
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007069 DenseMap<Instruction *, Constant *> CurrentIterVals;
7070 BasicBlock *Header = L->getHeader();
7071 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7072
Sanjoy Dasdd709962015-10-08 18:28:36 +00007073 BasicBlock *Latch = L->getLoopLatch();
7074 assert(Latch && "Should follow from NumIncomingValues == 2!");
7075
Sanjoy Das4493b402015-10-07 17:38:25 +00007076 for (auto &I : *Header) {
7077 PHINode *PHI = dyn_cast<PHINode>(&I);
7078 if (!PHI)
7079 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00007080 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00007081 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007082 CurrentIterVals[PHI] = StartCST;
7083 }
7084 if (!CurrentIterVals.count(PN))
7085 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00007086
7087 // Okay, we find a PHI node that defines the trip count of this loop. Execute
7088 // the loop symbolically to determine when the condition gets a value of
7089 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00007090 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00007091 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007092 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00007093 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007094 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00007095
Zhou Sheng75b871f2007-01-11 12:24:14 +00007096 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007097 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00007098
Reid Spencer983e3b32007-03-01 07:25:48 +00007099 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00007100 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00007101 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00007102 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007103
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007104 // Update all the PHI nodes for the next iteration.
7105 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00007106
7107 // Create a list of which PHIs we need to compute. We want to do this before
7108 // calling EvaluateExpression on them because that may invalidate iterators
7109 // into CurrentIterVals.
7110 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00007111 for (const auto &I : CurrentIterVals) {
7112 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007113 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00007114 PHIsToCompute.push_back(PHI);
7115 }
Sanjoy Das4493b402015-10-07 17:38:25 +00007116 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007117 Constant *&NextPHI = NextIterVals[PHI];
7118 if (NextPHI) continue; // Already computed!
7119
Sanjoy Dasdd709962015-10-08 18:28:36 +00007120 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007121 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00007122 }
7123 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00007124 }
7125
7126 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007127 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007128}
7129
Dan Gohmanaf752342009-07-07 17:06:11 +00007130const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00007131 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7132 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00007133 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00007134 for (auto &LS : Values)
7135 if (LS.first == L)
7136 return LS.second ? LS.second : V;
7137
7138 Values.emplace_back(L, nullptr);
7139
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00007140 // Otherwise compute it.
7141 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00007142 for (auto &LS : reverse(ValuesAtScopes[V]))
7143 if (LS.first == L) {
7144 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007145 break;
7146 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00007147 return C;
7148}
7149
Nick Lewyckya6674c72011-10-22 19:58:20 +00007150/// This builds up a Constant using the ConstantExpr interface. That way, we
7151/// will return Constants for objects which aren't represented by a
7152/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7153/// Returns NULL if the SCEV isn't representable as a Constant.
7154static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00007155 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00007156 case scCouldNotCompute:
7157 case scAddRecExpr:
7158 break;
7159 case scConstant:
7160 return cast<SCEVConstant>(V)->getValue();
7161 case scUnknown:
7162 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7163 case scSignExtend: {
7164 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7165 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7166 return ConstantExpr::getSExt(CastOp, SS->getType());
7167 break;
7168 }
7169 case scZeroExtend: {
7170 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7171 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7172 return ConstantExpr::getZExt(CastOp, SZ->getType());
7173 break;
7174 }
7175 case scTruncate: {
7176 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7177 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7178 return ConstantExpr::getTrunc(CastOp, ST->getType());
7179 break;
7180 }
7181 case scAddExpr: {
7182 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7183 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007184 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7185 unsigned AS = PTy->getAddressSpace();
7186 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7187 C = ConstantExpr::getBitCast(C, DestPtrTy);
7188 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00007189 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7190 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00007191 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007192
7193 // First pointer!
7194 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007195 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00007196 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007197 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007198 // The offsets have been converted to bytes. We can add bytes to an
7199 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007200 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007201 }
7202
7203 // Don't bother trying to sum two pointers. We probably can't
7204 // statically compute a load that results from it anyway.
7205 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00007206 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007207
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00007208 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7209 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00007210 C2 = ConstantExpr::getIntegerCast(
7211 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00007212 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007213 } else
7214 C = ConstantExpr::getAdd(C, C2);
7215 }
7216 return C;
7217 }
7218 break;
7219 }
7220 case scMulExpr: {
7221 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7222 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7223 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00007224 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007225 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7226 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00007227 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007228 C = ConstantExpr::getMul(C, C2);
7229 }
7230 return C;
7231 }
7232 break;
7233 }
7234 case scUDivExpr: {
7235 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7236 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7237 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7238 if (LHS->getType() == RHS->getType())
7239 return ConstantExpr::getUDiv(LHS, RHS);
7240 break;
7241 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00007242 case scSMaxExpr:
7243 case scUMaxExpr:
7244 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00007245 }
Craig Topper9f008862014-04-15 04:59:12 +00007246 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00007247}
7248
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00007249const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007250 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00007251
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007252 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00007253 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00007254 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007255 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007256 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00007257 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
7258 if (PHINode *PN = dyn_cast<PHINode>(I))
7259 if (PN->getParent() == LI->getHeader()) {
7260 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00007261 // to see if the loop that contains it has a known backedge-taken
7262 // count. If so, we may be able to force computation of the exit
7263 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00007264 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00007265 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00007266 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007267 // Okay, we know how many times the containing loop executes. If
7268 // this is a constant evolving PHI node, get the final value at
7269 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007270 Constant *RV =
7271 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00007272 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00007273 }
7274 }
7275
Reid Spencere6328ca2006-12-04 21:33:23 +00007276 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00007277 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00007278 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00007279 // result. This is particularly useful for computing loop exit values.
7280 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007281 SmallVector<Constant *, 4> Operands;
7282 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00007283 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00007284 if (Constant *C = dyn_cast<Constant>(Op)) {
7285 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007286 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00007287 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007288
7289 // If any of the operands is non-constant and if they are
7290 // non-integer and non-pointer, don't even try to analyze them
7291 // with scev techniques.
7292 if (!isSCEVable(Op->getType()))
7293 return V;
7294
7295 const SCEV *OrigV = getSCEV(Op);
7296 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7297 MadeImprovement |= OrigV != OpV;
7298
Nick Lewyckya6674c72011-10-22 19:58:20 +00007299 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007300 if (!C) return V;
7301 if (C->getType() != Op->getType())
7302 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7303 Op->getType(),
7304 false),
7305 C, Op->getType());
7306 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00007307 }
Dan Gohmance973df2009-06-24 04:48:43 +00007308
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007309 // Check to see if getSCEVAtScope actually made an improvement.
7310 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00007311 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00007312 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007313 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00007314 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007315 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007316 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7317 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00007318 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007319 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00007320 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007321 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00007322 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007323 }
Chris Lattnerdd730472004-04-17 22:58:41 +00007324 }
7325 }
7326
7327 // This is some other type of SCEVUnknown, just return it.
7328 return V;
7329 }
7330
Dan Gohmana30370b2009-05-04 22:02:23 +00007331 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007332 // Avoid performing the look-up in the common case where the specified
7333 // expression has no loop-variant portions.
7334 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007335 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007336 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007337 // Okay, at least one of these operands is loop variant but might be
7338 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00007339 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7340 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00007341 NewOps.push_back(OpAtScope);
7342
7343 for (++i; i != e; ++i) {
7344 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007345 NewOps.push_back(OpAtScope);
7346 }
7347 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007348 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007349 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007350 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007351 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007352 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007353 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007354 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00007355 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007356 }
7357 }
7358 // If we got here, all operands are loop invariant.
7359 return Comm;
7360 }
7361
Dan Gohmana30370b2009-05-04 22:02:23 +00007362 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007363 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7364 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00007365 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7366 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00007367 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00007368 }
7369
7370 // If this is a loop recurrence for a loop that does not contain L, then we
7371 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00007372 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007373 // First, attempt to evaluate each operand.
7374 // Avoid performing the look-up in the common case where the specified
7375 // expression has no loop-variant portions.
7376 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7377 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7378 if (OpAtScope == AddRec->getOperand(i))
7379 continue;
7380
7381 // Okay, at least one of these operands is loop variant but might be
7382 // foldable. Build a new instance of the folded commutative expression.
7383 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7384 AddRec->op_begin()+i);
7385 NewOps.push_back(OpAtScope);
7386 for (++i; i != e; ++i)
7387 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7388
Andrew Trick759ba082011-04-27 01:21:25 +00007389 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00007390 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00007391 AddRec->getNoWrapFlags(SCEV::FlagNW));
7392 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00007393 // The addrec may be folded to a nonrecurrence, for example, if the
7394 // induction variable is multiplied by zero after constant folding. Go
7395 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00007396 if (!AddRec)
7397 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007398 break;
7399 }
7400
7401 // If the scope is outside the addrec's loop, evaluate it by using the
7402 // loop exit value of the addrec.
7403 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007404 // To evaluate this recurrence, we need to know how many times the AddRec
7405 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00007406 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007407 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00007408
Eli Friedman61f67622008-08-04 23:49:06 +00007409 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007410 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007411 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007412
Dan Gohman8ca08852009-05-24 23:25:42 +00007413 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007414 }
7415
Dan Gohmana30370b2009-05-04 22:02:23 +00007416 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007417 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007418 if (Op == Cast->getOperand())
7419 return Cast; // must be loop invariant
7420 return getZeroExtendExpr(Op, Cast->getType());
7421 }
7422
Dan Gohmana30370b2009-05-04 22:02:23 +00007423 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007424 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007425 if (Op == Cast->getOperand())
7426 return Cast; // must be loop invariant
7427 return getSignExtendExpr(Op, Cast->getType());
7428 }
7429
Dan Gohmana30370b2009-05-04 22:02:23 +00007430 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007431 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007432 if (Op == Cast->getOperand())
7433 return Cast; // must be loop invariant
7434 return getTruncateExpr(Op, Cast->getType());
7435 }
7436
Torok Edwinfbcc6632009-07-14 16:55:14 +00007437 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007438}
7439
Dan Gohmanaf752342009-07-07 17:06:11 +00007440const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007441 return getSCEVAtScope(getSCEV(V), L);
7442}
7443
Sanjoy Dasf8570812016-05-29 00:38:22 +00007444/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007445///
7446/// A * X = B (mod N)
7447///
7448/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7449/// A and B isn't important.
7450///
7451/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007452static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007453 ScalarEvolution &SE) {
7454 uint32_t BW = A.getBitWidth();
Eli Friedman10d1ff62017-01-31 00:42:42 +00007455 assert(BW == SE.getTypeSizeInBits(B->getType()));
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007456 assert(A != 0 && "A must be non-zero.");
7457
7458 // 1. D = gcd(A, N)
7459 //
7460 // The gcd of A and N may have only one prime factor: 2. The number of
7461 // trailing zeros in A is its multiplicity
7462 uint32_t Mult2 = A.countTrailingZeros();
7463 // D = 2^Mult2
7464
7465 // 2. Check if B is divisible by D.
7466 //
7467 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7468 // is not less than multiplicity of this prime factor for D.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007469 if (SE.GetMinTrailingZeros(B) < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007470 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007471
7472 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7473 // modulo (N / D).
7474 //
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007475 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7476 // (N / D) in general. The inverse itself always fits into BW bits, though,
7477 // so we immediately truncate it.
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007478 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7479 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007480 Mod.setBit(BW - Mult2); // Mod = N / D
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007481 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007482
7483 // 4. Compute the minimum unsigned root of the equation:
7484 // I * (B / D) mod (N / D)
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007485 // To simplify the computation, we factor out the divide by D:
7486 // (I * B mod N) / D
Eli Friedman10d1ff62017-01-31 00:42:42 +00007487 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7488 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007489}
Chris Lattnerd934c702004-04-02 20:23:17 +00007490
Sanjoy Dasf8570812016-05-29 00:38:22 +00007491/// Find the roots of the quadratic equation for the given quadratic chrec
7492/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7493/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007494///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007495static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007496SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007497 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007498 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7499 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7500 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007501
Chris Lattnerd934c702004-04-02 20:23:17 +00007502 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007503 if (!LC || !MC || !NC)
7504 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007505
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007506 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7507 const APInt &L = LC->getAPInt();
7508 const APInt &M = MC->getAPInt();
7509 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007510 APInt Two(BitWidth, 2);
Misha Brukman01808ca2005-04-21 21:13:18 +00007511
Craig Topper6694a4e2017-05-11 06:48:51 +00007512 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Misha Brukman01808ca2005-04-21 21:13:18 +00007513
Craig Topper6694a4e2017-05-11 06:48:51 +00007514 // The A coefficient is N/2
Craig Topper716cad82017-05-15 18:14:16 +00007515 APInt A = N.sdiv(Two);
Chris Lattnerd934c702004-04-02 20:23:17 +00007516
Craig Toppere3e1a352017-05-11 06:48:54 +00007517 // The B coefficient is M-N/2
Craig Topper716cad82017-05-15 18:14:16 +00007518 APInt B = M;
Craig Toppere3e1a352017-05-11 06:48:54 +00007519 B -= A; // A is the same as N/2.
7520
7521 // The C coefficient is L.
7522 const APInt& C = L;
7523
Craig Topper6694a4e2017-05-11 06:48:51 +00007524 // Compute the B^2-4ac term.
Craig Topper716cad82017-05-15 18:14:16 +00007525 APInt SqrtTerm = B;
Craig Topper6694a4e2017-05-11 06:48:51 +00007526 SqrtTerm *= B;
7527 SqrtTerm -= 4 * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007528
Craig Topper6694a4e2017-05-11 06:48:51 +00007529 if (SqrtTerm.isNegative()) {
7530 // The loop is provably infinite.
7531 return None;
7532 }
Nick Lewyckyfb780832012-08-01 09:14:36 +00007533
Craig Topper6694a4e2017-05-11 06:48:51 +00007534 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7535 // integer value or else APInt::sqrt() will assert.
Craig Topper716cad82017-05-15 18:14:16 +00007536 APInt SqrtVal = SqrtTerm.sqrt();
Misha Brukman01808ca2005-04-21 21:13:18 +00007537
Craig Topper6694a4e2017-05-11 06:48:51 +00007538 // Compute the two solutions for the quadratic formula.
7539 // The divisions must be performed as signed divisions.
Craig Topper716cad82017-05-15 18:14:16 +00007540 APInt NegB = -std::move(B);
7541 APInt TwoA = std::move(A);
Craig Toppere3e1a352017-05-11 06:48:54 +00007542 TwoA <<= 1;
7543 if (TwoA.isNullValue())
Craig Topper6694a4e2017-05-11 06:48:51 +00007544 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007545
Craig Topper6694a4e2017-05-11 06:48:51 +00007546 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007547
Craig Topper6694a4e2017-05-11 06:48:51 +00007548 ConstantInt *Solution1 =
7549 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7550 ConstantInt *Solution2 =
7551 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007552
Craig Topper6694a4e2017-05-11 06:48:51 +00007553 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7554 cast<SCEVConstant>(SE.getConstant(Solution2)));
Chris Lattnerd934c702004-04-02 20:23:17 +00007555}
7556
Andrew Trick3ca3f982011-07-26 17:19:55 +00007557ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007558ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007559 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007560
7561 // This is only used for loops with a "x != y" exit test. The exit condition
7562 // is now expressed as a single expression, V = x-y. So the exit test is
7563 // effectively V != 0. We know and take advantage of the fact that this
7564 // expression only being used in a comparison by zero context.
7565
Sanjoy Dasf0022122016-09-28 17:14:58 +00007566 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007567 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007568 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007569 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007570 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007571 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007572 }
7573
Dan Gohman48f82222009-05-04 22:30:44 +00007574 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007575 if (!AddRec && AllowPredicates)
7576 // Try to make this an AddRec using runtime tests, in the first X
7577 // iterations of this loop, where X is the SCEV expression found by the
7578 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007579 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007580
Chris Lattnerd934c702004-04-02 20:23:17 +00007581 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007582 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007583
Chris Lattnerdff679f2011-01-09 22:39:48 +00007584 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7585 // the quadratic equation to solve it.
7586 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007587 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7588 const SCEVConstant *R1 = Roots->first;
7589 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007590 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007591 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7592 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007593 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007594 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007595
Chris Lattnerd934c702004-04-02 20:23:17 +00007596 // We can only use this value if the chrec ends up with an exact zero
7597 // value at this index. When solving for "X*X != 5", for example, we
7598 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007599 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007600 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007601 // We found a quadratic root!
7602 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007603 }
7604 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007605 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007606 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007607
Chris Lattnerdff679f2011-01-09 22:39:48 +00007608 // Otherwise we can only handle this if it is affine.
7609 if (!AddRec->isAffine())
7610 return getCouldNotCompute();
7611
7612 // If this is an affine expression, the execution count of this branch is
7613 // the minimum unsigned root of the following equation:
7614 //
7615 // Start + Step*N = 0 (mod 2^BW)
7616 //
7617 // equivalent to:
7618 //
7619 // Step*N = -Start (mod 2^BW)
7620 //
7621 // where BW is the common bit width of Start and Step.
7622
7623 // Get the initial value for the loop.
7624 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7625 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7626
7627 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007628 //
7629 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7630 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7631 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7632 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007633 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007634 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007635 return getCouldNotCompute();
7636
Andrew Trick8b55b732011-03-14 16:50:06 +00007637 // For positive steps (counting up until unsigned overflow):
7638 // N = -Start/Step (as unsigned)
7639 // For negative steps (counting down to zero):
7640 // N = Start/-Step
7641 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007642 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007643 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007644
7645 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007646 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7647 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007648 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
Craig Topper01020392017-06-24 23:34:50 +00007649 APInt MaxBECount = getUnsignedRangeMax(Distance);
Eli Friedmanbd6deda2017-01-11 21:07:15 +00007650
7651 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7652 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7653 // case, and see if we can improve the bound.
7654 //
7655 // Explicitly handling this here is necessary because getUnsignedRange
7656 // isn't context-sensitive; it doesn't know that we only care about the
7657 // range inside the loop.
7658 const SCEV *Zero = getZero(Distance->getType());
7659 const SCEV *One = getOne(Distance->getType());
7660 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7661 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7662 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7663 // as "unsigned_max(Distance + 1) - 1".
7664 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7665 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7666 }
Eli Friedman83962652017-01-11 20:55:48 +00007667 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007668 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007669
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007670 // If the condition controls loop exit (the loop exits only if the expression
7671 // is true) and the addition is no-wrap we can use unsigned divide to
7672 // compute the backedge count. In this case, the step may not divide the
7673 // distance, but we don't care because if the condition is "missed" the loop
7674 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007675 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7676 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007677 const SCEV *Exact =
7678 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Sanjoy Das036dda22017-05-22 06:46:04 +00007679 const SCEV *Max =
7680 Exact == getCouldNotCompute()
7681 ? Exact
Craig Topper01020392017-06-24 23:34:50 +00007682 : getConstant(getUnsignedRangeMax(Exact));
Sanjoy Das036dda22017-05-22 06:46:04 +00007683 return ExitLimit(Exact, Max, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007684 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007685
Eli Friedman10d1ff62017-01-31 00:42:42 +00007686 // Solve the general equation.
Sanjoy Das036dda22017-05-22 06:46:04 +00007687 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
7688 getNegativeSCEV(Start), *this);
7689 const SCEV *M = E == getCouldNotCompute()
7690 ? E
Craig Topper01020392017-06-24 23:34:50 +00007691 : getConstant(getUnsignedRangeMax(E));
Sanjoy Das036dda22017-05-22 06:46:04 +00007692 return ExitLimit(E, M, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007693}
7694
Andrew Trick3ca3f982011-07-26 17:19:55 +00007695ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007696ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007697 // Loops that look like: while (X == 0) are very strange indeed. We don't
7698 // handle them yet except for the trivial case. This could be expanded in the
7699 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007700
Chris Lattnerd934c702004-04-02 20:23:17 +00007701 // If the value is a constant, check to see if it is known to be non-zero
7702 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007703 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007704 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007705 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007706 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007707 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007708
Chris Lattnerd934c702004-04-02 20:23:17 +00007709 // We could implement others, but I really doubt anyone writes loops like
7710 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007711 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007712}
7713
Dan Gohman4e3c1132010-04-15 16:19:08 +00007714std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007715ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007716 // If the block has a unique predecessor, then there is no path from the
7717 // predecessor to the block that does not go through the direct edge
7718 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007719 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007720 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007721
7722 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007723 // If the header has a unique predecessor outside the loop, it must be
7724 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007725 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007726 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007727
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007728 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007729}
7730
Sanjoy Dasf8570812016-05-29 00:38:22 +00007731/// SCEV structural equivalence is usually sufficient for testing whether two
7732/// expressions are equal, however for the purposes of looking for a condition
7733/// guarding a loop, it can be useful to be a little more general, since a
7734/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007735///
Dan Gohmanaf752342009-07-07 17:06:11 +00007736static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007737 // Quick check to see if they are the same SCEV.
7738 if (A == B) return true;
7739
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007740 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7741 // Not all instructions that are "identical" compute the same value. For
7742 // instance, two distinct alloca instructions allocating the same type are
7743 // identical and do not read memory; but compute distinct values.
7744 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7745 };
7746
Dan Gohman450f4e02009-06-20 00:35:32 +00007747 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7748 // two different instructions with the same value. Check for this case.
7749 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7750 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7751 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7752 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007753 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007754 return true;
7755
7756 // Otherwise assume they may have a different value.
7757 return false;
7758}
7759
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007760bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007761 const SCEV *&LHS, const SCEV *&RHS,
7762 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007763 bool Changed = false;
7764
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007765 // If we hit the max recursion limit bail out.
7766 if (Depth >= 3)
7767 return false;
7768
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007769 // Canonicalize a constant to the right side.
7770 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7771 // Check for both operands constant.
7772 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7773 if (ConstantExpr::getICmp(Pred,
7774 LHSC->getValue(),
7775 RHSC->getValue())->isNullValue())
7776 goto trivially_false;
7777 else
7778 goto trivially_true;
7779 }
7780 // Otherwise swap the operands to put the constant on the right.
7781 std::swap(LHS, RHS);
7782 Pred = ICmpInst::getSwappedPredicate(Pred);
7783 Changed = true;
7784 }
7785
7786 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007787 // addrec's loop, put the addrec on the left. Also make a dominance check,
7788 // as both operands could be addrecs loop-invariant in each other's loop.
7789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7790 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007791 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007792 std::swap(LHS, RHS);
7793 Pred = ICmpInst::getSwappedPredicate(Pred);
7794 Changed = true;
7795 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007796 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007797
7798 // If there's a constant operand, canonicalize comparisons with boundary
7799 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7800 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007801 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007802
7803 bool SimplifiedByConstantRange = false;
7804
7805 if (!ICmpInst::isEquality(Pred)) {
7806 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7807 if (ExactCR.isFullSet())
7808 goto trivially_true;
7809 else if (ExactCR.isEmptySet())
7810 goto trivially_false;
7811
7812 APInt NewRHS;
7813 CmpInst::Predicate NewPred;
7814 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7815 ICmpInst::isEquality(NewPred)) {
7816 // We were able to convert an inequality to an equality.
7817 Pred = NewPred;
7818 RHS = getConstant(NewRHS);
7819 Changed = SimplifiedByConstantRange = true;
7820 }
7821 }
7822
7823 if (!SimplifiedByConstantRange) {
7824 switch (Pred) {
7825 default:
7826 break;
7827 case ICmpInst::ICMP_EQ:
7828 case ICmpInst::ICMP_NE:
7829 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7830 if (!RA)
7831 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7832 if (const SCEVMulExpr *ME =
7833 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7834 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7835 ME->getOperand(0)->isAllOnesValue()) {
7836 RHS = AE->getOperand(1);
7837 LHS = ME->getOperand(1);
7838 Changed = true;
7839 }
7840 break;
7841
7842
7843 // The "Should have been caught earlier!" messages refer to the fact
7844 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7845 // should have fired on the corresponding cases, and canonicalized the
7846 // check to trivially_true or trivially_false.
7847
7848 case ICmpInst::ICMP_UGE:
7849 assert(!RA.isMinValue() && "Should have been caught earlier!");
7850 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007851 RHS = getConstant(RA - 1);
7852 Changed = true;
7853 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007854 case ICmpInst::ICMP_ULE:
7855 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7856 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007857 RHS = getConstant(RA + 1);
7858 Changed = true;
7859 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007860 case ICmpInst::ICMP_SGE:
7861 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7862 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007863 RHS = getConstant(RA - 1);
7864 Changed = true;
7865 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007866 case ICmpInst::ICMP_SLE:
7867 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7868 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007869 RHS = getConstant(RA + 1);
7870 Changed = true;
7871 break;
7872 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007873 }
7874 }
7875
7876 // Check for obvious equality.
7877 if (HasSameValue(LHS, RHS)) {
7878 if (ICmpInst::isTrueWhenEqual(Pred))
7879 goto trivially_true;
7880 if (ICmpInst::isFalseWhenEqual(Pred))
7881 goto trivially_false;
7882 }
7883
Dan Gohman81585c12010-05-03 16:35:17 +00007884 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7885 // adding or subtracting 1 from one of the operands.
7886 switch (Pred) {
7887 case ICmpInst::ICMP_SLE:
Craig Topper01020392017-06-24 23:34:50 +00007888 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
Dan Gohman81585c12010-05-03 16:35:17 +00007889 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007890 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007891 Pred = ICmpInst::ICMP_SLT;
7892 Changed = true;
Craig Topper01020392017-06-24 23:34:50 +00007893 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007894 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007895 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007896 Pred = ICmpInst::ICMP_SLT;
7897 Changed = true;
7898 }
7899 break;
7900 case ICmpInst::ICMP_SGE:
Craig Topper01020392017-06-24 23:34:50 +00007901 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007902 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007903 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007904 Pred = ICmpInst::ICMP_SGT;
7905 Changed = true;
Craig Topper01020392017-06-24 23:34:50 +00007906 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
Dan Gohman81585c12010-05-03 16:35:17 +00007907 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007908 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007909 Pred = ICmpInst::ICMP_SGT;
7910 Changed = true;
7911 }
7912 break;
7913 case ICmpInst::ICMP_ULE:
Craig Topper01020392017-06-24 23:34:50 +00007914 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007915 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007916 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007917 Pred = ICmpInst::ICMP_ULT;
7918 Changed = true;
Craig Topper01020392017-06-24 23:34:50 +00007919 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007920 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007921 Pred = ICmpInst::ICMP_ULT;
7922 Changed = true;
7923 }
7924 break;
7925 case ICmpInst::ICMP_UGE:
Craig Topper01020392017-06-24 23:34:50 +00007926 if (!getUnsignedRangeMin(RHS).isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007927 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007928 Pred = ICmpInst::ICMP_UGT;
7929 Changed = true;
Craig Topper01020392017-06-24 23:34:50 +00007930 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007931 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007932 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007933 Pred = ICmpInst::ICMP_UGT;
7934 Changed = true;
7935 }
7936 break;
7937 default:
7938 break;
7939 }
7940
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007941 // TODO: More simplifications are possible here.
7942
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007943 // Recursively simplify until we either hit a recursion limit or nothing
7944 // changes.
7945 if (Changed)
7946 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7947
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007948 return Changed;
7949
7950trivially_true:
7951 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007952 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007953 Pred = ICmpInst::ICMP_EQ;
7954 return true;
7955
7956trivially_false:
7957 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007958 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007959 Pred = ICmpInst::ICMP_NE;
7960 return true;
7961}
7962
Dan Gohmane65c9172009-07-13 21:35:55 +00007963bool ScalarEvolution::isKnownNegative(const SCEV *S) {
Craig Topper01020392017-06-24 23:34:50 +00007964 return getSignedRangeMax(S).isNegative();
Dan Gohmane65c9172009-07-13 21:35:55 +00007965}
7966
7967bool ScalarEvolution::isKnownPositive(const SCEV *S) {
Craig Topper01020392017-06-24 23:34:50 +00007968 return getSignedRangeMin(S).isStrictlyPositive();
Dan Gohmane65c9172009-07-13 21:35:55 +00007969}
7970
7971bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
Craig Topper01020392017-06-24 23:34:50 +00007972 return !getSignedRangeMin(S).isNegative();
Dan Gohmane65c9172009-07-13 21:35:55 +00007973}
7974
7975bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
Craig Topper01020392017-06-24 23:34:50 +00007976 return !getSignedRangeMax(S).isStrictlyPositive();
Dan Gohmane65c9172009-07-13 21:35:55 +00007977}
7978
7979bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7980 return isKnownNegative(S) || isKnownPositive(S);
7981}
7982
7983bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7984 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007985 // Canonicalize the inputs first.
7986 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7987
Dan Gohman07591692010-04-11 22:16:48 +00007988 // If LHS or RHS is an addrec, check to see if the condition is true in
7989 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007990 // If LHS and RHS are both addrec, both conditions must be true in
7991 // every iteration of the loop.
7992 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7993 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7994 bool LeftGuarded = false;
7995 bool RightGuarded = false;
7996 if (LAR) {
7997 const Loop *L = LAR->getLoop();
7998 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7999 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8000 if (!RAR) return true;
8001 LeftGuarded = true;
8002 }
8003 }
8004 if (RAR) {
8005 const Loop *L = RAR->getLoop();
8006 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8007 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8008 if (!LAR) return true;
8009 RightGuarded = true;
8010 }
8011 }
8012 if (LeftGuarded && RightGuarded)
8013 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00008014
Sanjoy Das7d910f22015-10-02 18:50:30 +00008015 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8016 return true;
8017
Dan Gohman07591692010-04-11 22:16:48 +00008018 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00008019 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00008020}
8021
Sanjoy Das5dab2052015-07-27 21:42:49 +00008022bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8023 ICmpInst::Predicate Pred,
8024 bool &Increasing) {
8025 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8026
8027#ifndef NDEBUG
8028 // Verify an invariant: inverting the predicate should turn a monotonically
8029 // increasing change to a monotonically decreasing one, and vice versa.
8030 bool IncreasingSwapped;
8031 bool ResultSwapped = isMonotonicPredicateImpl(
8032 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8033
8034 assert(Result == ResultSwapped && "should be able to analyze both!");
8035 if (ResultSwapped)
8036 assert(Increasing == !IncreasingSwapped &&
8037 "monotonicity should flip as we flip the predicate");
8038#endif
8039
8040 return Result;
8041}
8042
8043bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8044 ICmpInst::Predicate Pred,
8045 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00008046
8047 // A zero step value for LHS means the induction variable is essentially a
8048 // loop invariant value. We don't really depend on the predicate actually
8049 // flipping from false to true (for increasing predicates, and the other way
8050 // around for decreasing predicates), all we care about is that *if* the
8051 // predicate changes then it only changes from false to true.
8052 //
8053 // A zero step value in itself is not very useful, but there may be places
8054 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8055 // as general as possible.
8056
Sanjoy Das366acc12015-08-06 20:43:41 +00008057 switch (Pred) {
8058 default:
8059 return false; // Conservative answer
8060
8061 case ICmpInst::ICMP_UGT:
8062 case ICmpInst::ICMP_UGE:
8063 case ICmpInst::ICMP_ULT:
8064 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00008065 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00008066 return false;
8067
8068 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00008069 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00008070
8071 case ICmpInst::ICMP_SGT:
8072 case ICmpInst::ICMP_SGE:
8073 case ICmpInst::ICMP_SLT:
8074 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00008075 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00008076 return false;
8077
8078 const SCEV *Step = LHS->getStepRecurrence(*this);
8079
8080 if (isKnownNonNegative(Step)) {
8081 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8082 return true;
8083 }
8084
8085 if (isKnownNonPositive(Step)) {
8086 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8087 return true;
8088 }
8089
8090 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00008091 }
8092
Sanjoy Das5dab2052015-07-27 21:42:49 +00008093 }
8094
Sanjoy Das366acc12015-08-06 20:43:41 +00008095 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00008096}
8097
8098bool ScalarEvolution::isLoopInvariantPredicate(
8099 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8100 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8101 const SCEV *&InvariantRHS) {
8102
8103 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8104 if (!isLoopInvariant(RHS, L)) {
8105 if (!isLoopInvariant(LHS, L))
8106 return false;
8107
8108 std::swap(LHS, RHS);
8109 Pred = ICmpInst::getSwappedPredicate(Pred);
8110 }
8111
8112 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8113 if (!ArLHS || ArLHS->getLoop() != L)
8114 return false;
8115
8116 bool Increasing;
8117 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8118 return false;
8119
8120 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8121 // true as the loop iterates, and the backedge is control dependent on
8122 // "ArLHS `Pred` RHS" == true then we can reason as follows:
8123 //
8124 // * if the predicate was false in the first iteration then the predicate
8125 // is never evaluated again, since the loop exits without taking the
8126 // backedge.
8127 // * if the predicate was true in the first iteration then it will
8128 // continue to be true for all future iterations since it is
8129 // monotonically increasing.
8130 //
8131 // For both the above possibilities, we can replace the loop varying
8132 // predicate with its value on the first iteration of the loop (which is
8133 // loop invariant).
8134 //
8135 // A similar reasoning applies for a monotonically decreasing predicate, by
8136 // replacing true with false and false with true in the above two bullets.
8137
8138 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8139
8140 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8141 return false;
8142
8143 InvariantPred = Pred;
8144 InvariantLHS = ArLHS->getStart();
8145 InvariantRHS = RHS;
8146 return true;
8147}
8148
Sanjoy Das401e6312016-02-01 20:48:10 +00008149bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8150 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008151 if (HasSameValue(LHS, RHS))
8152 return ICmpInst::isTrueWhenEqual(Pred);
8153
Dan Gohman07591692010-04-11 22:16:48 +00008154 // This code is split out from isKnownPredicate because it is called from
8155 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00008156
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00008157 auto CheckRanges =
8158 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8159 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8160 .contains(RangeLHS);
8161 };
8162
8163 // The check at the top of the function catches the case where the values are
8164 // known to be equal.
8165 if (Pred == CmpInst::ICMP_EQ)
8166 return false;
8167
8168 if (Pred == CmpInst::ICMP_NE)
8169 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8170 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8171 isKnownNonZero(getMinusSCEV(LHS, RHS));
8172
8173 if (CmpInst::isSigned(Pred))
8174 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8175
8176 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00008177}
8178
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008179bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8180 const SCEV *LHS,
8181 const SCEV *RHS) {
8182
8183 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8184 // Return Y via OutY.
8185 auto MatchBinaryAddToConst =
8186 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8187 SCEV::NoWrapFlags ExpectedFlags) {
8188 const SCEV *NonConstOp, *ConstOp;
8189 SCEV::NoWrapFlags FlagsPresent;
8190
8191 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8192 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8193 return false;
8194
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008195 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008196 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8197 };
8198
8199 APInt C;
8200
8201 switch (Pred) {
8202 default:
8203 break;
8204
8205 case ICmpInst::ICMP_SGE:
8206 std::swap(LHS, RHS);
Galina Kistanova8514dd52017-05-31 22:09:46 +00008207 LLVM_FALLTHROUGH;
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008208 case ICmpInst::ICMP_SLE:
8209 // X s<= (X + C)<nsw> if C >= 0
8210 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8211 return true;
8212
8213 // (X + C)<nsw> s<= X if C <= 0
8214 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8215 !C.isStrictlyPositive())
8216 return true;
8217 break;
8218
8219 case ICmpInst::ICMP_SGT:
8220 std::swap(LHS, RHS);
Galina Kistanova8514dd52017-05-31 22:09:46 +00008221 LLVM_FALLTHROUGH;
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008222 case ICmpInst::ICMP_SLT:
8223 // X s< (X + C)<nsw> if C > 0
8224 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8225 C.isStrictlyPositive())
8226 return true;
8227
8228 // (X + C)<nsw> s< X if C < 0
8229 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8230 return true;
8231 break;
8232 }
8233
8234 return false;
8235}
8236
Sanjoy Das7d910f22015-10-02 18:50:30 +00008237bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8238 const SCEV *LHS,
8239 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00008240 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00008241 return false;
8242
8243 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8244 // the stack can result in exponential time complexity.
8245 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8246
8247 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8248 //
8249 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8250 // isKnownPredicate. isKnownPredicate is more powerful, but also more
8251 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8252 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
8253 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00008254 return isKnownNonNegative(RHS) &&
8255 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8256 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00008257}
8258
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008259bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8260 ICmpInst::Predicate Pred,
8261 const SCEV *LHS, const SCEV *RHS) {
8262 // No need to even try if we know the module has no guards.
8263 if (!HasGuards)
8264 return false;
8265
8266 return any_of(*BB, [&](Instruction &I) {
8267 using namespace llvm::PatternMatch;
8268
8269 Value *Condition;
8270 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8271 m_Value(Condition))) &&
8272 isImpliedCond(Pred, LHS, RHS, Condition, false);
8273 });
8274}
8275
Dan Gohmane65c9172009-07-13 21:35:55 +00008276/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8277/// protected by a conditional between LHS and RHS. This is used to
8278/// to eliminate casts.
8279bool
8280ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8281 ICmpInst::Predicate Pred,
8282 const SCEV *LHS, const SCEV *RHS) {
8283 // Interpret a null as meaning no loop, where there is obviously no guard
8284 // (interprocedural conditions notwithstanding).
8285 if (!L) return true;
8286
Sanjoy Das401e6312016-02-01 20:48:10 +00008287 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8288 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008289
Dan Gohmane65c9172009-07-13 21:35:55 +00008290 BasicBlock *Latch = L->getLoopLatch();
8291 if (!Latch)
8292 return false;
8293
8294 BranchInst *LoopContinuePredicate =
8295 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008296 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8297 isImpliedCond(Pred, LHS, RHS,
8298 LoopContinuePredicate->getCondition(),
8299 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8300 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00008301
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008302 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008303 // -- that can lead to O(n!) time complexity.
8304 if (WalkingBEDominatingConds)
8305 return false;
8306
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00008307 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008308
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00008309 // See if we can exploit a trip count to prove the predicate.
8310 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8311 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8312 if (LatchBECount != getCouldNotCompute()) {
8313 // We know that Latch branches back to the loop header exactly
8314 // LatchBECount times. This means the backdege condition at Latch is
8315 // equivalent to "{0,+,1} u< LatchBECount".
8316 Type *Ty = LatchBECount->getType();
8317 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8318 const SCEV *LoopCounter =
8319 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8320 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8321 LatchBECount))
8322 return true;
8323 }
8324
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008325 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008326 for (auto &AssumeVH : AC.assumptions()) {
8327 if (!AssumeVH)
8328 continue;
8329 auto *CI = cast<CallInst>(AssumeVH);
8330 if (!DT.dominates(CI, Latch->getTerminator()))
8331 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008332
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008333 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8334 return true;
8335 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008336
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008337 // If the loop is not reachable from the entry block, we risk running into an
8338 // infinite loop as we walk up into the dom tree. These loops do not matter
8339 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008340 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008341 return false;
8342
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008343 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8344 return true;
8345
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008346 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8347 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008348
8349 assert(DTN && "should reach the loop header before reaching the root!");
8350
8351 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008352 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8353 return true;
8354
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008355 BasicBlock *PBB = BB->getSinglePredecessor();
8356 if (!PBB)
8357 continue;
8358
8359 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8360 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8361 continue;
8362
8363 Value *Condition = ContinuePredicate->getCondition();
8364
8365 // If we have an edge `E` within the loop body that dominates the only
8366 // latch, the condition guarding `E` also guards the backedge. This
8367 // reasoning works only for loops with a single latch.
8368
8369 BasicBlockEdge DominatingEdge(PBB, BB);
8370 if (DominatingEdge.isSingleEdge()) {
8371 // We're constructively (and conservatively) enumerating edges within the
8372 // loop body that dominate the latch. The dominator tree better agree
8373 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008374 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008375
8376 if (isImpliedCond(Pred, LHS, RHS, Condition,
8377 BB != ContinuePredicate->getSuccessor(0)))
8378 return true;
8379 }
8380 }
8381
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008382 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008383}
8384
Dan Gohmane65c9172009-07-13 21:35:55 +00008385bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008386ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8387 ICmpInst::Predicate Pred,
8388 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008389 // Interpret a null as meaning no loop, where there is obviously no guard
8390 // (interprocedural conditions notwithstanding).
8391 if (!L) return false;
8392
Sanjoy Das401e6312016-02-01 20:48:10 +00008393 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8394 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008395
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008396 // Starting at the loop predecessor, climb up the predecessor chain, as long
8397 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008398 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008399 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008400 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008401 Pair.first;
8402 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008403
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008404 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8405 return true;
8406
Dan Gohman2a62fd92008-08-12 20:17:31 +00008407 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008408 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008409 if (!LoopEntryPredicate ||
8410 LoopEntryPredicate->isUnconditional())
8411 continue;
8412
Dan Gohmane18c2d62010-08-10 23:46:30 +00008413 if (isImpliedCond(Pred, LHS, RHS,
8414 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008415 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008416 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008417 }
8418
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008419 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008420 for (auto &AssumeVH : AC.assumptions()) {
8421 if (!AssumeVH)
8422 continue;
8423 auto *CI = cast<CallInst>(AssumeVH);
8424 if (!DT.dominates(CI, L->getHeader()))
8425 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008426
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008427 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8428 return true;
8429 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008430
Dan Gohman2a62fd92008-08-12 20:17:31 +00008431 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008432}
8433
Dan Gohmane18c2d62010-08-10 23:46:30 +00008434bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008435 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008436 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008437 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008438 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008439 return false;
8440
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008441 auto ClearOnExit =
8442 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8443
Dan Gohman8b0a4192010-03-01 17:49:51 +00008444 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008446 if (BO->getOpcode() == Instruction::And) {
8447 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008448 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8449 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008450 } else if (BO->getOpcode() == Instruction::Or) {
8451 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008452 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8453 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008454 }
8455 }
8456
Dan Gohmane18c2d62010-08-10 23:46:30 +00008457 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008458 if (!ICI) return false;
8459
Andrew Trickfa594032012-11-29 18:35:13 +00008460 // Now that we found a conditional branch that dominates the loop or controls
8461 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008462 ICmpInst::Predicate FoundPred;
8463 if (Inverse)
8464 FoundPred = ICI->getInversePredicate();
8465 else
8466 FoundPred = ICI->getPredicate();
8467
8468 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8469 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008470
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008471 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8472}
8473
8474bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8475 const SCEV *RHS,
8476 ICmpInst::Predicate FoundPred,
8477 const SCEV *FoundLHS,
8478 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008479 // Balance the types.
8480 if (getTypeSizeInBits(LHS->getType()) <
8481 getTypeSizeInBits(FoundLHS->getType())) {
8482 if (CmpInst::isSigned(Pred)) {
8483 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8484 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8485 } else {
8486 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8487 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8488 }
8489 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008490 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008491 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008492 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8493 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8494 } else {
8495 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8496 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8497 }
8498 }
8499
Dan Gohman430f0cc2009-07-21 23:03:19 +00008500 // Canonicalize the query to match the way instcombine will have
8501 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008502 if (SimplifyICmpOperands(Pred, LHS, RHS))
8503 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008504 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008505 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8506 if (FoundLHS == FoundRHS)
8507 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008508
8509 // Check to see if we can make the LHS or RHS match.
8510 if (LHS == FoundRHS || RHS == FoundLHS) {
8511 if (isa<SCEVConstant>(RHS)) {
8512 std::swap(FoundLHS, FoundRHS);
8513 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8514 } else {
8515 std::swap(LHS, RHS);
8516 Pred = ICmpInst::getSwappedPredicate(Pred);
8517 }
8518 }
8519
8520 // Check whether the found predicate is the same as the desired predicate.
8521 if (FoundPred == Pred)
8522 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8523
8524 // Check whether swapping the found predicate makes it the same as the
8525 // desired predicate.
8526 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8527 if (isa<SCEVConstant>(RHS))
8528 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8529 else
8530 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8531 RHS, LHS, FoundLHS, FoundRHS);
8532 }
8533
Sanjoy Das6e78b172015-10-22 19:57:34 +00008534 // Unsigned comparison is the same as signed comparison when both the operands
8535 // are non-negative.
8536 if (CmpInst::isUnsigned(FoundPred) &&
8537 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8538 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8539 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8540
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008541 // Check if we can make progress by sharpening ranges.
8542 if (FoundPred == ICmpInst::ICMP_NE &&
8543 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8544
8545 const SCEVConstant *C = nullptr;
8546 const SCEV *V = nullptr;
8547
8548 if (isa<SCEVConstant>(FoundLHS)) {
8549 C = cast<SCEVConstant>(FoundLHS);
8550 V = FoundRHS;
8551 } else {
8552 C = cast<SCEVConstant>(FoundRHS);
8553 V = FoundLHS;
8554 }
8555
8556 // The guarding predicate tells us that C != V. If the known range
8557 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8558 // range we consider has to correspond to same signedness as the
8559 // predicate we're interested in folding.
8560
8561 APInt Min = ICmpInst::isSigned(Pred) ?
Craig Topper01020392017-06-24 23:34:50 +00008562 getSignedRangeMin(V) : getUnsignedRangeMin(V);
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008563
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008564 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008565 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8566 // This is true even if (Min + 1) wraps around -- in case of
8567 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8568
8569 APInt SharperMin = Min + 1;
8570
8571 switch (Pred) {
8572 case ICmpInst::ICMP_SGE:
8573 case ICmpInst::ICMP_UGE:
8574 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8575 // RHS, we're done.
8576 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8577 getConstant(SharperMin)))
8578 return true;
Galina Kistanova8514dd52017-05-31 22:09:46 +00008579 LLVM_FALLTHROUGH;
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008580
8581 case ICmpInst::ICMP_SGT:
8582 case ICmpInst::ICMP_UGT:
8583 // We know from the range information that (V `Pred` Min ||
8584 // V == Min). We know from the guarding condition that !(V
8585 // == Min). This gives us
8586 //
8587 // V `Pred` Min || V == Min && !(V == Min)
8588 // => V `Pred` Min
8589 //
8590 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8591
8592 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8593 return true;
Galina Kistanova8514dd52017-05-31 22:09:46 +00008594 LLVM_FALLTHROUGH;
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008595
8596 default:
8597 // No change
8598 break;
8599 }
8600 }
8601 }
8602
Dan Gohman430f0cc2009-07-21 23:03:19 +00008603 // Check whether the actual condition is beyond sufficient.
8604 if (FoundPred == ICmpInst::ICMP_EQ)
8605 if (ICmpInst::isTrueWhenEqual(Pred))
8606 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8607 return true;
8608 if (Pred == ICmpInst::ICMP_NE)
8609 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8610 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8611 return true;
8612
8613 // Otherwise assume the worst.
8614 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008615}
8616
Sanjoy Das1ed69102015-10-13 02:53:27 +00008617bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8618 const SCEV *&L, const SCEV *&R,
8619 SCEV::NoWrapFlags &Flags) {
8620 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8621 if (!AE || AE->getNumOperands() != 2)
8622 return false;
8623
8624 L = AE->getOperand(0);
8625 R = AE->getOperand(1);
8626 Flags = AE->getNoWrapFlags();
8627 return true;
8628}
8629
Sanjoy Das0b1af852016-07-23 00:28:56 +00008630Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8631 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008632 // We avoid subtracting expressions here because this function is usually
8633 // fairly deep in the call stack (i.e. is called many times).
8634
Sanjoy Das96709c42015-09-25 23:53:45 +00008635 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8636 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8637 const auto *MAR = cast<SCEVAddRecExpr>(More);
8638
8639 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008640 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008641
8642 // We look at affine expressions only; not for correctness but to keep
8643 // getStepRecurrence cheap.
8644 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008645 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008646
Sanjoy Das1ed69102015-10-13 02:53:27 +00008647 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008648 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008649
8650 Less = LAR->getStart();
8651 More = MAR->getStart();
8652
8653 // fall through
8654 }
8655
8656 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008657 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8658 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008659 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008660 }
8661
8662 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008663 SCEV::NoWrapFlags Flags;
8664 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008665 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008666 if (R == More)
8667 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008668
Sanjoy Das1ed69102015-10-13 02:53:27 +00008669 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008670 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008671 if (R == Less)
8672 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008673
Sanjoy Das0b1af852016-07-23 00:28:56 +00008674 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008675}
8676
8677bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8678 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8679 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8680 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8681 return false;
8682
8683 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8684 if (!AddRecLHS)
8685 return false;
8686
8687 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8688 if (!AddRecFoundLHS)
8689 return false;
8690
8691 // We'd like to let SCEV reason about control dependencies, so we constrain
8692 // both the inequalities to be about add recurrences on the same loop. This
8693 // way we can use isLoopEntryGuardedByCond later.
8694
8695 const Loop *L = AddRecFoundLHS->getLoop();
8696 if (L != AddRecLHS->getLoop())
8697 return false;
8698
8699 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8700 //
8701 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8702 // ... (2)
8703 //
8704 // Informal proof for (2), assuming (1) [*]:
8705 //
8706 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8707 //
8708 // Then
8709 //
8710 // FoundLHS s< FoundRHS s< INT_MIN - C
8711 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8712 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8713 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8714 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8715 // <=> FoundLHS + C s< FoundRHS + C
8716 //
8717 // [*]: (1) can be proved by ruling out overflow.
8718 //
8719 // [**]: This can be proved by analyzing all the four possibilities:
8720 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8721 // (A s>= 0, B s>= 0).
8722 //
8723 // Note:
8724 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8725 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8726 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8727 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8728 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8729 // C)".
8730
Sanjoy Das0b1af852016-07-23 00:28:56 +00008731 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8732 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8733 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008734 return false;
8735
Sanjoy Das0b1af852016-07-23 00:28:56 +00008736 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008737 return true;
8738
Sanjoy Das96709c42015-09-25 23:53:45 +00008739 APInt FoundRHSLimit;
8740
8741 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008742 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008743 } else {
8744 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008745 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008746 }
8747
8748 // Try to prove (1) or (2), as needed.
8749 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8750 getConstant(FoundRHSLimit));
8751}
8752
Dan Gohman430f0cc2009-07-21 23:03:19 +00008753bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8754 const SCEV *LHS, const SCEV *RHS,
8755 const SCEV *FoundLHS,
8756 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008757 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8758 return true;
8759
Sanjoy Das96709c42015-09-25 23:53:45 +00008760 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8761 return true;
8762
Dan Gohman430f0cc2009-07-21 23:03:19 +00008763 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8764 FoundLHS, FoundRHS) ||
8765 // ~x < ~y --> x > y
8766 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8767 getNotSCEV(FoundRHS),
8768 getNotSCEV(FoundLHS));
8769}
8770
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008771
8772/// If Expr computes ~A, return A else return nullptr
8773static const SCEV *MatchNotExpr(const SCEV *Expr) {
8774 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008775 if (!Add || Add->getNumOperands() != 2 ||
8776 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008777 return nullptr;
8778
8779 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008780 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8781 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008782 return nullptr;
8783
8784 return AddRHS->getOperand(1);
8785}
8786
8787
8788/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8789template<typename MaxExprType>
8790static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8791 const SCEV *Candidate) {
8792 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8793 if (!MaxExpr) return false;
8794
Sanjoy Das347d2722015-12-01 07:49:27 +00008795 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008796}
8797
8798
8799/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8800template<typename MaxExprType>
8801static bool IsMinConsistingOf(ScalarEvolution &SE,
8802 const SCEV *MaybeMinExpr,
8803 const SCEV *Candidate) {
8804 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8805 if (!MaybeMaxExpr)
8806 return false;
8807
8808 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8809}
8810
Hal Finkela8d205f2015-08-19 01:51:51 +00008811static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8812 ICmpInst::Predicate Pred,
8813 const SCEV *LHS, const SCEV *RHS) {
8814
8815 // If both sides are affine addrecs for the same loop, with equal
8816 // steps, and we know the recurrences don't wrap, then we only
8817 // need to check the predicate on the starting values.
8818
8819 if (!ICmpInst::isRelational(Pred))
8820 return false;
8821
8822 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8823 if (!LAR)
8824 return false;
8825 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8826 if (!RAR)
8827 return false;
8828 if (LAR->getLoop() != RAR->getLoop())
8829 return false;
8830 if (!LAR->isAffine() || !RAR->isAffine())
8831 return false;
8832
8833 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8834 return false;
8835
Hal Finkelff08a2e2015-08-19 17:26:07 +00008836 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8837 SCEV::FlagNSW : SCEV::FlagNUW;
8838 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008839 return false;
8840
8841 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8842}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008843
8844/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8845/// expression?
8846static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8847 ICmpInst::Predicate Pred,
8848 const SCEV *LHS, const SCEV *RHS) {
8849 switch (Pred) {
8850 default:
8851 return false;
8852
8853 case ICmpInst::ICMP_SGE:
8854 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008855 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008856 case ICmpInst::ICMP_SLE:
8857 return
8858 // min(A, ...) <= A
8859 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8860 // A <= max(A, ...)
8861 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8862
8863 case ICmpInst::ICMP_UGE:
8864 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008865 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008866 case ICmpInst::ICMP_ULE:
8867 return
8868 // min(A, ...) <= A
8869 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8870 // A <= max(A, ...)
8871 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8872 }
8873
8874 llvm_unreachable("covered switch fell through?!");
8875}
8876
Max Kazantsev2e44d292017-03-31 12:05:30 +00008877bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8878 const SCEV *LHS, const SCEV *RHS,
8879 const SCEV *FoundLHS,
8880 const SCEV *FoundRHS,
8881 unsigned Depth) {
8882 assert(getTypeSizeInBits(LHS->getType()) ==
8883 getTypeSizeInBits(RHS->getType()) &&
8884 "LHS and RHS have different sizes?");
8885 assert(getTypeSizeInBits(FoundLHS->getType()) ==
8886 getTypeSizeInBits(FoundRHS->getType()) &&
8887 "FoundLHS and FoundRHS have different sizes?");
8888 // We want to avoid hurting the compile time with analysis of too big trees.
8889 if (Depth > MaxSCEVOperationsImplicationDepth)
8890 return false;
8891 // We only want to work with ICMP_SGT comparison so far.
8892 // TODO: Extend to ICMP_UGT?
8893 if (Pred == ICmpInst::ICMP_SLT) {
8894 Pred = ICmpInst::ICMP_SGT;
8895 std::swap(LHS, RHS);
8896 std::swap(FoundLHS, FoundRHS);
8897 }
8898 if (Pred != ICmpInst::ICMP_SGT)
8899 return false;
8900
8901 auto GetOpFromSExt = [&](const SCEV *S) {
8902 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8903 return Ext->getOperand();
8904 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8905 // the constant in some cases.
8906 return S;
8907 };
8908
8909 // Acquire values from extensions.
8910 auto *OrigFoundLHS = FoundLHS;
8911 LHS = GetOpFromSExt(LHS);
8912 FoundLHS = GetOpFromSExt(FoundLHS);
8913
8914 // Is the SGT predicate can be proved trivially or using the found context.
8915 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8916 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8917 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8918 FoundRHS, Depth + 1);
8919 };
8920
8921 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8922 // We want to avoid creation of any new non-constant SCEV. Since we are
8923 // going to compare the operands to RHS, we should be certain that we don't
8924 // need any size extensions for this. So let's decline all cases when the
8925 // sizes of types of LHS and RHS do not match.
8926 // TODO: Maybe try to get RHS from sext to catch more cases?
8927 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8928 return false;
8929
8930 // Should not overflow.
8931 if (!LHSAddExpr->hasNoSignedWrap())
8932 return false;
8933
8934 auto *LL = LHSAddExpr->getOperand(0);
8935 auto *LR = LHSAddExpr->getOperand(1);
8936 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8937
8938 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8939 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8940 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8941 };
8942 // Try to prove the following rule:
8943 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8944 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8945 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8946 return true;
8947 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8948 Value *LL, *LR;
8949 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8950 using namespace llvm::PatternMatch;
8951 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8952 // Rules for division.
8953 // We are going to perform some comparisons with Denominator and its
8954 // derivative expressions. In general case, creating a SCEV for it may
8955 // lead to a complex analysis of the entire graph, and in particular it
8956 // can request trip count recalculation for the same loop. This would
8957 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8958 // this, we only want to create SCEVs that are constants in this section.
8959 // So we bail if Denominator is not a constant.
8960 if (!isa<ConstantInt>(LR))
8961 return false;
8962
8963 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8964
8965 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8966 // then a SCEV for the numerator already exists and matches with FoundLHS.
8967 auto *Numerator = getExistingSCEV(LL);
8968 if (!Numerator || Numerator->getType() != FoundLHS->getType())
8969 return false;
8970
8971 // Make sure that the numerator matches with FoundLHS and the denominator
8972 // is positive.
8973 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8974 return false;
8975
8976 auto *DTy = Denominator->getType();
8977 auto *FRHSTy = FoundRHS->getType();
8978 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8979 // One of types is a pointer and another one is not. We cannot extend
8980 // them properly to a wider type, so let us just reject this case.
8981 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8982 // to avoid this check.
8983 return false;
8984
8985 // Given that:
8986 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8987 auto *WTy = getWiderType(DTy, FRHSTy);
8988 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8989 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8990
8991 // Try to prove the following rule:
8992 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8993 // For example, given that FoundLHS > 2. It means that FoundLHS is at
8994 // least 3. If we divide it by Denominator < 4, we will have at least 1.
8995 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8996 if (isKnownNonPositive(RHS) &&
8997 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8998 return true;
8999
9000 // Try to prove the following rule:
9001 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9002 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9003 // If we divide it by Denominator > 2, then:
9004 // 1. If FoundLHS is negative, then the result is 0.
9005 // 2. If FoundLHS is non-negative, then the result is non-negative.
9006 // Anyways, the result is non-negative.
9007 auto *MinusOne = getNegativeSCEV(getOne(WTy));
9008 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9009 if (isKnownNegative(RHS) &&
9010 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9011 return true;
9012 }
9013 }
9014
9015 return false;
9016}
9017
9018bool
9019ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9020 const SCEV *LHS, const SCEV *RHS) {
9021 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9022 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9023 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9024 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9025}
9026
Dan Gohmane65c9172009-07-13 21:35:55 +00009027bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00009028ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9029 const SCEV *LHS, const SCEV *RHS,
9030 const SCEV *FoundLHS,
9031 const SCEV *FoundRHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00009032 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00009033 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9034 case ICmpInst::ICMP_EQ:
9035 case ICmpInst::ICMP_NE:
9036 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9037 return true;
9038 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00009039 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00009040 case ICmpInst::ICMP_SLE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00009041 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9042 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00009043 return true;
9044 break;
9045 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00009046 case ICmpInst::ICMP_SGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00009047 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9048 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00009049 return true;
9050 break;
9051 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00009052 case ICmpInst::ICMP_ULE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00009053 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9054 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00009055 return true;
9056 break;
9057 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00009058 case ICmpInst::ICMP_UGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00009059 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9060 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00009061 return true;
9062 break;
9063 }
9064
Max Kazantsev2e44d292017-03-31 12:05:30 +00009065 // Maybe it can be proved via operations?
9066 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9067 return true;
9068
Dan Gohmane65c9172009-07-13 21:35:55 +00009069 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00009070}
9071
Sanjoy Dascb8bca12015-03-18 00:41:29 +00009072bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9073 const SCEV *LHS,
9074 const SCEV *RHS,
9075 const SCEV *FoundLHS,
9076 const SCEV *FoundRHS) {
9077 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9078 // The restriction on `FoundRHS` be lifted easily -- it exists only to
9079 // reduce the compile time impact of this optimization.
9080 return false;
9081
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00009082 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00009083 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00009084 return false;
9085
Craig Topper8f26b792017-05-06 05:15:09 +00009086 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00009087
9088 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9089 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9090 ConstantRange FoundLHSRange =
9091 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9092
Sanjoy Das095f5b22016-07-22 20:47:55 +00009093 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9094 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00009095
9096 // We can also compute the range of values for `LHS` that satisfy the
9097 // consequent, "`LHS` `Pred` `RHS`":
Craig Topper8f26b792017-05-06 05:15:09 +00009098 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00009099 ConstantRange SatisfyingLHSRange =
9100 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9101
9102 // The antecedent implies the consequent if every value of `LHS` that
9103 // satisfies the antecedent also satisfies the consequent.
9104 return SatisfyingLHSRange.contains(LHSRange);
9105}
9106
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009107bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9108 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009109 assert(isKnownPositive(Stride) && "Positive stride expected!");
9110
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009111 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00009112
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009113 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009114 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00009115
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009116 if (IsSigned) {
Craig Topper01020392017-06-24 23:34:50 +00009117 APInt MaxRHS = getSignedRangeMax(RHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009118 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
Craig Topper01020392017-06-24 23:34:50 +00009119 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
Andrew Trick2afa3252011-03-09 17:29:58 +00009120
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009121 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
Craig Topperef869ec2017-05-08 17:39:01 +00009122 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00009123 }
Dan Gohman01048422009-06-21 23:46:38 +00009124
Craig Topper01020392017-06-24 23:34:50 +00009125 APInt MaxRHS = getUnsignedRangeMax(RHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009126 APInt MaxValue = APInt::getMaxValue(BitWidth);
Craig Topper01020392017-06-24 23:34:50 +00009127 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009128
9129 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
Craig Topperef869ec2017-05-08 17:39:01 +00009130 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009131}
9132
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009133bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9134 bool IsSigned, bool NoWrap) {
9135 if (NoWrap) return false;
9136
9137 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009138 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009139
9140 if (IsSigned) {
Craig Topper01020392017-06-24 23:34:50 +00009141 APInt MinRHS = getSignedRangeMin(RHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009142 APInt MinValue = APInt::getSignedMinValue(BitWidth);
Craig Topper01020392017-06-24 23:34:50 +00009143 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009144
9145 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
Craig Topperef869ec2017-05-08 17:39:01 +00009146 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009147 }
9148
Craig Topper01020392017-06-24 23:34:50 +00009149 APInt MinRHS = getUnsignedRangeMin(RHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009150 APInt MinValue = APInt::getMinValue(BitWidth);
Craig Topper01020392017-06-24 23:34:50 +00009151 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009152
9153 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
Craig Topperef869ec2017-05-08 17:39:01 +00009154 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009155}
9156
Johannes Doerfert2683e562015-02-09 12:34:23 +00009157const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009158 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009159 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009160 Delta = Equality ? getAddExpr(Delta, Step)
9161 : getAddExpr(Delta, getMinusSCEV(Step, One));
9162 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00009163}
9164
Andrew Trick3ca3f982011-07-26 17:19:55 +00009165ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00009166ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009167 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00009168 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00009169 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009170 // We handle only IV < Invariant
9171 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00009172 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00009173
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009174 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009175 bool PredicatedIV = false;
9176
9177 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00009178 // Try to make this an AddRec using runtime tests, in the first X
9179 // iterations of this loop, where X is the SCEV expression found by the
9180 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00009181 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009182 PredicatedIV = true;
9183 }
Dan Gohman2b8da352009-04-30 20:47:05 +00009184
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009185 // Avoid weird loops
9186 if (!IV || IV->getLoop() != L || !IV->isAffine())
9187 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00009188
Mark Heffernan2beab5f2014-10-10 17:39:11 +00009189 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009190 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00009191
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009192 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00009193
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009194 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00009195
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009196 // Avoid negative or zero stride values.
9197 if (!PositiveStride) {
9198 // We can compute the correct backedge taken count for loops with unknown
9199 // strides if we can prove that the loop is not an infinite loop with side
9200 // effects. Here's the loop structure we are trying to handle -
9201 //
9202 // i = start
9203 // do {
9204 // A[i] = i;
9205 // i += s;
9206 // } while (i < end);
9207 //
9208 // The backedge taken count for such loops is evaluated as -
9209 // (max(end, start + stride) - start - 1) /u stride
9210 //
9211 // The additional preconditions that we need to check to prove correctness
9212 // of the above formula is as follows -
9213 //
9214 // a) IV is either nuw or nsw depending upon signedness (indicated by the
9215 // NoWrap flag).
9216 // b) loop is single exit with no side effects.
9217 //
9218 //
9219 // Precondition a) implies that if the stride is negative, this is a single
9220 // trip loop. The backedge taken count formula reduces to zero in this case.
9221 //
9222 // Precondition b) implies that the unknown stride cannot be zero otherwise
9223 // we have UB.
9224 //
9225 // The positive stride case is the same as isKnownPositive(Stride) returning
9226 // true (original behavior of the function).
9227 //
9228 // We want to make sure that the stride is truly unknown as there are edge
9229 // cases where ScalarEvolution propagates no wrap flags to the
9230 // post-increment/decrement IV even though the increment/decrement operation
9231 // itself is wrapping. The computed backedge taken count may be wrong in
9232 // such cases. This is prevented by checking that the stride is not known to
9233 // be either positive or non-positive. For example, no wrap flags are
9234 // propagated to the post-increment IV of this loop with a trip count of 2 -
9235 //
9236 // unsigned char i;
9237 // for(i=127; i<128; i+=129)
9238 // A[i] = i;
9239 //
9240 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9241 !loopHasNoSideEffects(L))
9242 return getCouldNotCompute();
9243
9244 } else if (!Stride->isOne() &&
9245 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9246 // Avoid proven overflow cases: this will ensure that the backedge taken
9247 // count will not generate any unsigned overflow. Relaxed no-overflow
9248 // conditions exploit NoWrapFlags, allowing to optimize in presence of
9249 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009250 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00009251
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009252 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9253 : ICmpInst::ICMP_ULT;
9254 const SCEV *Start = IV->getStart();
9255 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00009256 // If the backedge is taken at least once, then it will be taken
9257 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9258 // is the LHS value of the less-than comparison the first time it is evaluated
9259 // and End is the RHS.
9260 const SCEV *BECountIfBackedgeTaken =
9261 computeBECount(getMinusSCEV(End, Start), Stride, false);
9262 // If the loop entry is guarded by the result of the backedge test of the
9263 // first loop iteration, then we know the backedge will be taken at least
9264 // once and so the backedge taken count is as above. If not then we use the
9265 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9266 // as if the backedge is taken at least once max(End,Start) is End and so the
9267 // result is as above, and if not max(End,Start) is Start so we get a backedge
9268 // count of zero.
9269 const SCEV *BECount;
9270 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9271 BECount = BECountIfBackedgeTaken;
9272 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00009273 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00009274 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9275 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009276
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00009277 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00009278 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009279 if (isa<SCEVConstant>(BECount))
9280 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00009281 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00009282 // If we know exactly how many times the backedge will be taken if it's
9283 // taken at least once, then the backedge count will either be that or
9284 // zero.
9285 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00009286 MaxOrZero = true;
9287 } else {
John Brawnecf79302016-10-18 10:10:53 +00009288 // Calculate the maximum backedge count based on the range of values
9289 // permitted by Start, End, and Stride.
Craig Topper01020392017-06-24 23:34:50 +00009290 APInt MinStart = IsSigned ? getSignedRangeMin(Start)
9291 : getUnsignedRangeMin(Start);
John Brawnecf79302016-10-18 10:10:53 +00009292
9293 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9294
9295 APInt StrideForMaxBECount;
9296
9297 if (PositiveStride)
9298 StrideForMaxBECount =
Craig Topper01020392017-06-24 23:34:50 +00009299 IsSigned ? getSignedRangeMin(Stride)
9300 : getUnsignedRangeMin(Stride);
John Brawnecf79302016-10-18 10:10:53 +00009301 else
9302 // Using a stride of 1 is safe when computing max backedge taken count for
9303 // a loop with unknown stride.
9304 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9305
9306 APInt Limit =
9307 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9308 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9309
9310 // Although End can be a MAX expression we estimate MaxEnd considering only
9311 // the case End = RHS. This is safe because in the other case (End - Start)
9312 // is zero, leading to a zero maximum backedge taken count.
9313 APInt MaxEnd =
Craig Topper01020392017-06-24 23:34:50 +00009314 IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit)
9315 : APIntOps::umin(getUnsignedRangeMax(RHS), Limit);
John Brawnecf79302016-10-18 10:10:53 +00009316
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009317 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009318 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00009319 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009320
Sanjoy Das036dda22017-05-22 06:46:04 +00009321 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9322 !isa<SCEVCouldNotCompute>(BECount))
Craig Topper01020392017-06-24 23:34:50 +00009323 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009324
John Brawn84b21832016-10-21 11:08:48 +00009325 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009326}
9327
9328ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00009329ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009330 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00009331 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00009332 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009333 // We handle only IV > Invariant
9334 if (!isLoopInvariant(RHS, L))
9335 return getCouldNotCompute();
9336
9337 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00009338 if (!IV && AllowPredicates)
9339 // Try to make this an AddRec using runtime tests, in the first X
9340 // iterations of this loop, where X is the SCEV expression found by the
9341 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00009342 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009343
9344 // Avoid weird loops
9345 if (!IV || IV->getLoop() != L || !IV->isAffine())
9346 return getCouldNotCompute();
9347
Mark Heffernan2beab5f2014-10-10 17:39:11 +00009348 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009349 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9350
9351 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9352
9353 // Avoid negative or zero stride values
9354 if (!isKnownPositive(Stride))
9355 return getCouldNotCompute();
9356
9357 // Avoid proven overflow cases: this will ensure that the backedge taken count
9358 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00009359 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009360 // behaviors like the case of C language.
9361 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9362 return getCouldNotCompute();
9363
9364 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9365 : ICmpInst::ICMP_UGT;
9366
9367 const SCEV *Start = IV->getStart();
9368 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00009369 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9370 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009371
9372 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9373
Craig Topper01020392017-06-24 23:34:50 +00009374 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
9375 : getUnsignedRangeMax(Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009376
Craig Topper01020392017-06-24 23:34:50 +00009377 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
9378 : getUnsignedRangeMin(Stride);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009379
9380 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9381 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9382 : APInt::getMinValue(BitWidth) + (MinStride - 1);
9383
9384 // Although End can be a MIN expression we estimate MinEnd considering only
9385 // the case End = RHS. This is safe because in the other case (Start - End)
9386 // is zero, leading to a zero maximum backedge taken count.
9387 APInt MinEnd =
Craig Topper01020392017-06-24 23:34:50 +00009388 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
9389 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009390
9391
9392 const SCEV *MaxBECount = getCouldNotCompute();
9393 if (isa<SCEVConstant>(BECount))
9394 MaxBECount = BECount;
9395 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00009396 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009397 getConstant(MinStride), false);
9398
9399 if (isa<SCEVCouldNotCompute>(MaxBECount))
9400 MaxBECount = BECount;
9401
John Brawn84b21832016-10-21 11:08:48 +00009402 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00009403}
9404
Benjamin Kramerc321e532016-06-08 19:09:22 +00009405const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00009406 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00009407 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00009408 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009409
9410 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00009411 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00009412 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00009413 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009414 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00009415 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00009416 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00009417 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00009418 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009419 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00009420 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00009421 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009422 }
9423
9424 // The only time we can solve this is when we have all constant indices.
9425 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00009426 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00009427 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009428
9429 // Okay at this point we know that all elements of the chrec are constants and
9430 // that the start element is zero.
9431
9432 // First check to see if the range contains zero. If not, the first
9433 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00009434 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00009435 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009436 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00009437
Chris Lattnerd934c702004-04-02 20:23:17 +00009438 if (isAffine()) {
9439 // If this is an affine expression then we have this situation:
9440 // Solve {0,+,A} in Range === Ax in Range
9441
Nick Lewycky52460262007-07-16 02:08:00 +00009442 // We know that zero is in the range. If A is positive then we know that
9443 // the upper value of the range must be the first possible exit value.
9444 // If A is negative then the lower of the range is the last possible loop
9445 // value. Also note that we already checked for a full range.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009446 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Craig Topperc97fdb82017-05-06 05:15:11 +00009447 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00009448
Nick Lewycky52460262007-07-16 02:08:00 +00009449 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00009450 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00009451 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00009452
9453 // Evaluate at the exit value. If we really did fall out of the valid
9454 // range, then we computed our trip count, otherwise wrap around or other
9455 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00009456 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009457 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00009458 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009459
9460 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00009461 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00009462 EvaluateConstantChrecAtConstant(this,
Craig Topperc97fdb82017-05-06 05:15:11 +00009463 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00009464 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00009465 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00009466 } else if (isQuadratic()) {
9467 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9468 // quadratic equation to solve it. To do this, we must frame our problem in
9469 // terms of figuring out when zero is crossed, instead of when
9470 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00009471 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00009472 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00009473 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00009474
9475 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00009476 if (auto Roots =
9477 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00009478 const SCEVConstant *R1 = Roots->first;
9479 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00009480 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00009481 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9482 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00009483 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00009484 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00009485
Chris Lattnerd934c702004-04-02 20:23:17 +00009486 // Make sure the root is not off by one. The returned iteration should
9487 // not be in the range, but the previous one should be. When solving
9488 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00009489 ConstantInt *R1Val =
9490 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009491 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009492 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009493 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009494 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009495
Dan Gohmana37eaf22007-10-22 18:31:58 +00009496 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009497 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009498 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00009499 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009500 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009501
Chris Lattnerd934c702004-04-02 20:23:17 +00009502 // If R1 was not in the range, then it is a good return value. Make
9503 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009504 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009505 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009506 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009507 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009508 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00009509 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009510 }
9511 }
9512 }
9513
Dan Gohman31efa302009-04-18 17:58:19 +00009514 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009515}
9516
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009517// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009518static inline bool containsUndefs(const SCEV *S) {
9519 return SCEVExprContains(S, [](const SCEV *S) {
9520 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9521 return isa<UndefValue>(SU->getValue());
9522 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9523 return isa<UndefValue>(SC->getValue());
9524 return false;
9525 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009526}
9527
9528namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009529// Collect all steps of SCEV expressions.
9530struct SCEVCollectStrides {
9531 ScalarEvolution &SE;
9532 SmallVectorImpl<const SCEV *> &Strides;
9533
9534 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9535 : SE(SE), Strides(S) {}
9536
9537 bool follow(const SCEV *S) {
9538 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9539 Strides.push_back(AR->getStepRecurrence(SE));
9540 return true;
9541 }
9542 bool isDone() const { return false; }
9543};
9544
9545// Collect all SCEVUnknown and SCEVMulExpr expressions.
9546struct SCEVCollectTerms {
9547 SmallVectorImpl<const SCEV *> &Terms;
9548
9549 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9550 : Terms(T) {}
9551
9552 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009553 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9554 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009555 if (!containsUndefs(S))
9556 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009557
9558 // Stop recursion: once we collected a term, do not walk its operands.
9559 return false;
9560 }
9561
9562 // Keep looking.
9563 return true;
9564 }
9565 bool isDone() const { return false; }
9566};
Tobias Grosser374bce02015-10-12 08:02:00 +00009567
9568// Check if a SCEV contains an AddRecExpr.
9569struct SCEVHasAddRec {
9570 bool &ContainsAddRec;
9571
9572 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9573 ContainsAddRec = false;
9574 }
9575
9576 bool follow(const SCEV *S) {
9577 if (isa<SCEVAddRecExpr>(S)) {
9578 ContainsAddRec = true;
9579
9580 // Stop recursion: once we collected a term, do not walk its operands.
9581 return false;
9582 }
9583
9584 // Keep looking.
9585 return true;
9586 }
9587 bool isDone() const { return false; }
9588};
9589
9590// Find factors that are multiplied with an expression that (possibly as a
9591// subexpression) contains an AddRecExpr. In the expression:
9592//
9593// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9594//
9595// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9596// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9597// parameters as they form a product with an induction variable.
9598//
9599// This collector expects all array size parameters to be in the same MulExpr.
9600// It might be necessary to later add support for collecting parameters that are
9601// spread over different nested MulExpr.
9602struct SCEVCollectAddRecMultiplies {
9603 SmallVectorImpl<const SCEV *> &Terms;
9604 ScalarEvolution &SE;
9605
9606 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9607 : Terms(T), SE(SE) {}
9608
9609 bool follow(const SCEV *S) {
9610 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9611 bool HasAddRec = false;
9612 SmallVector<const SCEV *, 0> Operands;
9613 for (auto Op : Mul->operands()) {
Tobias Grossere3684d02017-05-27 15:17:49 +00009614 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
9615 if (Unknown && !isa<CallInst>(Unknown->getValue())) {
Tobias Grosser374bce02015-10-12 08:02:00 +00009616 Operands.push_back(Op);
Tobias Grossere3684d02017-05-27 15:17:49 +00009617 } else if (Unknown) {
9618 HasAddRec = true;
Tobias Grosser374bce02015-10-12 08:02:00 +00009619 } else {
9620 bool ContainsAddRec;
9621 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9622 visitAll(Op, ContiansAddRec);
9623 HasAddRec |= ContainsAddRec;
9624 }
9625 }
9626 if (Operands.size() == 0)
9627 return true;
9628
9629 if (!HasAddRec)
9630 return false;
9631
9632 Terms.push_back(SE.getMulExpr(Operands));
9633 // Stop recursion: once we collected a term, do not walk its operands.
9634 return false;
9635 }
9636
9637 // Keep looking.
9638 return true;
9639 }
9640 bool isDone() const { return false; }
9641};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009642}
Sebastian Pop448712b2014-05-07 18:01:20 +00009643
Tobias Grosser374bce02015-10-12 08:02:00 +00009644/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9645/// two places:
9646/// 1) The strides of AddRec expressions.
9647/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009648void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9649 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009650 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009651 SCEVCollectStrides StrideCollector(*this, Strides);
9652 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009653
9654 DEBUG({
9655 dbgs() << "Strides:\n";
9656 for (const SCEV *S : Strides)
9657 dbgs() << *S << "\n";
9658 });
9659
9660 for (const SCEV *S : Strides) {
9661 SCEVCollectTerms TermCollector(Terms);
9662 visitAll(S, TermCollector);
9663 }
9664
9665 DEBUG({
9666 dbgs() << "Terms:\n";
9667 for (const SCEV *T : Terms)
9668 dbgs() << *T << "\n";
9669 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009670
9671 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9672 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009673}
9674
Sebastian Popb1a548f2014-05-12 19:01:53 +00009675static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009676 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009677 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009678 int Last = Terms.size() - 1;
9679 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009680
Sebastian Pop448712b2014-05-07 18:01:20 +00009681 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009682 if (Last == 0) {
9683 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009684 SmallVector<const SCEV *, 2> Qs;
9685 for (const SCEV *Op : M->operands())
9686 if (!isa<SCEVConstant>(Op))
9687 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009688
Sebastian Pope30bd352014-05-27 22:41:56 +00009689 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009690 }
9691
Sebastian Pope30bd352014-05-27 22:41:56 +00009692 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009693 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009694 }
9695
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009696 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009697 // Normalize the terms before the next call to findArrayDimensionsRec.
9698 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009699 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009700
9701 // Bail out when GCD does not evenly divide one of the terms.
9702 if (!R->isZero())
9703 return false;
9704
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009705 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009706 }
9707
Tobias Grosser3080cf12014-05-08 07:55:34 +00009708 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009709 Terms.erase(
9710 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9711 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009712
Sebastian Pop448712b2014-05-07 18:01:20 +00009713 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009714 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9715 return false;
9716
Sebastian Pope30bd352014-05-27 22:41:56 +00009717 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009718 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009719}
Sebastian Popc62c6792013-11-12 22:47:20 +00009720
Sebastian Pop448712b2014-05-07 18:01:20 +00009721
9722// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009723static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009724 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009725 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009726 return true;
9727 return false;
9728}
9729
9730// Return the number of product terms in S.
9731static inline int numberOfTerms(const SCEV *S) {
9732 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9733 return Expr->getNumOperands();
9734 return 1;
9735}
9736
Sebastian Popa6e58602014-05-27 22:41:45 +00009737static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9738 if (isa<SCEVConstant>(T))
9739 return nullptr;
9740
9741 if (isa<SCEVUnknown>(T))
9742 return T;
9743
9744 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9745 SmallVector<const SCEV *, 2> Factors;
9746 for (const SCEV *Op : M->operands())
9747 if (!isa<SCEVConstant>(Op))
9748 Factors.push_back(Op);
9749
9750 return SE.getMulExpr(Factors);
9751 }
9752
9753 return T;
9754}
9755
9756/// Return the size of an element read or written by Inst.
9757const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9758 Type *Ty;
9759 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9760 Ty = Store->getValueOperand()->getType();
9761 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009762 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009763 else
9764 return nullptr;
9765
9766 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9767 return getSizeOfExpr(ETy, Ty);
9768}
9769
Sebastian Popa6e58602014-05-27 22:41:45 +00009770void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9771 SmallVectorImpl<const SCEV *> &Sizes,
Sanjoy Dasdf8c2eb2017-05-07 05:29:36 +00009772 const SCEV *ElementSize) {
Sebastian Pop53524082014-05-29 19:44:05 +00009773 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009774 return;
9775
9776 // Early return when Terms do not contain parameters: we do not delinearize
9777 // non parametric SCEVs.
9778 if (!containsParameters(Terms))
9779 return;
9780
9781 DEBUG({
9782 dbgs() << "Terms:\n";
9783 for (const SCEV *T : Terms)
9784 dbgs() << *T << "\n";
9785 });
9786
9787 // Remove duplicates.
Sanjoy Das40415ee2017-05-07 05:29:34 +00009788 array_pod_sort(Terms.begin(), Terms.end());
Sebastian Pop448712b2014-05-07 18:01:20 +00009789 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9790
9791 // Put larger terms first.
9792 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9793 return numberOfTerms(LHS) > numberOfTerms(RHS);
9794 });
9795
Tobias Grosser374bce02015-10-12 08:02:00 +00009796 // Try to divide all terms by the element size. If term is not divisible by
9797 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009798 for (const SCEV *&Term : Terms) {
9799 const SCEV *Q, *R;
Sanjoy Dasdf8c2eb2017-05-07 05:29:36 +00009800 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009801 if (!Q->isZero())
9802 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009803 }
9804
9805 SmallVector<const SCEV *, 4> NewTerms;
9806
9807 // Remove constant factors.
9808 for (const SCEV *T : Terms)
Sanjoy Dasdf8c2eb2017-05-07 05:29:36 +00009809 if (const SCEV *NewT = removeConstantFactors(*this, T))
Sebastian Popa6e58602014-05-27 22:41:45 +00009810 NewTerms.push_back(NewT);
9811
Sebastian Pop448712b2014-05-07 18:01:20 +00009812 DEBUG({
9813 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009814 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009815 dbgs() << *T << "\n";
9816 });
9817
Sanjoy Dasdf8c2eb2017-05-07 05:29:36 +00009818 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009819 Sizes.clear();
9820 return;
9821 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009822
Sebastian Popa6e58602014-05-27 22:41:45 +00009823 // The last element to be pushed into Sizes is the size of an element.
9824 Sizes.push_back(ElementSize);
9825
Sebastian Pop448712b2014-05-07 18:01:20 +00009826 DEBUG({
9827 dbgs() << "Sizes:\n";
9828 for (const SCEV *S : Sizes)
9829 dbgs() << *S << "\n";
9830 });
9831}
9832
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009833void ScalarEvolution::computeAccessFunctions(
9834 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9835 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009836
Sebastian Popb1a548f2014-05-12 19:01:53 +00009837 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009838 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009839 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009840
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009841 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009842 if (!AR->isAffine())
9843 return;
9844
9845 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009846 int Last = Sizes.size() - 1;
9847 for (int i = Last; i >= 0; i--) {
9848 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009849 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009850
9851 DEBUG({
9852 dbgs() << "Res: " << *Res << "\n";
9853 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9854 dbgs() << "Res divided by Sizes[i]:\n";
9855 dbgs() << "Quotient: " << *Q << "\n";
9856 dbgs() << "Remainder: " << *R << "\n";
9857 });
9858
9859 Res = Q;
9860
Sebastian Popa6e58602014-05-27 22:41:45 +00009861 // Do not record the last subscript corresponding to the size of elements in
9862 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009863 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009864
9865 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009866 if (isa<SCEVAddRecExpr>(R)) {
9867 Subscripts.clear();
9868 Sizes.clear();
9869 return;
9870 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009871
Sebastian Pop448712b2014-05-07 18:01:20 +00009872 continue;
9873 }
9874
9875 // Record the access function for the current subscript.
9876 Subscripts.push_back(R);
9877 }
9878
9879 // Also push in last position the remainder of the last division: it will be
9880 // the access function of the innermost dimension.
9881 Subscripts.push_back(Res);
9882
9883 std::reverse(Subscripts.begin(), Subscripts.end());
9884
9885 DEBUG({
9886 dbgs() << "Subscripts:\n";
9887 for (const SCEV *S : Subscripts)
9888 dbgs() << *S << "\n";
9889 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009890}
9891
Sebastian Popc62c6792013-11-12 22:47:20 +00009892/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9893/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009894/// is the offset start of the array. The SCEV->delinearize algorithm computes
9895/// the multiples of SCEV coefficients: that is a pattern matching of sub
9896/// expressions in the stride and base of a SCEV corresponding to the
9897/// computation of a GCD (greatest common divisor) of base and stride. When
9898/// SCEV->delinearize fails, it returns the SCEV unchanged.
9899///
9900/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9901///
9902/// void foo(long n, long m, long o, double A[n][m][o]) {
9903///
9904/// for (long i = 0; i < n; i++)
9905/// for (long j = 0; j < m; j++)
9906/// for (long k = 0; k < o; k++)
9907/// A[i][j][k] = 1.0;
9908/// }
9909///
9910/// the delinearization input is the following AddRec SCEV:
9911///
9912/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9913///
9914/// From this SCEV, we are able to say that the base offset of the access is %A
9915/// because it appears as an offset that does not divide any of the strides in
9916/// the loops:
9917///
9918/// CHECK: Base offset: %A
9919///
9920/// and then SCEV->delinearize determines the size of some of the dimensions of
9921/// the array as these are the multiples by which the strides are happening:
9922///
9923/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9924///
9925/// Note that the outermost dimension remains of UnknownSize because there are
9926/// no strides that would help identifying the size of the last dimension: when
9927/// the array has been statically allocated, one could compute the size of that
9928/// dimension by dividing the overall size of the array by the size of the known
9929/// dimensions: %m * %o * 8.
9930///
9931/// Finally delinearize provides the access functions for the array reference
9932/// that does correspond to A[i][j][k] of the above C testcase:
9933///
9934/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9935///
9936/// The testcases are checking the output of a function pass:
9937/// DelinearizationPass that walks through all loads and stores of a function
9938/// asking for the SCEV of the memory access with respect to all enclosing
9939/// loops, calling SCEV->delinearize on that and printing the results.
9940
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009941void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009942 SmallVectorImpl<const SCEV *> &Subscripts,
9943 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009944 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009945 // First step: collect parametric terms.
9946 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009947 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009948
Sebastian Popb1a548f2014-05-12 19:01:53 +00009949 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009950 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009951
Sebastian Pop448712b2014-05-07 18:01:20 +00009952 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009953 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009954
Sebastian Popb1a548f2014-05-12 19:01:53 +00009955 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009956 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009957
Sebastian Pop448712b2014-05-07 18:01:20 +00009958 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009959 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009960
Sebastian Pop28e6b972014-05-27 22:41:51 +00009961 if (Subscripts.empty())
9962 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009963
Sebastian Pop448712b2014-05-07 18:01:20 +00009964 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009965 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009966 dbgs() << "ArrayDecl[UnknownSize]";
9967 for (const SCEV *S : Sizes)
9968 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009969
Sebastian Pop444621a2014-05-09 22:45:02 +00009970 dbgs() << "\nArrayRef";
9971 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009972 dbgs() << "[" << *S << "]";
9973 dbgs() << "\n";
9974 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009975}
Chris Lattnerd934c702004-04-02 20:23:17 +00009976
9977//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009978// SCEVCallbackVH Class Implementation
9979//===----------------------------------------------------------------------===//
9980
Dan Gohmand33a0902009-05-19 19:22:47 +00009981void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009982 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009983 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9984 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009985 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009986 // this now dangles!
9987}
9988
Dan Gohman7a066722010-07-28 01:09:07 +00009989void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009990 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009991
Dan Gohman48f82222009-05-04 22:30:44 +00009992 // Forget all the expressions associated with users of the old value,
9993 // so that future queries will recompute the expressions using the new
9994 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009995 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009996 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009997 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009998 while (!Worklist.empty()) {
9999 User *U = Worklist.pop_back_val();
10000 // Deleting the Old value will cause this to dangle. Postpone
10001 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +000010002 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +000010003 continue;
David Blaikie70573dc2014-11-19 07:49:26 +000010004 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +000010005 continue;
Dan Gohman48f82222009-05-04 22:30:44 +000010006 if (PHINode *PN = dyn_cast<PHINode>(U))
10007 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +000010008 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +000010009 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +000010010 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +000010011 // Delete the Old value.
10012 if (PHINode *PN = dyn_cast<PHINode>(Old))
10013 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +000010014 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +000010015 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +000010016}
10017
Dan Gohmand33a0902009-05-19 19:22:47 +000010018ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +000010019 : CallbackVH(V), SE(se) {}
10020
10021//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +000010022// ScalarEvolution Class Implementation
10023//===----------------------------------------------------------------------===//
10024
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010025ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010026 AssumptionCache &AC, DominatorTree &DT,
10027 LoopInfo &LI)
10028 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010029 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +000010030 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
10031 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +000010032 FirstUnknown(nullptr) {
10033
10034 // To use guards for proving predicates, we need to scan every instruction in
10035 // relevant basic blocks, and not just terminators. Doing this is a waste of
10036 // time if the IR does not actually contain any calls to
10037 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10038 //
10039 // This pessimizes the case where a pass that preserves ScalarEvolution wants
10040 // to _add_ guards to the module when there weren't any before, and wants
10041 // ScalarEvolution to optimize based on those guards. For now we prefer to be
10042 // efficient in lieu of being smart in that rather obscure case.
10043
10044 auto *GuardDecl = F.getParent()->getFunction(
10045 Intrinsic::getName(Intrinsic::experimental_guard));
10046 HasGuards = GuardDecl && !GuardDecl->use_empty();
10047}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010048
10049ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010050 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +000010051 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010052 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +000010053 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +000010054 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Igor Laevskyc11c1ed2017-02-14 15:53:12 +000010055 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010056 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +000010057 PredicatedBackedgeTakenCounts(
10058 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010059 ConstantEvolutionLoopExitValue(
10060 std::move(Arg.ConstantEvolutionLoopExitValue)),
10061 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10062 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +000010063 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +000010064 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010065 UnsignedRanges(std::move(Arg.UnsignedRanges)),
10066 SignedRanges(std::move(Arg.SignedRanges)),
10067 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +000010068 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010069 SCEVAllocator(std::move(Arg.SCEVAllocator)),
10070 FirstUnknown(Arg.FirstUnknown) {
10071 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +000010072}
10073
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010074ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +000010075 // Iterate through all the SCEVUnknown instances and call their
10076 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +000010077 for (SCEVUnknown *U = FirstUnknown; U;) {
10078 SCEVUnknown *Tmp = U;
10079 U = U->Next;
10080 Tmp->~SCEVUnknown();
10081 }
Craig Topper9f008862014-04-15 04:59:12 +000010082 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +000010083
Wei Mia49559b2016-02-04 01:27:38 +000010084 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +000010085 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +000010086 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +000010087
10088 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10089 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +000010090 for (auto &BTCI : BackedgeTakenCounts)
10091 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +000010092 for (auto &BTCI : PredicatedBackedgeTakenCounts)
10093 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +000010094
Andrew Trick7fa4e0f2012-05-19 00:48:25 +000010095 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +000010096 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +000010097 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +000010098}
10099
Dan Gohmanc8e23622009-04-21 23:15:49 +000010100bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +000010101 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +000010102}
10103
Dan Gohmanc8e23622009-04-21 23:15:49 +000010104static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +000010105 const Loop *L) {
10106 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +000010107 for (Loop *I : *L)
10108 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +000010109
Dan Gohmanbc694912010-01-09 18:17:45 +000010110 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +000010111 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +000010112 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +000010113
Dan Gohmancb0efec2009-12-18 01:14:11 +000010114 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +000010115 L->getExitBlocks(ExitBlocks);
10116 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +000010117 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +000010118
Dan Gohman0bddac12009-02-24 18:55:53 +000010119 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10120 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +000010121 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +000010122 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +000010123 }
10124
Dan Gohmanbc694912010-01-09 18:17:45 +000010125 OS << "\n"
10126 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +000010127 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +000010128 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +000010129
10130 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10131 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +000010132 if (SE->isBackedgeTakenCountMaxOrZero(L))
10133 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +000010134 } else {
10135 OS << "Unpredictable max backedge-taken count. ";
10136 }
10137
Silviu Baranga6f444df2016-04-08 14:29:09 +000010138 OS << "\n"
10139 "Loop ";
10140 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10141 OS << ": ";
10142
10143 SCEVUnionPredicate Pred;
10144 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10145 if (!isa<SCEVCouldNotCompute>(PBT)) {
10146 OS << "Predicated backedge-taken count is " << *PBT << "\n";
10147 OS << " Predicates:\n";
10148 Pred.print(OS, 4);
10149 } else {
10150 OS << "Unpredictable predicated backedge-taken count. ";
10151 }
Dan Gohman69942932009-06-24 00:33:16 +000010152 OS << "\n";
Eli Friedmanb1578d32017-03-20 20:25:46 +000010153
10154 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10155 OS << "Loop ";
10156 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10157 OS << ": ";
10158 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10159 }
Chris Lattnerd934c702004-04-02 20:23:17 +000010160}
10161
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010162static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10163 switch (LD) {
10164 case ScalarEvolution::LoopVariant:
10165 return "Variant";
10166 case ScalarEvolution::LoopInvariant:
10167 return "Invariant";
10168 case ScalarEvolution::LoopComputable:
10169 return "Computable";
10170 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +000010171 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010172}
10173
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010174void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +000010175 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +000010176 // out SCEV values of all instructions that are interesting. Doing
10177 // this potentially causes it to create new SCEV objects though,
10178 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +000010179 // observable from outside the class though, so casting away the
10180 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +000010181 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +000010182
Dan Gohmanbc694912010-01-09 18:17:45 +000010183 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010184 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +000010185 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +000010186 for (Instruction &I : instructions(F))
10187 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10188 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +000010189 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +000010190 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +000010191 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +000010192 if (!isa<SCEVCouldNotCompute>(SV)) {
10193 OS << " U: ";
10194 SE.getUnsignedRange(SV).print(OS);
10195 OS << " S: ";
10196 SE.getSignedRange(SV).print(OS);
10197 }
Misha Brukman01808ca2005-04-21 21:13:18 +000010198
Sanjoy Dasd9f6d332015-10-18 00:29:16 +000010199 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +000010200
Dan Gohmanaf752342009-07-07 17:06:11 +000010201 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +000010202 if (AtUse != SV) {
10203 OS << " --> ";
10204 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +000010205 if (!isa<SCEVCouldNotCompute>(AtUse)) {
10206 OS << " U: ";
10207 SE.getUnsignedRange(AtUse).print(OS);
10208 OS << " S: ";
10209 SE.getSignedRange(AtUse).print(OS);
10210 }
Dan Gohmanb9063a82009-06-19 17:49:54 +000010211 }
10212
10213 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +000010214 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +000010215 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +000010216 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +000010217 OS << "<<Unknown>>";
10218 } else {
10219 OS << *ExitValue;
10220 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010221
10222 bool First = true;
10223 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10224 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010225 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010226 First = false;
10227 } else {
10228 OS << ", ";
10229 }
10230
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010231 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10232 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +000010233 }
10234
Sanjoy Das013a4ac2016-05-03 17:49:57 +000010235 for (auto *InnerL : depth_first(L)) {
10236 if (InnerL == L)
10237 continue;
10238 if (First) {
10239 OS << "\t\t" "LoopDispositions: { ";
10240 First = false;
10241 } else {
10242 OS << ", ";
10243 }
10244
10245 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10246 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10247 }
10248
10249 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +000010250 }
10251
Chris Lattnerd934c702004-04-02 20:23:17 +000010252 OS << "\n";
10253 }
10254
Dan Gohmanbc694912010-01-09 18:17:45 +000010255 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010256 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +000010257 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +000010258 for (Loop *I : LI)
10259 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +000010260}
Dan Gohmane20f8242009-04-21 00:47:46 +000010261
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010262ScalarEvolution::LoopDisposition
10263ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010264 auto &Values = LoopDispositions[S];
10265 for (auto &V : Values) {
10266 if (V.getPointer() == L)
10267 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010268 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010269 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010270 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010271 auto &Values2 = LoopDispositions[S];
10272 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10273 if (V.getPointer() == L) {
10274 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010275 break;
10276 }
10277 }
10278 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010279}
10280
10281ScalarEvolution::LoopDisposition
10282ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +000010283 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +000010284 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010285 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010286 case scTruncate:
10287 case scZeroExtend:
10288 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010289 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +000010290 case scAddRecExpr: {
10291 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10292
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010293 // If L is the addrec's loop, it's computable.
10294 if (AR->getLoop() == L)
10295 return LoopComputable;
10296
Dan Gohmanafd6db92010-11-17 21:23:15 +000010297 // Add recurrences are never invariant in the function-body (null loop).
10298 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010299 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010300
10301 // This recurrence is variant w.r.t. L if L contains AR's loop.
10302 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010303 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010304
10305 // This recurrence is invariant w.r.t. L if AR's loop contains L.
10306 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010307 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010308
10309 // This recurrence is variant w.r.t. L if any of its operands
10310 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +000010311 for (auto *Op : AR->operands())
10312 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010313 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010314
10315 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010316 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010317 }
10318 case scAddExpr:
10319 case scMulExpr:
10320 case scUMaxExpr:
10321 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +000010322 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +000010323 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10324 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010325 if (D == LoopVariant)
10326 return LoopVariant;
10327 if (D == LoopComputable)
10328 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010329 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010330 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010331 }
10332 case scUDivExpr: {
10333 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010334 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10335 if (LD == LoopVariant)
10336 return LoopVariant;
10337 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10338 if (RD == LoopVariant)
10339 return LoopVariant;
10340 return (LD == LoopInvariant && RD == LoopInvariant) ?
10341 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010342 }
10343 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010344 // All non-instruction values are loop invariant. All instructions are loop
10345 // invariant if they are not contained in the specified loop.
10346 // Instructions are never considered invariant in the function body
10347 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +000010348 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010349 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10350 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010351 case scCouldNotCompute:
10352 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +000010353 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010354 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010355}
10356
10357bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10358 return getLoopDisposition(S, L) == LoopInvariant;
10359}
10360
10361bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10362 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010363}
Dan Gohman20d9ce22010-11-17 21:41:58 +000010364
Dan Gohman8ea83d82010-11-18 00:34:22 +000010365ScalarEvolution::BlockDisposition
10366ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010367 auto &Values = BlockDispositions[S];
10368 for (auto &V : Values) {
10369 if (V.getPointer() == BB)
10370 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010371 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010372 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010373 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010374 auto &Values2 = BlockDispositions[S];
10375 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10376 if (V.getPointer() == BB) {
10377 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010378 break;
10379 }
10380 }
10381 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010382}
10383
Dan Gohman8ea83d82010-11-18 00:34:22 +000010384ScalarEvolution::BlockDisposition
10385ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +000010386 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +000010387 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010388 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010389 case scTruncate:
10390 case scZeroExtend:
10391 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010392 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +000010393 case scAddRecExpr: {
10394 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +000010395 // to test for proper dominance too, because the instruction which
10396 // produces the addrec's value is a PHI, and a PHI effectively properly
10397 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +000010398 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010399 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010400 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +000010401
10402 // Fall through into SCEVNAryExpr handling.
10403 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010404 }
Dan Gohman20d9ce22010-11-17 21:41:58 +000010405 case scAddExpr:
10406 case scMulExpr:
10407 case scUMaxExpr:
10408 case scSMaxExpr: {
10409 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010410 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +000010411 for (const SCEV *NAryOp : NAry->operands()) {
10412 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010413 if (D == DoesNotDominateBlock)
10414 return DoesNotDominateBlock;
10415 if (D == DominatesBlock)
10416 Proper = false;
10417 }
10418 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010419 }
10420 case scUDivExpr: {
10421 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010422 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10423 BlockDisposition LD = getBlockDisposition(LHS, BB);
10424 if (LD == DoesNotDominateBlock)
10425 return DoesNotDominateBlock;
10426 BlockDisposition RD = getBlockDisposition(RHS, BB);
10427 if (RD == DoesNotDominateBlock)
10428 return DoesNotDominateBlock;
10429 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10430 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010431 }
10432 case scUnknown:
10433 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +000010434 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10435 if (I->getParent() == BB)
10436 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010437 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010438 return ProperlyDominatesBlock;
10439 return DoesNotDominateBlock;
10440 }
10441 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010442 case scCouldNotCompute:
10443 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +000010444 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010445 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +000010446}
10447
10448bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10449 return getBlockDisposition(S, BB) >= DominatesBlock;
10450}
10451
10452bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10453 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010454}
Dan Gohman534749b2010-11-17 22:27:42 +000010455
10456bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +000010457 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +000010458}
Dan Gohman7e6b3932010-11-17 23:28:48 +000010459
10460void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10461 ValuesAtScopes.erase(S);
10462 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010463 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010464 UnsignedRanges.erase(S);
10465 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +000010466 ExprValueMap.erase(S);
10467 HasRecMap.erase(S);
Igor Laevskyc11c1ed2017-02-14 15:53:12 +000010468 MinTrailingZerosCache.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +000010469
Silviu Baranga6f444df2016-04-08 14:29:09 +000010470 auto RemoveSCEVFromBackedgeMap =
10471 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10472 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10473 BackedgeTakenInfo &BEInfo = I->second;
10474 if (BEInfo.hasOperand(S, this)) {
10475 BEInfo.clear();
10476 Map.erase(I++);
10477 } else
10478 ++I;
10479 }
10480 };
10481
10482 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10483 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010484}
Benjamin Kramer214935e2012-10-26 17:31:32 +000010485
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010486void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010487 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010488 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010489
Sanjoy Das148e49f2017-04-23 23:04:45 +000010490 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
Benjamin Kramer214935e2012-10-26 17:31:32 +000010491
Sanjoy Das148e49f2017-04-23 23:04:45 +000010492 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10493 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10494 const SCEV *visitConstant(const SCEVConstant *Constant) {
10495 return SE.getConstant(Constant->getAPInt());
10496 }
10497 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10498 return SE.getUnknown(Expr->getValue());
10499 }
Benjamin Kramer214935e2012-10-26 17:31:32 +000010500
Sanjoy Das148e49f2017-04-23 23:04:45 +000010501 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10502 return SE.getCouldNotCompute();
10503 }
10504 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10505 };
10506
10507 SCEVMapper SCM(SE2);
10508
10509 while (!LoopStack.empty()) {
10510 auto *L = LoopStack.pop_back_val();
10511 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10512
10513 auto *CurBECount = SCM.visit(
10514 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10515 auto *NewBECount = SE2.getBackedgeTakenCount(L);
10516
10517 if (CurBECount == SE2.getCouldNotCompute() ||
10518 NewBECount == SE2.getCouldNotCompute()) {
10519 // NB! This situation is legal, but is very suspicious -- whatever pass
10520 // change the loop to make a trip count go from could not compute to
10521 // computable or vice-versa *should have* invalidated SCEV. However, we
10522 // choose not to assert here (for now) since we don't want false
10523 // positives.
10524 continue;
10525 }
10526
10527 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10528 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10529 // not propagate undef aggressively). This means we can (and do) fail
10530 // verification in cases where a transform makes the trip count of a loop
10531 // go from "undef" to "undef+1" (say). The transform is fine, since in
10532 // both cases the loop iterates "undef" times, but SCEV thinks we
10533 // increased the trip count of the loop by 1 incorrectly.
10534 continue;
10535 }
10536
10537 if (SE.getTypeSizeInBits(CurBECount->getType()) >
10538 SE.getTypeSizeInBits(NewBECount->getType()))
10539 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10540 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10541 SE.getTypeSizeInBits(NewBECount->getType()))
10542 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10543
10544 auto *ConstantDelta =
10545 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10546
10547 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10548 dbgs() << "Trip Count Changed!\n";
10549 dbgs() << "Old: " << *CurBECount << "\n";
10550 dbgs() << "New: " << *NewBECount << "\n";
10551 dbgs() << "Delta: " << *ConstantDelta << "\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010552 std::abort();
10553 }
10554 }
Benjamin Kramer214935e2012-10-26 17:31:32 +000010555}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010556
Chandler Carruth082c1832017-01-09 07:44:34 +000010557bool ScalarEvolution::invalidate(
10558 Function &F, const PreservedAnalyses &PA,
10559 FunctionAnalysisManager::Invalidator &Inv) {
10560 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10561 // of its dependencies is invalidated.
10562 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10563 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10564 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10565 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10566 Inv.invalidate<LoopAnalysis>(F, PA);
10567}
10568
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010569AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010570
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010571ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010572 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010573 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010574 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010575 AM.getResult<DominatorTreeAnalysis>(F),
10576 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010577}
10578
10579PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010580ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010581 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010582 return PreservedAnalyses::all();
10583}
10584
10585INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10586 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010587INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010588INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10589INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10590INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10591INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10592 "Scalar Evolution Analysis", false, true)
10593char ScalarEvolutionWrapperPass::ID = 0;
10594
10595ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10596 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10597}
10598
10599bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10600 SE.reset(new ScalarEvolution(
10601 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010602 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010603 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10604 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10605 return false;
10606}
10607
10608void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10609
10610void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10611 SE->print(OS);
10612}
10613
10614void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10615 if (!VerifySCEV)
10616 return;
10617
10618 SE->verify();
10619}
10620
10621void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10622 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010623 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010624 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10625 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10626 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10627}
Silviu Barangae3c05342015-11-02 14:41:02 +000010628
10629const SCEVPredicate *
10630ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10631 const SCEVConstant *RHS) {
10632 FoldingSetNodeID ID;
10633 // Unique this node based on the arguments
10634 ID.AddInteger(SCEVPredicate::P_Equal);
10635 ID.AddPointer(LHS);
10636 ID.AddPointer(RHS);
10637 void *IP = nullptr;
10638 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10639 return S;
10640 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10641 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10642 UniquePreds.InsertNode(Eq, IP);
10643 return Eq;
10644}
10645
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010646const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10647 const SCEVAddRecExpr *AR,
10648 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10649 FoldingSetNodeID ID;
10650 // Unique this node based on the arguments
10651 ID.AddInteger(SCEVPredicate::P_Wrap);
10652 ID.AddPointer(AR);
10653 ID.AddInteger(AddedFlags);
10654 void *IP = nullptr;
10655 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10656 return S;
10657 auto *OF = new (SCEVAllocator)
10658 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10659 UniquePreds.InsertNode(OF, IP);
10660 return OF;
10661}
10662
Benjamin Kramer83709b12015-11-16 09:01:28 +000010663namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010664
Silviu Barangae3c05342015-11-02 14:41:02 +000010665class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10666public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010667 /// Rewrites \p S in the context of a loop L and the SCEV predication
10668 /// infrastructure.
10669 ///
10670 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10671 /// equivalences present in \p Pred.
10672 ///
10673 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10674 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010675 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010676 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10677 SCEVUnionPredicate *Pred) {
10678 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010679 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010680 }
10681
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010682 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010683 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10684 SCEVUnionPredicate *Pred)
10685 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010686
10687 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010688 if (Pred) {
10689 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10690 for (auto *Pred : ExprPreds)
10691 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10692 if (IPred->getLHS() == Expr)
10693 return IPred->getRHS();
10694 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010695
10696 return Expr;
10697 }
10698
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010699 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10700 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010701 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010702 if (AR && AR->getLoop() == L && AR->isAffine()) {
10703 // This couldn't be folded because the operand didn't have the nuw
10704 // flag. Add the nusw flag as an assumption that we could make.
10705 const SCEV *Step = AR->getStepRecurrence(SE);
10706 Type *Ty = Expr->getType();
10707 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10708 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10709 SE.getSignExtendExpr(Step, Ty), L,
10710 AR->getNoWrapFlags());
10711 }
10712 return SE.getZeroExtendExpr(Operand, Expr->getType());
10713 }
10714
10715 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10716 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010717 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010718 if (AR && AR->getLoop() == L && AR->isAffine()) {
10719 // This couldn't be folded because the operand didn't have the nsw
10720 // flag. Add the nssw flag as an assumption that we could make.
10721 const SCEV *Step = AR->getStepRecurrence(SE);
10722 Type *Ty = Expr->getType();
10723 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10724 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10725 SE.getSignExtendExpr(Step, Ty), L,
10726 AR->getNoWrapFlags());
10727 }
10728 return SE.getSignExtendExpr(Operand, Expr->getType());
10729 }
10730
Silviu Barangae3c05342015-11-02 14:41:02 +000010731private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010732 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10733 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10734 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010735 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010736 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010737 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010738 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010739 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010740 return true;
10741 }
10742
Sanjoy Dasf0022122016-09-28 17:14:58 +000010743 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10744 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010745 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010746};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010747} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010748
Sanjoy Das807d33d2016-02-20 01:44:10 +000010749const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010750 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010751 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010752}
10753
Sanjoy Dasf0022122016-09-28 17:14:58 +000010754const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10755 const SCEV *S, const Loop *L,
10756 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10757
10758 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10759 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010760 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10761
10762 if (!AddRec)
10763 return nullptr;
10764
10765 // Since the transformation was successful, we can now transfer the SCEV
10766 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010767 for (auto *P : TransformPreds)
10768 Preds.insert(P);
10769
Silviu Barangad68ed852016-03-23 15:29:30 +000010770 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010771}
10772
10773/// SCEV predicates
10774SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10775 SCEVPredicateKind Kind)
10776 : FastID(ID), Kind(Kind) {}
10777
10778SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10779 const SCEVUnknown *LHS,
10780 const SCEVConstant *RHS)
10781 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10782
10783bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010784 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010785
10786 if (!Op)
10787 return false;
10788
10789 return Op->LHS == LHS && Op->RHS == RHS;
10790}
10791
10792bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10793
10794const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10795
10796void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10797 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10798}
10799
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010800SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10801 const SCEVAddRecExpr *AR,
10802 IncrementWrapFlags Flags)
10803 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10804
10805const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10806
10807bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10808 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10809
10810 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10811}
10812
10813bool SCEVWrapPredicate::isAlwaysTrue() const {
10814 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10815 IncrementWrapFlags IFlags = Flags;
10816
10817 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10818 IFlags = clearFlags(IFlags, IncrementNSSW);
10819
10820 return IFlags == IncrementAnyWrap;
10821}
10822
10823void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10824 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10825 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10826 OS << "<nusw>";
10827 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10828 OS << "<nssw>";
10829 OS << "\n";
10830}
10831
10832SCEVWrapPredicate::IncrementWrapFlags
10833SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10834 ScalarEvolution &SE) {
10835 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10836 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10837
10838 // We can safely transfer the NSW flag as NSSW.
10839 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10840 ImpliedFlags = IncrementNSSW;
10841
10842 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10843 // If the increment is positive, the SCEV NUW flag will also imply the
10844 // WrapPredicate NUSW flag.
10845 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10846 if (Step->getValue()->getValue().isNonNegative())
10847 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10848 }
10849
10850 return ImpliedFlags;
10851}
10852
Silviu Barangae3c05342015-11-02 14:41:02 +000010853/// Union predicates don't get cached so create a dummy set ID for it.
10854SCEVUnionPredicate::SCEVUnionPredicate()
10855 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10856
10857bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010858 return all_of(Preds,
10859 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010860}
10861
10862ArrayRef<const SCEVPredicate *>
10863SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10864 auto I = SCEVToPreds.find(Expr);
10865 if (I == SCEVToPreds.end())
10866 return ArrayRef<const SCEVPredicate *>();
10867 return I->second;
10868}
10869
10870bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010871 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010872 return all_of(Set->Preds,
10873 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010874
10875 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10876 if (ScevPredsIt == SCEVToPreds.end())
10877 return false;
10878 auto &SCEVPreds = ScevPredsIt->second;
10879
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010880 return any_of(SCEVPreds,
10881 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010882}
10883
10884const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10885
10886void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10887 for (auto Pred : Preds)
10888 Pred->print(OS, Depth);
10889}
10890
10891void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010892 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010893 for (auto Pred : Set->Preds)
10894 add(Pred);
10895 return;
10896 }
10897
10898 if (implies(N))
10899 return;
10900
10901 const SCEV *Key = N->getExpr();
10902 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10903 " associated expression!");
10904
10905 SCEVToPreds[Key].push_back(N);
10906 Preds.push_back(N);
10907}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010908
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010909PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10910 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010911 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010912
10913const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10914 const SCEV *Expr = SE.getSCEV(V);
10915 RewriteEntry &Entry = RewriteMap[Expr];
10916
10917 // If we already have an entry and the version matches, return it.
10918 if (Entry.second && Generation == Entry.first)
10919 return Entry.second;
10920
10921 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010922 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010923 if (Entry.second)
10924 Expr = Entry.second;
10925
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010926 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010927 Entry = {Generation, NewSCEV};
10928
10929 return NewSCEV;
10930}
10931
Silviu Baranga6f444df2016-04-08 14:29:09 +000010932const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10933 if (!BackedgeCount) {
10934 SCEVUnionPredicate BackedgePred;
10935 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10936 addPredicate(BackedgePred);
10937 }
10938 return BackedgeCount;
10939}
10940
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010941void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10942 if (Preds.implies(&Pred))
10943 return;
10944 Preds.add(&Pred);
10945 updateGeneration();
10946}
10947
10948const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10949 return Preds;
10950}
10951
10952void PredicatedScalarEvolution::updateGeneration() {
10953 // If the generation number wrapped recompute everything.
10954 if (++Generation == 0) {
10955 for (auto &II : RewriteMap) {
10956 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010957 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010958 }
10959 }
10960}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010961
10962void PredicatedScalarEvolution::setNoOverflow(
10963 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10964 const SCEV *Expr = getSCEV(V);
10965 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10966
10967 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10968
10969 // Clear the statically implied flags.
10970 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10971 addPredicate(*SE.getWrapPredicate(AR, Flags));
10972
10973 auto II = FlagsMap.insert({V, Flags});
10974 if (!II.second)
10975 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10976}
10977
10978bool PredicatedScalarEvolution::hasNoOverflow(
10979 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10980 const SCEV *Expr = getSCEV(V);
10981 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10982
10983 Flags = SCEVWrapPredicate::clearFlags(
10984 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10985
10986 auto II = FlagsMap.find(V);
10987
10988 if (II != FlagsMap.end())
10989 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10990
10991 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10992}
10993
Silviu Barangad68ed852016-03-23 15:29:30 +000010994const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010995 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010996 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10997 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010998
10999 if (!New)
11000 return nullptr;
11001
Sanjoy Dasf0022122016-09-28 17:14:58 +000011002 for (auto *P : NewPreds)
11003 Preds.add(P);
11004
Silviu Barangaea63a7f2016-02-08 17:02:45 +000011005 updateGeneration();
11006 RewriteMap[SE.getSCEV(V)] = {Generation, New};
11007 return New;
11008}
11009
Silviu Baranga6f444df2016-04-08 14:29:09 +000011010PredicatedScalarEvolution::PredicatedScalarEvolution(
11011 const PredicatedScalarEvolution &Init)
11012 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11013 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000011014 for (const auto &I : Init.FlagsMap)
11015 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000011016}
Silviu Barangab77365b2016-04-14 16:08:45 +000011017
11018void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11019 // For each block.
11020 for (auto *BB : L.getBlocks())
11021 for (auto &I : *BB) {
11022 if (!SE.isSCEVable(I.getType()))
11023 continue;
11024
11025 auto *Expr = SE.getSCEV(&I);
11026 auto II = RewriteMap.find(Expr);
11027
11028 if (II == RewriteMap.end())
11029 continue;
11030
11031 // Don't print things that are not interesting.
11032 if (II->second.second == Expr)
11033 continue;
11034
11035 OS.indent(Depth) << "[PSE]" << I << ":\n";
11036 OS.indent(Depth + 2) << *Expr << "\n";
11037 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11038 }
11039}