blob: fd8ba55e57bf079c88bb92845331494bdd064a17 [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"
Chris Lattner0a1e9932006-12-19 01:16:02 +000092#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000093#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000094#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000095#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000096using namespace llvm;
97
Chandler Carruthf1221bd2014-04-22 02:48:03 +000098#define DEBUG_TYPE "scalar-evolution"
99
Chris Lattner57ef9422006-12-19 22:30:33 +0000100STATISTIC(NumArrayLenItCounts,
101 "Number of trip counts computed with array length");
102STATISTIC(NumTripCountsComputed,
103 "Number of loops with predictable loop counts");
104STATISTIC(NumTripCountsNotComputed,
105 "Number of loops without predictable loop counts");
106STATISTIC(NumBruteForceTripCountsComputed,
107 "Number of loops with trip counts computed by force");
108
Dan Gohmand78c4002008-05-13 00:00:25 +0000109static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000110MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000112 "symbolically execute a constant "
113 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000114 cl::init(100));
115
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000116// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Benjamin Kramer214935e2012-10-26 17:31:32 +0000117static cl::opt<bool>
118VerifySCEV("verify-scev",
119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000120static cl::opt<bool>
121 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000122 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000123 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000124
Li Huangfcfe8cd2016-10-20 21:38:39 +0000125static cl::opt<unsigned> MulOpsInlineThreshold(
126 "scev-mulops-inline-threshold", cl::Hidden,
127 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128 cl::init(1000));
129
Daniil Fukalovb09dac52017-01-26 13:33:17 +0000130static cl::opt<unsigned> AddOpsInlineThreshold(
131 "scev-addops-inline-threshold", cl::Hidden,
132 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
133 cl::init(500));
134
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000135static cl::opt<unsigned>
136 MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden,
137 cl::desc("Maximum depth of recursive compare complexity"),
138 cl::init(32));
139
Michael Liao468fb742017-01-13 18:28:30 +0000140static cl::opt<unsigned> MaxConstantEvolvingDepth(
141 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
142 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
143
Chris Lattnerd934c702004-04-02 20:23:17 +0000144//===----------------------------------------------------------------------===//
145// SCEV class definitions
146//===----------------------------------------------------------------------===//
147
148//===----------------------------------------------------------------------===//
149// Implementation of the SCEV class.
150//
Dan Gohman3423e722009-06-30 20:13:32 +0000151
Matthias Braun8c209aa2017-01-28 02:02:38 +0000152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
153LLVM_DUMP_METHOD void SCEV::dump() const {
Davide Italiano2071f4c2015-10-25 19:55:24 +0000154 print(dbgs());
155 dbgs() << '\n';
156}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000157#endif
Davide Italiano2071f4c2015-10-25 19:55:24 +0000158
Dan Gohman534749b2010-11-17 22:27:42 +0000159void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000160 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000161 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000162 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000163 return;
164 case scTruncate: {
165 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
166 const SCEV *Op = Trunc->getOperand();
167 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
168 << *Trunc->getType() << ")";
169 return;
170 }
171 case scZeroExtend: {
172 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
173 const SCEV *Op = ZExt->getOperand();
174 OS << "(zext " << *Op->getType() << " " << *Op << " to "
175 << *ZExt->getType() << ")";
176 return;
177 }
178 case scSignExtend: {
179 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
180 const SCEV *Op = SExt->getOperand();
181 OS << "(sext " << *Op->getType() << " " << *Op << " to "
182 << *SExt->getType() << ")";
183 return;
184 }
185 case scAddRecExpr: {
186 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
187 OS << "{" << *AR->getOperand(0);
188 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
189 OS << ",+," << *AR->getOperand(i);
190 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000191 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000192 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000193 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000194 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000195 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000196 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
197 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000198 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000199 OS << ">";
200 return;
201 }
202 case scAddExpr:
203 case scMulExpr:
204 case scUMaxExpr:
205 case scSMaxExpr: {
206 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000207 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000208 switch (NAry->getSCEVType()) {
209 case scAddExpr: OpStr = " + "; break;
210 case scMulExpr: OpStr = " * "; break;
211 case scUMaxExpr: OpStr = " umax "; break;
212 case scSMaxExpr: OpStr = " smax "; break;
213 }
214 OS << "(";
215 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
216 I != E; ++I) {
217 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000218 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000219 OS << OpStr;
220 }
221 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000222 switch (NAry->getSCEVType()) {
223 case scAddExpr:
224 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000225 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000226 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000227 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000228 OS << "<nsw>";
229 }
Dan Gohman534749b2010-11-17 22:27:42 +0000230 return;
231 }
232 case scUDivExpr: {
233 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
234 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
235 return;
236 }
237 case scUnknown: {
238 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000239 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000240 if (U->isSizeOf(AllocTy)) {
241 OS << "sizeof(" << *AllocTy << ")";
242 return;
243 }
244 if (U->isAlignOf(AllocTy)) {
245 OS << "alignof(" << *AllocTy << ")";
246 return;
247 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000248
Chris Lattner229907c2011-07-18 04:54:35 +0000249 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000250 Constant *FieldNo;
251 if (U->isOffsetOf(CTy, FieldNo)) {
252 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000253 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000254 OS << ")";
255 return;
256 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000257
Dan Gohman534749b2010-11-17 22:27:42 +0000258 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000259 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000260 return;
261 }
262 case scCouldNotCompute:
263 OS << "***COULDNOTCOMPUTE***";
264 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000265 }
266 llvm_unreachable("Unknown SCEV kind!");
267}
268
Chris Lattner229907c2011-07-18 04:54:35 +0000269Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000270 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000271 case scConstant:
272 return cast<SCEVConstant>(this)->getType();
273 case scTruncate:
274 case scZeroExtend:
275 case scSignExtend:
276 return cast<SCEVCastExpr>(this)->getType();
277 case scAddRecExpr:
278 case scMulExpr:
279 case scUMaxExpr:
280 case scSMaxExpr:
281 return cast<SCEVNAryExpr>(this)->getType();
282 case scAddExpr:
283 return cast<SCEVAddExpr>(this)->getType();
284 case scUDivExpr:
285 return cast<SCEVUDivExpr>(this)->getType();
286 case scUnknown:
287 return cast<SCEVUnknown>(this)->getType();
288 case scCouldNotCompute:
289 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000290 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000291 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000292}
293
Dan Gohmanbe928e32008-06-18 16:23:07 +0000294bool SCEV::isZero() const {
295 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
296 return SC->getValue()->isZero();
297 return false;
298}
299
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000300bool SCEV::isOne() const {
301 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
302 return SC->getValue()->isOne();
303 return false;
304}
Chris Lattnerd934c702004-04-02 20:23:17 +0000305
Dan Gohman18a96bb2009-06-24 00:30:26 +0000306bool SCEV::isAllOnesValue() const {
307 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
308 return SC->getValue()->isAllOnesValue();
309 return false;
310}
311
Andrew Trick881a7762012-01-07 00:27:31 +0000312bool SCEV::isNonConstantNegative() const {
313 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
314 if (!Mul) return false;
315
316 // If there is a constant factor, it will be first.
317 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
318 if (!SC) return false;
319
320 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000321 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000322}
323
Owen Anderson04052ec2009-06-22 21:57:23 +0000324SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000325 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000326
Chris Lattnerd934c702004-04-02 20:23:17 +0000327bool SCEVCouldNotCompute::classof(const SCEV *S) {
328 return S->getSCEVType() == scCouldNotCompute;
329}
330
Dan Gohmanaf752342009-07-07 17:06:11 +0000331const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000332 FoldingSetNodeID ID;
333 ID.AddInteger(scConstant);
334 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000335 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000336 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000337 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000338 UniqueSCEVs.InsertNode(S, IP);
339 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000340}
Chris Lattnerd934c702004-04-02 20:23:17 +0000341
Nick Lewycky31eaca52014-01-27 10:04:03 +0000342const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000343 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000344}
345
Dan Gohmanaf752342009-07-07 17:06:11 +0000346const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000347ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
348 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000349 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000350}
351
Dan Gohman24ceda82010-06-18 19:54:20 +0000352SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000353 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000354 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000355
Dan Gohman24ceda82010-06-18 19:54:20 +0000356SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000357 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000358 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000359 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
360 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000361 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000362}
Chris Lattnerd934c702004-04-02 20:23:17 +0000363
Dan Gohman24ceda82010-06-18 19:54:20 +0000364SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000365 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000366 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000367 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
368 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000369 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000370}
371
Dan Gohman24ceda82010-06-18 19:54:20 +0000372SCEVSignExtendExpr::SCEVSignExtendExpr(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, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000375 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000377 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000378}
379
Dan Gohman7cac9572010-08-02 23:49:30 +0000380void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000381 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000382 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000383
384 // Remove this SCEVUnknown from the uniquing map.
385 SE->UniqueSCEVs.RemoveNode(this);
386
387 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000388 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000389}
390
391void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000392 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000393 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000394
395 // Remove this SCEVUnknown from the uniquing map.
396 SE->UniqueSCEVs.RemoveNode(this);
397
398 // Update this SCEVUnknown to point to the new value. This is needed
399 // because there may still be outstanding SCEVs which still point to
400 // this SCEVUnknown.
401 setValPtr(New);
402}
403
Chris Lattner229907c2011-07-18 04:54:35 +0000404bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000405 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000406 if (VCE->getOpcode() == Instruction::PtrToInt)
407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 if (CE->getOpcode() == Instruction::GetElementPtr &&
409 CE->getOperand(0)->isNullValue() &&
410 CE->getNumOperands() == 2)
411 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
412 if (CI->isOne()) {
413 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
414 ->getElementType();
415 return true;
416 }
Dan Gohmancf913832010-01-28 02:15:55 +0000417
418 return false;
419}
420
Chris Lattner229907c2011-07-18 04:54:35 +0000421bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000422 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000423 if (VCE->getOpcode() == Instruction::PtrToInt)
424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000425 if (CE->getOpcode() == Instruction::GetElementPtr &&
426 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000427 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000428 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000429 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000430 if (!STy->isPacked() &&
431 CE->getNumOperands() == 3 &&
432 CE->getOperand(1)->isNullValue()) {
433 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
434 if (CI->isOne() &&
435 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000436 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000437 AllocTy = STy->getElementType(1);
438 return true;
439 }
440 }
441 }
Dan Gohmancf913832010-01-28 02:15:55 +0000442
443 return false;
444}
445
Chris Lattner229907c2011-07-18 04:54:35 +0000446bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000447 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000448 if (VCE->getOpcode() == Instruction::PtrToInt)
449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
450 if (CE->getOpcode() == Instruction::GetElementPtr &&
451 CE->getNumOperands() == 3 &&
452 CE->getOperand(0)->isNullValue() &&
453 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000454 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000455 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
456 // Ignore vector types here so that ScalarEvolutionExpander doesn't
457 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000458 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000459 CTy = Ty;
460 FieldNo = CE->getOperand(2);
461 return true;
462 }
463 }
464
465 return false;
466}
467
Chris Lattnereb3e8402004-06-20 06:23:15 +0000468//===----------------------------------------------------------------------===//
469// SCEV Utilities
470//===----------------------------------------------------------------------===//
471
Sanjoy Das17078692016-10-31 03:32:43 +0000472/// Compare the two values \p LV and \p RV in terms of their "complexity" where
473/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
474/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
475/// have been previously deemed to be "equally complex" by this routine. It is
476/// intended to avoid exponential time complexity in cases like:
477///
478/// %a = f(%x, %y)
479/// %b = f(%a, %a)
480/// %c = f(%b, %b)
481///
482/// %d = f(%x, %y)
483/// %e = f(%d, %d)
484/// %f = f(%e, %e)
485///
486/// CompareValueComplexity(%f, %c)
487///
488/// Since we do not continue running this routine on expression trees once we
489/// have seen unequal values, there is no need to track them in the cache.
490static int
491CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
492 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000493 unsigned Depth) {
494 if (Depth > MaxCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000495 return 0;
496
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000497 // Order pointer values after integer values. This helps SCEVExpander form
498 // GEPs.
499 bool LIsPointer = LV->getType()->isPointerTy(),
500 RIsPointer = RV->getType()->isPointerTy();
501 if (LIsPointer != RIsPointer)
502 return (int)LIsPointer - (int)RIsPointer;
503
504 // Compare getValueID values.
505 unsigned LID = LV->getValueID(), RID = RV->getValueID();
506 if (LID != RID)
507 return (int)LID - (int)RID;
508
509 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000510 if (const auto *LA = dyn_cast<Argument>(LV)) {
511 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
514 }
515
Sanjoy Das299e6722016-10-30 23:52:56 +0000516 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
517 const auto *RGV = cast<GlobalValue>(RV);
518
519 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
520 auto LT = GV->getLinkage();
521 return !(GlobalValue::isPrivateLinkage(LT) ||
522 GlobalValue::isInternalLinkage(LT));
523 };
524
525 // Use the names to distinguish the two values, but only if the
526 // names are semantically important.
527 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
528 return LGV->getName().compare(RGV->getName());
529 }
530
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000531 // For instructions, compare their loop depth, and their operand count. This
532 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000533 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
534 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000535
536 // Compare loop depths.
537 const BasicBlock *LParent = LInst->getParent(),
538 *RParent = RInst->getParent();
539 if (LParent != RParent) {
540 unsigned LDepth = LI->getLoopDepth(LParent),
541 RDepth = LI->getLoopDepth(RParent);
542 if (LDepth != RDepth)
543 return (int)LDepth - (int)RDepth;
544 }
545
546 // Compare the number of operands.
547 unsigned LNumOps = LInst->getNumOperands(),
548 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000549 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000550 return (int)LNumOps - (int)RNumOps;
551
Sanjoy Das17078692016-10-31 03:32:43 +0000552 for (unsigned Idx : seq(0u, LNumOps)) {
553 int Result =
554 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000555 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000556 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000557 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000558 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000559 }
560
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000561 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000562 return 0;
563}
564
Sanjoy Das237c8452016-09-27 18:01:48 +0000565// Return negative, zero, or positive, if LHS is less than, equal to, or greater
566// than RHS, respectively. A three-way result allows recursive comparisons to be
567// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000568static int CompareSCEVComplexity(
569 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
570 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
571 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000572 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
573 if (LHS == RHS)
574 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000575
Sanjoy Das237c8452016-09-27 18:01:48 +0000576 // Primarily, sort the SCEVs by their getSCEVType().
577 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
578 if (LType != RType)
579 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000580
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000581 if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS}))
582 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000583 // Aside from the getSCEVType() ordering, the particular ordering
584 // isn't very important except that it's beneficial to be consistent,
585 // so that (a + b) and (b + a) don't end up as different expressions.
586 switch (static_cast<SCEVTypes>(LType)) {
587 case scUnknown: {
588 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
589 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000590
Sanjoy Das17078692016-10-31 03:32:43 +0000591 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000592 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
593 Depth + 1);
594 if (X == 0)
595 EqCacheSCEV.insert({LHS, RHS});
596 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000597 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000598
Sanjoy Das237c8452016-09-27 18:01:48 +0000599 case scConstant: {
600 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
601 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
602
603 // Compare constant values.
604 const APInt &LA = LC->getAPInt();
605 const APInt &RA = RC->getAPInt();
606 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
607 if (LBitWidth != RBitWidth)
608 return (int)LBitWidth - (int)RBitWidth;
609 return LA.ult(RA) ? -1 : 1;
610 }
611
612 case scAddRecExpr: {
613 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
614 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
615
616 // Compare addrec loop depths.
617 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
618 if (LLoop != RLoop) {
619 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
620 if (LDepth != RDepth)
621 return (int)LDepth - (int)RDepth;
622 }
623
624 // Addrec complexity grows with operand count.
625 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
626 if (LNumOps != RNumOps)
627 return (int)LNumOps - (int)RNumOps;
628
629 // Lexicographically compare.
630 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000631 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
632 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000633 if (X != 0)
634 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000635 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000636 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000637 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000638 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000639
640 case scAddExpr:
641 case scMulExpr:
642 case scSMaxExpr:
643 case scUMaxExpr: {
644 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
645 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
646
647 // Lexicographically compare n-ary expressions.
648 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
649 if (LNumOps != RNumOps)
650 return (int)LNumOps - (int)RNumOps;
651
652 for (unsigned i = 0; i != LNumOps; ++i) {
653 if (i >= RNumOps)
654 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000655 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
656 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000657 if (X != 0)
658 return X;
659 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000660 EqCacheSCEV.insert({LHS, RHS});
661 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000662 }
663
664 case scUDivExpr: {
665 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
666 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
667
668 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000669 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
670 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000671 if (X != 0)
672 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000673 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
674 Depth + 1);
675 if (X == 0)
676 EqCacheSCEV.insert({LHS, RHS});
677 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000678 }
679
680 case scTruncate:
681 case scZeroExtend:
682 case scSignExtend: {
683 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
684 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
685
686 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000687 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
688 RC->getOperand(), Depth + 1);
689 if (X == 0)
690 EqCacheSCEV.insert({LHS, RHS});
691 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000692 }
693
694 case scCouldNotCompute:
695 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
696 }
697 llvm_unreachable("Unknown SCEV kind!");
698}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000699
Sanjoy Dasf8570812016-05-29 00:38:22 +0000700/// Given a list of SCEV objects, order them by their complexity, and group
701/// objects of the same complexity together by value. When this routine is
702/// finished, we know that any duplicates in the vector are consecutive and that
703/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000704///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000705/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000706/// results from this routine. In other words, we don't want the results of
707/// this to depend on where the addresses of various SCEV objects happened to
708/// land in memory.
709///
Dan Gohmanaf752342009-07-07 17:06:11 +0000710static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000711 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000712 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000713
714 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000715 if (Ops.size() == 2) {
716 // This is the common case, which also happens to be trivially simple.
717 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000718 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000719 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000720 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000721 return;
722 }
723
Dan Gohman24ceda82010-06-18 19:54:20 +0000724 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000725 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000726 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
727 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000728 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000729
730 // Now that we are sorted by complexity, group elements of the same
731 // complexity. Note that this is, at worst, N^2, but the vector is likely to
732 // be extremely short in practice. Note that we take this approach because we
733 // do not want to depend on the addresses of the objects we are grouping.
734 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
735 const SCEV *S = Ops[i];
736 unsigned Complexity = S->getSCEVType();
737
738 // If there are any objects of the same complexity and same value as this
739 // one, group them.
740 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
741 if (Ops[j] == S) { // Found a duplicate.
742 // Move it to immediately after i'th element.
743 std::swap(Ops[i+1], Ops[j]);
744 ++i; // no need to rescan it.
745 if (i == e-2) return; // Done!
746 }
747 }
748 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000749}
750
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000751// Returns the size of the SCEV S.
752static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000753 struct FindSCEVSize {
754 int Size;
755 FindSCEVSize() : Size(0) {}
756
757 bool follow(const SCEV *S) {
758 ++Size;
759 // Keep looking at all operands of S.
760 return true;
761 }
762 bool isDone() const {
763 return false;
764 }
765 };
766
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000767 FindSCEVSize F;
768 SCEVTraversal<FindSCEVSize> ST(F);
769 ST.visitAll(S);
770 return F.Size;
771}
772
773namespace {
774
David Majnemer4e879362014-12-14 09:12:33 +0000775struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000776public:
777 // Computes the Quotient and Remainder of the division of Numerator by
778 // Denominator.
779 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
780 const SCEV *Denominator, const SCEV **Quotient,
781 const SCEV **Remainder) {
782 assert(Numerator && Denominator && "Uninitialized SCEV");
783
David Majnemer4e879362014-12-14 09:12:33 +0000784 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000785
786 // Check for the trivial case here to avoid having to check for it in the
787 // rest of the code.
788 if (Numerator == Denominator) {
789 *Quotient = D.One;
790 *Remainder = D.Zero;
791 return;
792 }
793
794 if (Numerator->isZero()) {
795 *Quotient = D.Zero;
796 *Remainder = D.Zero;
797 return;
798 }
799
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000800 // A simple case when N/1. The quotient is N.
801 if (Denominator->isOne()) {
802 *Quotient = Numerator;
803 *Remainder = D.Zero;
804 return;
805 }
806
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000807 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000808 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000809 const SCEV *Q, *R;
810 *Quotient = Numerator;
811 for (const SCEV *Op : T->operands()) {
812 divide(SE, *Quotient, Op, &Q, &R);
813 *Quotient = Q;
814
815 // Bail out when the Numerator is not divisible by one of the terms of
816 // the Denominator.
817 if (!R->isZero()) {
818 *Quotient = D.Zero;
819 *Remainder = Numerator;
820 return;
821 }
822 }
823 *Remainder = D.Zero;
824 return;
825 }
826
827 D.visit(Numerator);
828 *Quotient = D.Quotient;
829 *Remainder = D.Remainder;
830 }
831
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000832 // Except in the trivial case described above, we do not know how to divide
833 // Expr by Denominator for the following functions with empty implementation.
834 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
835 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
836 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
837 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
838 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
839 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
840 void visitUnknown(const SCEVUnknown *Numerator) {}
841 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
842
David Majnemer4e879362014-12-14 09:12:33 +0000843 void visitConstant(const SCEVConstant *Numerator) {
844 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000845 APInt NumeratorVal = Numerator->getAPInt();
846 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000847 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
848 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
849
850 if (NumeratorBW > DenominatorBW)
851 DenominatorVal = DenominatorVal.sext(NumeratorBW);
852 else if (NumeratorBW < DenominatorBW)
853 NumeratorVal = NumeratorVal.sext(DenominatorBW);
854
855 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
856 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
857 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
858 Quotient = SE.getConstant(QuotientVal);
859 Remainder = SE.getConstant(RemainderVal);
860 return;
861 }
862 }
863
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000864 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
865 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000866 if (!Numerator->isAffine())
867 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000868 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
869 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000870 // Bail out if the types do not match.
871 Type *Ty = Denominator->getType();
872 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000873 Ty != StepQ->getType() || Ty != StepR->getType())
874 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000875 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
876 Numerator->getNoWrapFlags());
877 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
878 Numerator->getNoWrapFlags());
879 }
880
881 void visitAddExpr(const SCEVAddExpr *Numerator) {
882 SmallVector<const SCEV *, 2> Qs, Rs;
883 Type *Ty = Denominator->getType();
884
885 for (const SCEV *Op : Numerator->operands()) {
886 const SCEV *Q, *R;
887 divide(SE, Op, Denominator, &Q, &R);
888
889 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 if (Ty != Q->getType() || Ty != R->getType())
891 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000892
893 Qs.push_back(Q);
894 Rs.push_back(R);
895 }
896
897 if (Qs.size() == 1) {
898 Quotient = Qs[0];
899 Remainder = Rs[0];
900 return;
901 }
902
903 Quotient = SE.getAddExpr(Qs);
904 Remainder = SE.getAddExpr(Rs);
905 }
906
907 void visitMulExpr(const SCEVMulExpr *Numerator) {
908 SmallVector<const SCEV *, 2> Qs;
909 Type *Ty = Denominator->getType();
910
911 bool FoundDenominatorTerm = false;
912 for (const SCEV *Op : Numerator->operands()) {
913 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000914 if (Ty != Op->getType())
915 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000916
917 if (FoundDenominatorTerm) {
918 Qs.push_back(Op);
919 continue;
920 }
921
922 // Check whether Denominator divides one of the product operands.
923 const SCEV *Q, *R;
924 divide(SE, Op, Denominator, &Q, &R);
925 if (!R->isZero()) {
926 Qs.push_back(Op);
927 continue;
928 }
929
930 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000931 if (Ty != Q->getType())
932 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000933
934 FoundDenominatorTerm = true;
935 Qs.push_back(Q);
936 }
937
938 if (FoundDenominatorTerm) {
939 Remainder = Zero;
940 if (Qs.size() == 1)
941 Quotient = Qs[0];
942 else
943 Quotient = SE.getMulExpr(Qs);
944 return;
945 }
946
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000947 if (!isa<SCEVUnknown>(Denominator))
948 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000949
950 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
951 ValueToValueMap RewriteMap;
952 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
953 cast<SCEVConstant>(Zero)->getValue();
954 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
955
956 if (Remainder->isZero()) {
957 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
958 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
959 cast<SCEVConstant>(One)->getValue();
960 Quotient =
961 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
962 return;
963 }
964
965 // Quotient is (Numerator - Remainder) divided by Denominator.
966 const SCEV *Q, *R;
967 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000968 // This SCEV does not seem to simplify: fail the division here.
969 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
970 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000971 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000972 if (R != Zero)
973 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000974 Quotient = Q;
975 }
976
977private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000978 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
979 const SCEV *Denominator)
980 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000981 Zero = SE.getZero(Denominator->getType());
982 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000983
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000984 // We generally do not know how to divide Expr by Denominator. We
985 // initialize the division to a "cannot divide" state to simplify the rest
986 // of the code.
987 cannotDivide(Numerator);
988 }
989
990 // Convenience function for giving up on the division. We set the quotient to
991 // be equal to zero and the remainder to be equal to the numerator.
992 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000993 Quotient = Zero;
994 Remainder = Numerator;
995 }
996
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000997 ScalarEvolution &SE;
998 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000999};
1000
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001001}
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001002
Chris Lattnerd934c702004-04-02 20:23:17 +00001003//===----------------------------------------------------------------------===//
1004// Simple SCEV method implementations
1005//===----------------------------------------------------------------------===//
1006
Sanjoy Dasf8570812016-05-29 00:38:22 +00001007/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +00001008static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +00001009 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001010 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001011 // Handle the simplest case efficiently.
1012 if (K == 1)
1013 return SE.getTruncateOrZeroExtend(It, ResultTy);
1014
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001015 // We are using the following formula for BC(It, K):
1016 //
1017 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1018 //
Eli Friedman61f67622008-08-04 23:49:06 +00001019 // Suppose, W is the bitwidth of the return value. We must be prepared for
1020 // overflow. Hence, we must assure that the result of our computation is
1021 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1022 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001023 //
Eli Friedman61f67622008-08-04 23:49:06 +00001024 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001025 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001026 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1027 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001028 //
Eli Friedman61f67622008-08-04 23:49:06 +00001029 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001030 //
Eli Friedman61f67622008-08-04 23:49:06 +00001031 // This formula is trivially equivalent to the previous formula. However,
1032 // this formula can be implemented much more efficiently. The trick is that
1033 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1034 // arithmetic. To do exact division in modular arithmetic, all we have
1035 // to do is multiply by the inverse. Therefore, this step can be done at
1036 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001037 //
Eli Friedman61f67622008-08-04 23:49:06 +00001038 // The next issue is how to safely do the division by 2^T. The way this
1039 // is done is by doing the multiplication step at a width of at least W + T
1040 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1041 // when we perform the division by 2^T (which is equivalent to a right shift
1042 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1043 // truncated out after the division by 2^T.
1044 //
1045 // In comparison to just directly using the first formula, this technique
1046 // is much more efficient; using the first formula requires W * K bits,
1047 // but this formula less than W + K bits. Also, the first formula requires
1048 // a division step, whereas this formula only requires multiplies and shifts.
1049 //
1050 // It doesn't matter whether the subtraction step is done in the calculation
1051 // width or the input iteration count's width; if the subtraction overflows,
1052 // the result must be zero anyway. We prefer here to do it in the width of
1053 // the induction variable because it helps a lot for certain cases; CodeGen
1054 // isn't smart enough to ignore the overflow, which leads to much less
1055 // efficient code if the width of the subtraction is wider than the native
1056 // register width.
1057 //
1058 // (It's possible to not widen at all by pulling out factors of 2 before
1059 // the multiplication; for example, K=2 can be calculated as
1060 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1061 // extra arithmetic, so it's not an obvious win, and it gets
1062 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001063
Eli Friedman61f67622008-08-04 23:49:06 +00001064 // Protection from insane SCEVs; this bound is conservative,
1065 // but it probably doesn't matter.
1066 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001067 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001068
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001069 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001070
Eli Friedman61f67622008-08-04 23:49:06 +00001071 // Calculate K! / 2^T and T; we divide out the factors of two before
1072 // multiplying for calculating K! / 2^T to avoid overflow.
1073 // Other overflow doesn't matter because we only care about the bottom
1074 // W bits of the result.
1075 APInt OddFactorial(W, 1);
1076 unsigned T = 1;
1077 for (unsigned i = 3; i <= K; ++i) {
1078 APInt Mult(W, i);
1079 unsigned TwoFactors = Mult.countTrailingZeros();
1080 T += TwoFactors;
1081 Mult = Mult.lshr(TwoFactors);
1082 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001083 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001084
Eli Friedman61f67622008-08-04 23:49:06 +00001085 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001086 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001087
Dan Gohman8b0a4192010-03-01 17:49:51 +00001088 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001089 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001090
1091 // Calculate the multiplicative inverse of K! / 2^T;
1092 // this multiplication factor will perform the exact division by
1093 // K! / 2^T.
1094 APInt Mod = APInt::getSignedMinValue(W+1);
1095 APInt MultiplyFactor = OddFactorial.zext(W+1);
1096 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1097 MultiplyFactor = MultiplyFactor.trunc(W);
1098
1099 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001100 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001101 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001102 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001103 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001104 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001105 Dividend = SE.getMulExpr(Dividend,
1106 SE.getTruncateOrZeroExtend(S, CalculationTy));
1107 }
1108
1109 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001110 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001111
1112 // Truncate the result, and divide by K! / 2^T.
1113
1114 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1115 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001116}
1117
Sanjoy Dasf8570812016-05-29 00:38:22 +00001118/// Return the value of this chain of recurrences at the specified iteration
1119/// number. We can evaluate this recurrence by multiplying each element in the
1120/// chain by the binomial coefficient corresponding to it. In other words, we
1121/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001122///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001123/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001124///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001125/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001126///
Dan Gohmanaf752342009-07-07 17:06:11 +00001127const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001128 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001129 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001130 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001131 // The computation is correct in the face of overflow provided that the
1132 // multiplication is performed _after_ the evaluation of the binomial
1133 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001134 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001135 if (isa<SCEVCouldNotCompute>(Coeff))
1136 return Coeff;
1137
1138 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001139 }
1140 return Result;
1141}
1142
Chris Lattnerd934c702004-04-02 20:23:17 +00001143//===----------------------------------------------------------------------===//
1144// SCEV Expression folder implementations
1145//===----------------------------------------------------------------------===//
1146
Dan Gohmanaf752342009-07-07 17:06:11 +00001147const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001148 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001149 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001150 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001151 assert(isSCEVable(Ty) &&
1152 "This is not a conversion to a SCEVable type!");
1153 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001154
Dan Gohman3a302cb2009-07-13 20:50:19 +00001155 FoldingSetNodeID ID;
1156 ID.AddInteger(scTruncate);
1157 ID.AddPointer(Op);
1158 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001159 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001160 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1161
Dan Gohman3423e722009-06-30 20:13:32 +00001162 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001163 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001164 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001165 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001166
Dan Gohman79af8542009-04-22 16:20:48 +00001167 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001168 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001169 return getTruncateExpr(ST->getOperand(), Ty);
1170
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001171 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001172 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001173 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1174
1175 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001176 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001177 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1178
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001179 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001180 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001181 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1182 SmallVector<const SCEV *, 4> Operands;
1183 bool hasTrunc = false;
1184 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1185 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001186 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1187 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001188 Operands.push_back(S);
1189 }
1190 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001191 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001192 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001193 }
1194
Nick Lewycky5c901f32011-01-19 18:56:00 +00001195 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001196 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001197 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1198 SmallVector<const SCEV *, 4> Operands;
1199 bool hasTrunc = false;
1200 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1201 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001202 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1203 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001204 Operands.push_back(S);
1205 }
1206 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001207 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001208 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001209 }
1210
Dan Gohman5a728c92009-06-18 16:24:47 +00001211 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001212 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001213 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001214 for (const SCEV *Op : AddRec->operands())
1215 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001216 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001217 }
1218
Dan Gohman89dd42a2010-06-25 18:47:08 +00001219 // The cast wasn't folded; create an explicit cast node. We can reuse
1220 // the existing insert position since if we get here, we won't have
1221 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001222 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1223 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001224 UniqueSCEVs.InsertNode(S, IP);
1225 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001226}
1227
Sanjoy Das4153f472015-02-18 01:47:07 +00001228// Get the limit of a recurrence such that incrementing by Step cannot cause
1229// signed overflow as long as the value of the recurrence within the
1230// loop does not exceed this limit before incrementing.
1231static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1232 ICmpInst::Predicate *Pred,
1233 ScalarEvolution *SE) {
1234 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1235 if (SE->isKnownPositive(Step)) {
1236 *Pred = ICmpInst::ICMP_SLT;
1237 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1238 SE->getSignedRange(Step).getSignedMax());
1239 }
1240 if (SE->isKnownNegative(Step)) {
1241 *Pred = ICmpInst::ICMP_SGT;
1242 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1243 SE->getSignedRange(Step).getSignedMin());
1244 }
1245 return nullptr;
1246}
1247
1248// Get the limit of a recurrence such that incrementing by Step cannot cause
1249// unsigned overflow as long as the value of the recurrence within the loop does
1250// not exceed this limit before incrementing.
1251static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1252 ICmpInst::Predicate *Pred,
1253 ScalarEvolution *SE) {
1254 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1255 *Pred = ICmpInst::ICMP_ULT;
1256
1257 return SE->getConstant(APInt::getMinValue(BitWidth) -
1258 SE->getUnsignedRange(Step).getUnsignedMax());
1259}
1260
1261namespace {
1262
1263struct ExtendOpTraitsBase {
1264 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1265};
1266
1267// Used to make code generic over signed and unsigned overflow.
1268template <typename ExtendOp> struct ExtendOpTraits {
1269 // Members present:
1270 //
1271 // static const SCEV::NoWrapFlags WrapType;
1272 //
1273 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1274 //
1275 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276 // ICmpInst::Predicate *Pred,
1277 // ScalarEvolution *SE);
1278};
1279
1280template <>
1281struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1283
1284 static const GetExtendExprTy GetExtendExpr;
1285
1286 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287 ICmpInst::Predicate *Pred,
1288 ScalarEvolution *SE) {
1289 return getSignedOverflowLimitForStep(Step, Pred, SE);
1290 }
1291};
1292
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001293const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001294 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1295
1296template <>
1297struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1299
1300 static const GetExtendExprTy GetExtendExpr;
1301
1302 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303 ICmpInst::Predicate *Pred,
1304 ScalarEvolution *SE) {
1305 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1306 }
1307};
1308
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001309const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001310 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001311}
Sanjoy Das4153f472015-02-18 01:47:07 +00001312
1313// The recurrence AR has been shown to have no signed/unsigned wrap or something
1314// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1315// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1316// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1317// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1318// expression "Step + sext/zext(PreIncAR)" is congruent with
1319// "sext/zext(PostIncAR)"
1320template <typename ExtendOpTy>
1321static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1322 ScalarEvolution *SE) {
1323 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1324 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1325
1326 const Loop *L = AR->getLoop();
1327 const SCEV *Start = AR->getStart();
1328 const SCEV *Step = AR->getStepRecurrence(*SE);
1329
1330 // Check for a simple looking step prior to loop entry.
1331 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1332 if (!SA)
1333 return nullptr;
1334
1335 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1336 // subtraction is expensive. For this purpose, perform a quick and dirty
1337 // difference, by checking for Step in the operand list.
1338 SmallVector<const SCEV *, 4> DiffOps;
1339 for (const SCEV *Op : SA->operands())
1340 if (Op != Step)
1341 DiffOps.push_back(Op);
1342
1343 if (DiffOps.size() == SA->getNumOperands())
1344 return nullptr;
1345
1346 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1347 // `Step`:
1348
1349 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001350 auto PreStartFlags =
1351 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1352 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001353 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1354 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1355
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001356 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1357 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001358 //
1359
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001360 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1361 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1362 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001363 return PreStart;
1364
1365 // 2. Direct overflow check on the step operation's expression.
1366 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1367 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1368 const SCEV *OperandExtendedStart =
1369 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1370 (SE->*GetExtendExpr)(Step, WideTy));
1371 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1372 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1373 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1374 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1375 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1376 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1377 }
1378 return PreStart;
1379 }
1380
1381 // 3. Loop precondition.
1382 ICmpInst::Predicate Pred;
1383 const SCEV *OverflowLimit =
1384 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1385
1386 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001387 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001388 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001389
Sanjoy Das4153f472015-02-18 01:47:07 +00001390 return nullptr;
1391}
1392
1393// Get the normalized zero or sign extended expression for this AddRec's Start.
1394template <typename ExtendOpTy>
1395static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1396 ScalarEvolution *SE) {
1397 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1398
1399 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1400 if (!PreStart)
1401 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1402
1403 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1404 (SE->*GetExtendExpr)(PreStart, Ty));
1405}
1406
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001407// Try to prove away overflow by looking at "nearby" add recurrences. A
1408// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1409// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1410//
1411// Formally:
1412//
1413// {S,+,X} == {S-T,+,X} + T
1414// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1415//
1416// If ({S-T,+,X} + T) does not overflow ... (1)
1417//
1418// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1419//
1420// If {S-T,+,X} does not overflow ... (2)
1421//
1422// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1423// == {Ext(S-T)+Ext(T),+,Ext(X)}
1424//
1425// If (S-T)+T does not overflow ... (3)
1426//
1427// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1428// == {Ext(S),+,Ext(X)} == LHS
1429//
1430// Thus, if (1), (2) and (3) are true for some T, then
1431// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1432//
1433// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1434// does not overflow" restricted to the 0th iteration. Therefore we only need
1435// to check for (1) and (2).
1436//
1437// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1438// is `Delta` (defined below).
1439//
1440template <typename ExtendOpTy>
1441bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1442 const SCEV *Step,
1443 const Loop *L) {
1444 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1445
1446 // We restrict `Start` to a constant to prevent SCEV from spending too much
1447 // time here. It is correct (but more expensive) to continue with a
1448 // non-constant `Start` and do a general SCEV subtraction to compute
1449 // `PreStart` below.
1450 //
1451 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1452 if (!StartC)
1453 return false;
1454
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001455 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001456
1457 for (unsigned Delta : {-2, -1, 1, 2}) {
1458 const SCEV *PreStart = getConstant(StartAI - Delta);
1459
Sanjoy Das42801102015-10-23 06:57:21 +00001460 FoldingSetNodeID ID;
1461 ID.AddInteger(scAddRecExpr);
1462 ID.AddPointer(PreStart);
1463 ID.AddPointer(Step);
1464 ID.AddPointer(L);
1465 void *IP = nullptr;
1466 const auto *PreAR =
1467 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1468
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001469 // Give up if we don't already have the add recurrence we need because
1470 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001471 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1472 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1473 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1474 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1475 DeltaS, &Pred, this);
1476 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1477 return true;
1478 }
1479 }
1480
1481 return false;
1482}
1483
Dan Gohmanaf752342009-07-07 17:06:11 +00001484const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001485 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001486 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001487 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001488 assert(isSCEVable(Ty) &&
1489 "This is not a conversion to a SCEVable type!");
1490 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001491
Dan Gohman3423e722009-06-30 20:13:32 +00001492 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001493 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1494 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001495 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001496
Dan Gohman79af8542009-04-22 16:20:48 +00001497 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001498 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001499 return getZeroExtendExpr(SZ->getOperand(), Ty);
1500
Dan Gohman74a0ba12009-07-13 20:55:53 +00001501 // Before doing any expensive analysis, check to see if we've already
1502 // computed a SCEV for this Op and Ty.
1503 FoldingSetNodeID ID;
1504 ID.AddInteger(scZeroExtend);
1505 ID.AddPointer(Op);
1506 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001507 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001508 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1509
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001510 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1511 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1512 // It's possible the bits taken off by the truncate were all zero bits. If
1513 // so, we should be able to simplify this further.
1514 const SCEV *X = ST->getOperand();
1515 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001516 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1517 unsigned NewBits = getTypeSizeInBits(Ty);
1518 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001519 CR.zextOrTrunc(NewBits)))
1520 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001521 }
1522
Dan Gohman76466372009-04-27 20:16:15 +00001523 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001524 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001525 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001526 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001527 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001528 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001529 const SCEV *Start = AR->getStart();
1530 const SCEV *Step = AR->getStepRecurrence(*this);
1531 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1532 const Loop *L = AR->getLoop();
1533
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001534 if (!AR->hasNoUnsignedWrap()) {
1535 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1536 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1537 }
1538
Dan Gohman62ef6a72009-07-25 01:22:26 +00001539 // If we have special knowledge that this addrec won't overflow,
1540 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001541 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001542 return getAddRecExpr(
1543 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1544 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001545
Dan Gohman76466372009-04-27 20:16:15 +00001546 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1547 // Note that this serves two purposes: It filters out loops that are
1548 // simply not analyzable, and it covers the case where this code is
1549 // being called from within backedge-taken count analysis, such that
1550 // attempting to ask for the backedge-taken count would likely result
1551 // in infinite recursion. In the later case, the analysis code will
1552 // cope with a conservative value, and it will take care to purge
1553 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001554 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001555 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001556 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001557 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001558
1559 // Check whether the backedge-taken count can be losslessly casted to
1560 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001561 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001562 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001563 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001564 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1565 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001566 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001567 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001568 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001569 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1570 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1571 const SCEV *WideMaxBECount =
1572 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001573 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001574 getAddExpr(WideStart,
1575 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001576 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001577 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001578 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1579 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001580 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001581 return getAddRecExpr(
1582 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1583 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001584 }
Dan Gohman76466372009-04-27 20:16:15 +00001585 // Similar to above, only this time treat the step value as signed.
1586 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001587 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001588 getAddExpr(WideStart,
1589 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001590 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001591 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001592 // Cache knowledge of AR NW, which is propagated to this AddRec.
1593 // Negative step causes unsigned wrap, but it still can't self-wrap.
1594 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001595 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001596 return getAddRecExpr(
1597 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1598 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001599 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001600 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001601 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001602
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001603 // Normally, in the cases we can prove no-overflow via a
1604 // backedge guarding condition, we can also compute a backedge
1605 // taken count for the loop. The exceptions are assumptions and
1606 // guards present in the loop -- SCEV is not great at exploiting
1607 // these to compute max backedge taken counts, but can still use
1608 // these to prove lack of overflow. Use this fact to avoid
1609 // doing extra work that may not pay off.
1610 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001611 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001612 // If the backedge is guarded by a comparison with the pre-inc
1613 // value the addrec is safe. Also, if the entry is guarded by
1614 // a comparison with the start value and the backedge is
1615 // guarded by a comparison with the post-inc value, the addrec
1616 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001617 if (isKnownPositive(Step)) {
1618 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1619 getUnsignedRange(Step).getUnsignedMax());
1620 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001621 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001622 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001623 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001624 // Cache knowledge of AR NUW, which is propagated to this
1625 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001626 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001627 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001628 return getAddRecExpr(
1629 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1630 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001631 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001632 } else if (isKnownNegative(Step)) {
1633 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1634 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001635 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1636 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001637 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001638 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001639 // Cache knowledge of AR NW, which is propagated to this
1640 // AddRec. Negative step causes unsigned wrap, but it
1641 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001642 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1643 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001644 return getAddRecExpr(
1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1646 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001647 }
Dan Gohman76466372009-04-27 20:16:15 +00001648 }
1649 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001650
1651 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1652 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1653 return getAddRecExpr(
1654 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1655 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1656 }
Dan Gohman76466372009-04-27 20:16:15 +00001657 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001658
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001659 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1660 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001661 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001662 // If the addition does not unsign overflow then we can, by definition,
1663 // commute the zero extension with the addition operation.
1664 SmallVector<const SCEV *, 4> Ops;
1665 for (const auto *Op : SA->operands())
1666 Ops.push_back(getZeroExtendExpr(Op, Ty));
1667 return getAddExpr(Ops, SCEV::FlagNUW);
1668 }
1669 }
1670
Dan Gohman74a0ba12009-07-13 20:55:53 +00001671 // The cast wasn't folded; create an explicit cast node.
1672 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001673 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001674 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1675 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001676 UniqueSCEVs.InsertNode(S, IP);
1677 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001678}
1679
Dan Gohmanaf752342009-07-07 17:06:11 +00001680const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001681 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001682 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001683 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001684 assert(isSCEVable(Ty) &&
1685 "This is not a conversion to a SCEVable type!");
1686 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001687
Dan Gohman3423e722009-06-30 20:13:32 +00001688 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001689 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1690 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001691 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001692
Dan Gohman79af8542009-04-22 16:20:48 +00001693 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001694 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001695 return getSignExtendExpr(SS->getOperand(), Ty);
1696
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001697 // sext(zext(x)) --> zext(x)
1698 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1699 return getZeroExtendExpr(SZ->getOperand(), Ty);
1700
Dan Gohman74a0ba12009-07-13 20:55:53 +00001701 // Before doing any expensive analysis, check to see if we've already
1702 // computed a SCEV for this Op and Ty.
1703 FoldingSetNodeID ID;
1704 ID.AddInteger(scSignExtend);
1705 ID.AddPointer(Op);
1706 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001707 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001708 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1709
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001710 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1711 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1712 // It's possible the bits taken off by the truncate were all sign bits. If
1713 // so, we should be able to simplify this further.
1714 const SCEV *X = ST->getOperand();
1715 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001716 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1717 unsigned NewBits = getTypeSizeInBits(Ty);
1718 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001719 CR.sextOrTrunc(NewBits)))
1720 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001721 }
1722
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001723 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001724 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001725 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001726 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1727 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001728 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001729 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001730 const APInt &C1 = SC1->getAPInt();
1731 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001732 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001733 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001734 return getAddExpr(getSignExtendExpr(SC1, Ty),
1735 getSignExtendExpr(SMul, Ty));
1736 }
1737 }
1738 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001739
1740 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001741 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001742 // If the addition does not sign overflow then we can, by definition,
1743 // commute the sign extension with the addition operation.
1744 SmallVector<const SCEV *, 4> Ops;
1745 for (const auto *Op : SA->operands())
1746 Ops.push_back(getSignExtendExpr(Op, Ty));
1747 return getAddExpr(Ops, SCEV::FlagNSW);
1748 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001749 }
Dan Gohman76466372009-04-27 20:16:15 +00001750 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001751 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001752 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001753 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001754 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001755 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001756 const SCEV *Start = AR->getStart();
1757 const SCEV *Step = AR->getStepRecurrence(*this);
1758 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1759 const Loop *L = AR->getLoop();
1760
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001761 if (!AR->hasNoSignedWrap()) {
1762 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1763 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1764 }
1765
Dan Gohman62ef6a72009-07-25 01:22:26 +00001766 // If we have special knowledge that this addrec won't overflow,
1767 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001768 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001769 return getAddRecExpr(
1770 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1771 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001772
Dan Gohman76466372009-04-27 20:16:15 +00001773 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1774 // Note that this serves two purposes: It filters out loops that are
1775 // simply not analyzable, and it covers the case where this code is
1776 // being called from within backedge-taken count analysis, such that
1777 // attempting to ask for the backedge-taken count would likely result
1778 // in infinite recursion. In the later case, the analysis code will
1779 // cope with a conservative value, and it will take care to purge
1780 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001781 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001782 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001783 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001784 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001785
1786 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001787 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001788 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001789 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001790 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001791 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1792 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001793 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001794 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001795 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001796 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1797 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1798 const SCEV *WideMaxBECount =
1799 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001800 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001801 getAddExpr(WideStart,
1802 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001803 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001804 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001805 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1806 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001807 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001808 return getAddRecExpr(
1809 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1810 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001811 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001812 // Similar to above, only this time treat the step value as unsigned.
1813 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001814 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001815 getAddExpr(WideStart,
1816 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001817 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001818 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001819 // If AR wraps around then
1820 //
1821 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1822 // => SAdd != OperandExtendedAdd
1823 //
1824 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1825 // (SAdd == OperandExtendedAdd => AR is NW)
1826
1827 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1828
Dan Gohman8c129d72009-07-16 17:34:36 +00001829 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001830 return getAddRecExpr(
1831 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1832 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001833 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001834 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001835 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001836
Sanjoy Das787c2462016-05-11 17:41:26 +00001837 // Normally, in the cases we can prove no-overflow via a
1838 // backedge guarding condition, we can also compute a backedge
1839 // taken count for the loop. The exceptions are assumptions and
1840 // guards present in the loop -- SCEV is not great at exploiting
1841 // these to compute max backedge taken counts, but can still use
1842 // these to prove lack of overflow. Use this fact to avoid
1843 // doing extra work that may not pay off.
1844
1845 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001846 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001847 // If the backedge is guarded by a comparison with the pre-inc
1848 // value the addrec is safe. Also, if the entry is guarded by
1849 // a comparison with the start value and the backedge is
1850 // guarded by a comparison with the post-inc value, the addrec
1851 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001852 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001853 const SCEV *OverflowLimit =
1854 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001855 if (OverflowLimit &&
1856 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1857 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1858 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1859 OverflowLimit)))) {
1860 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1861 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001862 return getAddRecExpr(
1863 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1864 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001865 }
1866 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001867
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001868 // If Start and Step are constants, check if we can apply this
1869 // transformation:
1870 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001871 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1872 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001873 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001874 const APInt &C1 = SC1->getAPInt();
1875 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001876 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1877 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001878 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001879 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1880 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001881 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1882 }
1883 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001884
1885 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1886 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1887 return getAddRecExpr(
1888 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1889 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1890 }
Dan Gohman76466372009-04-27 20:16:15 +00001891 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001892
Sanjoy Das11ef6062016-03-03 18:31:23 +00001893 // If the input value is provably positive and we could not simplify
1894 // away the sext build a zext instead.
1895 if (isKnownNonNegative(Op))
1896 return getZeroExtendExpr(Op, Ty);
1897
Dan Gohman74a0ba12009-07-13 20:55:53 +00001898 // The cast wasn't folded; create an explicit cast node.
1899 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001900 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001901 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1902 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001903 UniqueSCEVs.InsertNode(S, IP);
1904 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001905}
1906
Dan Gohman8db2edc2009-06-13 15:56:47 +00001907/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1908/// unspecified bits out to the given type.
1909///
Dan Gohmanaf752342009-07-07 17:06:11 +00001910const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001911 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001912 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1913 "This is not an extending conversion!");
1914 assert(isSCEVable(Ty) &&
1915 "This is not a conversion to a SCEVable type!");
1916 Ty = getEffectiveSCEVType(Ty);
1917
1918 // Sign-extend negative constants.
1919 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001920 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001921 return getSignExtendExpr(Op, Ty);
1922
1923 // Peel off a truncate cast.
1924 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001925 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001926 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1927 return getAnyExtendExpr(NewOp, Ty);
1928 return getTruncateOrNoop(NewOp, Ty);
1929 }
1930
1931 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001932 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001933 if (!isa<SCEVZeroExtendExpr>(ZExt))
1934 return ZExt;
1935
1936 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001937 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001938 if (!isa<SCEVSignExtendExpr>(SExt))
1939 return SExt;
1940
Dan Gohman51ad99d2010-01-21 02:09:26 +00001941 // Force the cast to be folded into the operands of an addrec.
1942 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1943 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001944 for (const SCEV *Op : AR->operands())
1945 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001946 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001947 }
1948
Dan Gohman8db2edc2009-06-13 15:56:47 +00001949 // If the expression is obviously signed, use the sext cast value.
1950 if (isa<SCEVSMaxExpr>(Op))
1951 return SExt;
1952
1953 // Absent any other information, use the zext cast value.
1954 return ZExt;
1955}
1956
Sanjoy Dasf8570812016-05-29 00:38:22 +00001957/// Process the given Ops list, which is a list of operands to be added under
1958/// the given scale, update the given map. This is a helper function for
1959/// getAddRecExpr. As an example of what it does, given a sequence of operands
1960/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001961///
Tobias Grosserba49e422014-03-05 10:37:17 +00001962/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001963///
1964/// where A and B are constants, update the map with these values:
1965///
1966/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1967///
1968/// and add 13 + A*B*29 to AccumulatedConstant.
1969/// This will allow getAddRecExpr to produce this:
1970///
1971/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1972///
1973/// This form often exposes folding opportunities that are hidden in
1974/// the original operand list.
1975///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001976/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001977/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1978/// the common case where no interesting opportunities are present, and
1979/// is also used as a check to avoid infinite recursion.
1980///
1981static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001982CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001983 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001984 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001985 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001986 const APInt &Scale,
1987 ScalarEvolution &SE) {
1988 bool Interesting = false;
1989
Dan Gohman45073042010-06-18 19:12:32 +00001990 // Iterate over the add operands. They are sorted, with constants first.
1991 unsigned i = 0;
1992 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1993 ++i;
1994 // Pull a buried constant out to the outside.
1995 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1996 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001997 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001998 }
1999
2000 // Next comes everything else. We're especially interested in multiplies
2001 // here, but they're in the middle, so just visit the rest with one loop.
2002 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002003 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2004 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2005 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002006 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002007 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2008 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002009 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002010 Interesting |=
2011 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002012 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002013 NewScale, SE);
2014 } else {
2015 // A multiplication of a constant with some other value. Update
2016 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002017 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2018 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002019 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002020 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002021 NewOps.push_back(Pair.first->first);
2022 } else {
2023 Pair.first->second += NewScale;
2024 // The map already had an entry for this value, which may indicate
2025 // a folding opportunity.
2026 Interesting = true;
2027 }
2028 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002029 } else {
2030 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002031 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002032 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002033 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002034 NewOps.push_back(Pair.first->first);
2035 } else {
2036 Pair.first->second += Scale;
2037 // The map already had an entry for this value, which may indicate
2038 // a folding opportunity.
2039 Interesting = true;
2040 }
2041 }
2042 }
2043
2044 return Interesting;
2045}
2046
Sanjoy Das81401d42015-01-10 23:41:24 +00002047// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2048// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2049// can't-overflow flags for the operation if possible.
2050static SCEV::NoWrapFlags
2051StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2052 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002053 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002054 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002055 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002056
2057 bool CanAnalyze =
2058 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2059 (void)CanAnalyze;
2060 assert(CanAnalyze && "don't call from other places!");
2061
2062 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2063 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002064 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002065
2066 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002067 auto IsKnownNonNegative = [&](const SCEV *S) {
2068 return SE->isKnownNonNegative(S);
2069 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002070
Sanjoy Das3b827c72015-11-29 23:40:53 +00002071 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002072 Flags =
2073 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002074
Sanjoy Das8f274152015-10-22 19:57:19 +00002075 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2076
2077 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2078 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2079
2080 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2081 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2082
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002083 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002084 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002085 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2086 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002087 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2088 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2089 }
2090 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002091 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2092 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002093 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2094 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2095 }
2096 }
2097
2098 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002099}
2100
Sanjoy Dasf8570812016-05-29 00:38:22 +00002101/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002102const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002103 SCEV::NoWrapFlags Flags) {
2104 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2105 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002106 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002107 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002108#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002109 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002110 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002111 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002112 "SCEVAddExpr operand types don't match!");
2113#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002114
2115 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002116 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002117
Sanjoy Das64895612015-10-09 02:44:45 +00002118 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2119
Chris Lattnerd934c702004-04-02 20:23:17 +00002120 // If there are any constants, fold them together.
2121 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002122 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002123 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002124 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002125 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002126 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002127 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002128 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002129 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002130 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002131 }
2132
2133 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002134 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002135 Ops.erase(Ops.begin());
2136 --Idx;
2137 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002138
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002139 if (Ops.size() == 1) return Ops[0];
2140 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002141
Dan Gohman15871f22010-08-27 21:39:59 +00002142 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002143 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002144 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002145 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002146 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002147 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002148 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002149 // Scan ahead to count how many equal operands there are.
2150 unsigned Count = 2;
2151 while (i+Count != e && Ops[i+Count] == Ops[i])
2152 ++Count;
2153 // Merge the values into a multiply.
2154 const SCEV *Scale = getConstant(Ty, Count);
2155 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2156 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002157 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002158 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002159 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002160 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002161 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002162 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002163 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002164 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002165
Dan Gohman2e55cc52009-05-08 21:03:19 +00002166 // Check for truncates. If all the operands are truncated from the same
2167 // type, see if factoring out the truncate would permit the result to be
2168 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2169 // if the contents of the resulting outer trunc fold to something simple.
2170 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2171 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002172 Type *DstType = Trunc->getType();
2173 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002174 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002175 bool Ok = true;
2176 // Check all the operands to see if they can be represented in the
2177 // source type of the truncate.
2178 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2179 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2180 if (T->getOperand()->getType() != SrcType) {
2181 Ok = false;
2182 break;
2183 }
2184 LargeOps.push_back(T->getOperand());
2185 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002186 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002187 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002188 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002189 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2190 if (const SCEVTruncateExpr *T =
2191 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2192 if (T->getOperand()->getType() != SrcType) {
2193 Ok = false;
2194 break;
2195 }
2196 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002197 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002198 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002199 } else {
2200 Ok = false;
2201 break;
2202 }
2203 }
2204 if (Ok)
2205 LargeOps.push_back(getMulExpr(LargeMulOps));
2206 } else {
2207 Ok = false;
2208 break;
2209 }
2210 }
2211 if (Ok) {
2212 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002213 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002214 // If it folds to something simple, use it. Otherwise, don't.
2215 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2216 return getTruncateExpr(Fold, DstType);
2217 }
2218 }
2219
2220 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002221 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2222 ++Idx;
2223
2224 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002225 if (Idx < Ops.size()) {
2226 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002227 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Daniil Fukalovb09dac52017-01-26 13:33:17 +00002228 if (Ops.size() > AddOpsInlineThreshold ||
2229 Add->getNumOperands() > AddOpsInlineThreshold)
2230 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002231 // If we have an add, expand the add operands onto the end of the operands
2232 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002233 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002234 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002235 DeletedAdd = true;
2236 }
2237
2238 // If we deleted at least one add, we added operands to the end of the list,
2239 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002240 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002241 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002242 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002243 }
2244
2245 // Skip over the add expression until we get to a multiply.
2246 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2247 ++Idx;
2248
Dan Gohman038d02e2009-06-14 22:58:51 +00002249 // Check to see if there are any folding opportunities present with
2250 // operands multiplied by constant values.
2251 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2252 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002253 DenseMap<const SCEV *, APInt> M;
2254 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002255 APInt AccumulatedConstant(BitWidth, 0);
2256 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002257 Ops.data(), Ops.size(),
2258 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002259 struct APIntCompare {
2260 bool operator()(const APInt &LHS, const APInt &RHS) const {
2261 return LHS.ult(RHS);
2262 }
2263 };
2264
Dan Gohman038d02e2009-06-14 22:58:51 +00002265 // Some interesting folding opportunity is present, so its worthwhile to
2266 // re-generate the operands list. Group the operands by constant scale,
2267 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002268 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002269 for (const SCEV *NewOp : NewOps)
2270 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002271 // Re-generate the operands list.
2272 Ops.clear();
2273 if (AccumulatedConstant != 0)
2274 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002275 for (auto &MulOp : MulOpLists)
2276 if (MulOp.first != 0)
2277 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2278 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002279 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002280 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002281 if (Ops.size() == 1)
2282 return Ops[0];
2283 return getAddExpr(Ops);
2284 }
2285 }
2286
Chris Lattnerd934c702004-04-02 20:23:17 +00002287 // If we are adding something to a multiply expression, make sure the
2288 // something is not already an operand of the multiply. If so, merge it into
2289 // the multiply.
2290 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002291 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002292 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002293 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002294 if (isa<SCEVConstant>(MulOpSCEV))
2295 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002296 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002297 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002298 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002299 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002300 if (Mul->getNumOperands() != 2) {
2301 // If the multiply has more than two operands, we must get the
2302 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002303 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2304 Mul->op_begin()+MulOp);
2305 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002306 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002307 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002308 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002309 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002310 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002311 if (Ops.size() == 2) return OuterMul;
2312 if (AddOp < Idx) {
2313 Ops.erase(Ops.begin()+AddOp);
2314 Ops.erase(Ops.begin()+Idx-1);
2315 } else {
2316 Ops.erase(Ops.begin()+Idx);
2317 Ops.erase(Ops.begin()+AddOp-1);
2318 }
2319 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002320 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002321 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002322
Chris Lattnerd934c702004-04-02 20:23:17 +00002323 // Check this multiply against other multiplies being added together.
2324 for (unsigned OtherMulIdx = Idx+1;
2325 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2326 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002327 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002328 // If MulOp occurs in OtherMul, we can fold the two multiplies
2329 // together.
2330 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2331 OMulOp != e; ++OMulOp)
2332 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2333 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002334 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002335 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002336 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002337 Mul->op_begin()+MulOp);
2338 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002339 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002340 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002341 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002342 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002343 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002344 OtherMul->op_begin()+OMulOp);
2345 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002346 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002347 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002348 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2349 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002350 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002351 Ops.erase(Ops.begin()+Idx);
2352 Ops.erase(Ops.begin()+OtherMulIdx-1);
2353 Ops.push_back(OuterMul);
2354 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002355 }
2356 }
2357 }
2358 }
2359
2360 // If there are any add recurrences in the operands list, see if any other
2361 // added values are loop invariant. If so, we can fold them into the
2362 // recurrence.
2363 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2364 ++Idx;
2365
2366 // Scan over all recurrences, trying to fold loop invariants into them.
2367 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2368 // Scan all of the other operands to this add and add them to the vector if
2369 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002370 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002371 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002372 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002373 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002374 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002375 LIOps.push_back(Ops[i]);
2376 Ops.erase(Ops.begin()+i);
2377 --i; --e;
2378 }
2379
2380 // If we found some loop invariants, fold them into the recurrence.
2381 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002382 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002383 LIOps.push_back(AddRec->getStart());
2384
Dan Gohmanaf752342009-07-07 17:06:11 +00002385 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002386 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002387 // This follows from the fact that the no-wrap flags on the outer add
2388 // expression are applicable on the 0th iteration, when the add recurrence
2389 // will be equal to its start value.
2390 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002391
Dan Gohman16206132010-06-30 07:16:37 +00002392 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002393 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002394 // Always propagate NW.
2395 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002396 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002397
Chris Lattnerd934c702004-04-02 20:23:17 +00002398 // If all of the other operands were loop invariant, we are done.
2399 if (Ops.size() == 1) return NewRec;
2400
Nick Lewyckydb66b822011-09-06 05:08:09 +00002401 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002402 for (unsigned i = 0;; ++i)
2403 if (Ops[i] == AddRec) {
2404 Ops[i] = NewRec;
2405 break;
2406 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002407 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002408 }
2409
2410 // Okay, if there weren't any loop invariants to be folded, check to see if
2411 // there are multiple AddRec's with the same loop induction variable being
2412 // added together. If so, we can fold them.
2413 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002414 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2415 ++OtherIdx)
2416 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2417 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2418 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2419 AddRec->op_end());
2420 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2421 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002422 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002423 if (OtherAddRec->getLoop() == AddRecLoop) {
2424 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2425 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002426 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002427 AddRecOps.append(OtherAddRec->op_begin()+i,
2428 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002429 break;
2430 }
Dan Gohman028c1812010-08-29 14:53:34 +00002431 AddRecOps[i] = getAddExpr(AddRecOps[i],
2432 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002433 }
2434 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002435 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002436 // Step size has changed, so we cannot guarantee no self-wraparound.
2437 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002438 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002439 }
2440
2441 // Otherwise couldn't fold anything into this recurrence. Move onto the
2442 // next one.
2443 }
2444
2445 // Okay, it looks like we really DO need an add expr. Check to see if we
2446 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002447 FoldingSetNodeID ID;
2448 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002449 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2450 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002451 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002452 SCEVAddExpr *S =
2453 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2454 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002455 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2456 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002457 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2458 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002459 UniqueSCEVs.InsertNode(S, IP);
2460 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002461 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002462 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002463}
2464
Nick Lewycky287682e2011-10-04 06:51:26 +00002465static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2466 uint64_t k = i*j;
2467 if (j > 1 && k / j != i) Overflow = true;
2468 return k;
2469}
2470
2471/// Compute the result of "n choose k", the binomial coefficient. If an
2472/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002473/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002474static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2475 // We use the multiplicative formula:
2476 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2477 // At each iteration, we take the n-th term of the numeral and divide by the
2478 // (k-n)th term of the denominator. This division will always produce an
2479 // integral result, and helps reduce the chance of overflow in the
2480 // intermediate computations. However, we can still overflow even when the
2481 // final result would fit.
2482
2483 if (n == 0 || n == k) return 1;
2484 if (k > n) return 0;
2485
2486 if (k > n/2)
2487 k = n-k;
2488
2489 uint64_t r = 1;
2490 for (uint64_t i = 1; i <= k; ++i) {
2491 r = umul_ov(r, n-(i-1), Overflow);
2492 r /= i;
2493 }
2494 return r;
2495}
2496
Nick Lewycky05044c22014-12-06 00:45:50 +00002497/// Determine if any of the operands in this SCEV are a constant or if
2498/// any of the add or multiply expressions in this SCEV contain a constant.
2499static bool containsConstantSomewhere(const SCEV *StartExpr) {
2500 SmallVector<const SCEV *, 4> Ops;
2501 Ops.push_back(StartExpr);
2502 while (!Ops.empty()) {
2503 const SCEV *CurrentExpr = Ops.pop_back_val();
2504 if (isa<SCEVConstant>(*CurrentExpr))
2505 return true;
2506
2507 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2508 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002509 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002510 }
2511 }
2512 return false;
2513}
2514
Sanjoy Dasf8570812016-05-29 00:38:22 +00002515/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002516const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002517 SCEV::NoWrapFlags Flags) {
2518 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2519 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002520 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002521 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002522#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002523 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002524 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002525 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002526 "SCEVMulExpr operand types don't match!");
2527#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002528
2529 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002530 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002531
Sanjoy Das64895612015-10-09 02:44:45 +00002532 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2533
Chris Lattnerd934c702004-04-02 20:23:17 +00002534 // If there are any constants, fold them together.
2535 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002536 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002537
2538 // C1*(C2+V) -> C1*C2 + C1*V
2539 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002540 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2541 // If any of Add's ops are Adds or Muls with a constant,
2542 // apply this transformation as well.
2543 if (Add->getNumOperands() == 2)
2544 if (containsConstantSomewhere(Add))
2545 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2546 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002547
Chris Lattnerd934c702004-04-02 20:23:17 +00002548 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002549 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002550 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002551 ConstantInt *Fold =
2552 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002553 Ops[0] = getConstant(Fold);
2554 Ops.erase(Ops.begin()+1); // Erase the folded element
2555 if (Ops.size() == 1) return Ops[0];
2556 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002557 }
2558
2559 // If we are left with a constant one being multiplied, strip it off.
2560 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2561 Ops.erase(Ops.begin());
2562 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002563 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002564 // If we have a multiply of zero, it will always be zero.
2565 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002566 } else if (Ops[0]->isAllOnesValue()) {
2567 // If we have a mul by -1 of an add, try distributing the -1 among the
2568 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002569 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002570 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2571 SmallVector<const SCEV *, 4> NewOps;
2572 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002573 for (const SCEV *AddOp : Add->operands()) {
2574 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002575 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2576 NewOps.push_back(Mul);
2577 }
2578 if (AnyFolded)
2579 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002580 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002581 // Negation preserves a recurrence's no self-wrap property.
2582 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002583 for (const SCEV *AddRecOp : AddRec->operands())
2584 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2585
Andrew Tricke92dcce2011-03-14 17:38:54 +00002586 return getAddRecExpr(Operands, AddRec->getLoop(),
2587 AddRec->getNoWrapFlags(SCEV::FlagNW));
2588 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002589 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002590 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002591
2592 if (Ops.size() == 1)
2593 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002594 }
2595
2596 // Skip over the add expression until we get to a multiply.
2597 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2598 ++Idx;
2599
Chris Lattnerd934c702004-04-02 20:23:17 +00002600 // If there are mul operands inline them all into this expression.
2601 if (Idx < Ops.size()) {
2602 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002603 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002604 if (Ops.size() > MulOpsInlineThreshold)
2605 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002606 // If we have an mul, expand the mul operands onto the end of the operands
2607 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002608 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002609 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002610 DeletedMul = true;
2611 }
2612
2613 // If we deleted at least one mul, we added operands to the end of the list,
2614 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002615 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002616 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002617 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002618 }
2619
2620 // If there are any add recurrences in the operands list, see if any other
2621 // added values are loop invariant. If so, we can fold them into the
2622 // recurrence.
2623 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2624 ++Idx;
2625
2626 // Scan over all recurrences, trying to fold loop invariants into them.
2627 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2628 // Scan all of the other operands to this mul and add them to the vector if
2629 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002630 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002631 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002632 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002633 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002634 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002635 LIOps.push_back(Ops[i]);
2636 Ops.erase(Ops.begin()+i);
2637 --i; --e;
2638 }
2639
2640 // If we found some loop invariants, fold them into the recurrence.
2641 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002642 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002643 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002644 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002645 const SCEV *Scale = getMulExpr(LIOps);
2646 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2647 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002648
Dan Gohman16206132010-06-30 07:16:37 +00002649 // Build the new addrec. Propagate the NUW and NSW flags if both the
2650 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002651 //
2652 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002653 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002654 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2655 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002656
2657 // If all of the other operands were loop invariant, we are done.
2658 if (Ops.size() == 1) return NewRec;
2659
Nick Lewyckydb66b822011-09-06 05:08:09 +00002660 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002661 for (unsigned i = 0;; ++i)
2662 if (Ops[i] == AddRec) {
2663 Ops[i] = NewRec;
2664 break;
2665 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002666 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002667 }
2668
2669 // Okay, if there weren't any loop invariants to be folded, check to see if
2670 // there are multiple AddRec's with the same loop induction variable being
2671 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002672
2673 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2674 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2675 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2676 // ]]],+,...up to x=2n}.
2677 // Note that the arguments to choose() are always integers with values
2678 // known at compile time, never SCEV objects.
2679 //
2680 // The implementation avoids pointless extra computations when the two
2681 // addrec's are of different length (mathematically, it's equivalent to
2682 // an infinite stream of zeros on the right).
2683 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002684 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002685 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002686 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002687 const SCEVAddRecExpr *OtherAddRec =
2688 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2689 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002690 continue;
2691
Nick Lewycky97756402014-09-01 05:17:15 +00002692 bool Overflow = false;
2693 Type *Ty = AddRec->getType();
2694 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2695 SmallVector<const SCEV*, 7> AddRecOps;
2696 for (int x = 0, xe = AddRec->getNumOperands() +
2697 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002698 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002699 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2700 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2701 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2702 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2703 z < ze && !Overflow; ++z) {
2704 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2705 uint64_t Coeff;
2706 if (LargerThan64Bits)
2707 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2708 else
2709 Coeff = Coeff1*Coeff2;
2710 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2711 const SCEV *Term1 = AddRec->getOperand(y-z);
2712 const SCEV *Term2 = OtherAddRec->getOperand(z);
2713 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002714 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002715 }
Nick Lewycky97756402014-09-01 05:17:15 +00002716 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002717 }
Nick Lewycky97756402014-09-01 05:17:15 +00002718 if (!Overflow) {
2719 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2720 SCEV::FlagAnyWrap);
2721 if (Ops.size() == 2) return NewAddRec;
2722 Ops[Idx] = NewAddRec;
2723 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2724 OpsModified = true;
2725 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2726 if (!AddRec)
2727 break;
2728 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002729 }
Nick Lewycky97756402014-09-01 05:17:15 +00002730 if (OpsModified)
2731 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002732
2733 // Otherwise couldn't fold anything into this recurrence. Move onto the
2734 // next one.
2735 }
2736
2737 // Okay, it looks like we really DO need an mul expr. Check to see if we
2738 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002739 FoldingSetNodeID ID;
2740 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002741 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2742 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002743 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002744 SCEVMulExpr *S =
2745 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2746 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002747 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2748 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002749 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2750 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002751 UniqueSCEVs.InsertNode(S, IP);
2752 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002753 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002754 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002755}
2756
Sanjoy Dasf8570812016-05-29 00:38:22 +00002757/// Get a canonical unsigned division expression, or something simpler if
2758/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002759const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2760 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002761 assert(getEffectiveSCEVType(LHS->getType()) ==
2762 getEffectiveSCEVType(RHS->getType()) &&
2763 "SCEVUDivExpr operand types don't match!");
2764
Dan Gohmana30370b2009-05-04 22:02:23 +00002765 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002766 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002767 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002768 // If the denominator is zero, the result of the udiv is undefined. Don't
2769 // try to analyze it, because the resolution chosen here may differ from
2770 // the resolution chosen in other parts of the compiler.
2771 if (!RHSC->getValue()->isZero()) {
2772 // Determine if the division can be folded into the operands of
2773 // its operands.
2774 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002775 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002776 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002777 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002778 // For non-power-of-two values, effectively round the value up to the
2779 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002780 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002781 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002782 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002783 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002784 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2785 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002786 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2787 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002788 const APInt &StepInt = Step->getAPInt();
2789 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002790 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002791 getZeroExtendExpr(AR, ExtTy) ==
2792 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2793 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002794 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002795 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002796 for (const SCEV *Op : AR->operands())
2797 Operands.push_back(getUDivExpr(Op, RHS));
2798 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002799 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002800 /// Get a canonical UDivExpr for a recurrence.
2801 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2802 // We can currently only fold X%N if X is constant.
2803 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2804 if (StartC && !DivInt.urem(StepInt) &&
2805 getZeroExtendExpr(AR, ExtTy) ==
2806 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2807 getZeroExtendExpr(Step, ExtTy),
2808 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002809 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002810 const APInt &StartRem = StartInt.urem(StepInt);
2811 if (StartRem != 0)
2812 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2813 AR->getLoop(), SCEV::FlagNW);
2814 }
2815 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002816 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2817 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2818 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002819 for (const SCEV *Op : M->operands())
2820 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002821 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2822 // Find an operand that's safely divisible.
2823 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2824 const SCEV *Op = M->getOperand(i);
2825 const SCEV *Div = getUDivExpr(Op, RHSC);
2826 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2827 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2828 M->op_end());
2829 Operands[i] = Div;
2830 return getMulExpr(Operands);
2831 }
2832 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002833 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002834 // (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 +00002835 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002836 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002837 for (const SCEV *Op : A->operands())
2838 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002839 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2840 Operands.clear();
2841 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2842 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2843 if (isa<SCEVUDivExpr>(Op) ||
2844 getMulExpr(Op, RHS) != A->getOperand(i))
2845 break;
2846 Operands.push_back(Op);
2847 }
2848 if (Operands.size() == A->getNumOperands())
2849 return getAddExpr(Operands);
2850 }
2851 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002852
Dan Gohmanacd700a2010-04-22 01:35:11 +00002853 // Fold if both operands are constant.
2854 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2855 Constant *LHSCV = LHSC->getValue();
2856 Constant *RHSCV = RHSC->getValue();
2857 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2858 RHSCV)));
2859 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002860 }
2861 }
2862
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002863 FoldingSetNodeID ID;
2864 ID.AddInteger(scUDivExpr);
2865 ID.AddPointer(LHS);
2866 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002867 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002868 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002869 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2870 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002871 UniqueSCEVs.InsertNode(S, IP);
2872 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002873}
2874
Nick Lewycky31eaca52014-01-27 10:04:03 +00002875static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002876 APInt A = C1->getAPInt().abs();
2877 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002878 uint32_t ABW = A.getBitWidth();
2879 uint32_t BBW = B.getBitWidth();
2880
2881 if (ABW > BBW)
2882 B = B.zext(ABW);
2883 else if (ABW < BBW)
2884 A = A.zext(BBW);
2885
2886 return APIntOps::GreatestCommonDivisor(A, B);
2887}
2888
Sanjoy Dasf8570812016-05-29 00:38:22 +00002889/// Get a canonical unsigned division expression, or something simpler if
2890/// possible. There is no representation for an exact udiv in SCEV IR, but we
2891/// can attempt to remove factors from the LHS and RHS. We can't do this when
2892/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002893const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2894 const SCEV *RHS) {
2895 // TODO: we could try to find factors in all sorts of things, but for now we
2896 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2897 // end of this file for inspiration.
2898
2899 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
Eli Friedmanf1f49c82017-01-18 23:56:42 +00002900 if (!Mul || !Mul->hasNoUnsignedWrap())
Nick Lewycky31eaca52014-01-27 10:04:03 +00002901 return getUDivExpr(LHS, RHS);
2902
2903 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2904 // If the mulexpr multiplies by a constant, then that constant must be the
2905 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002906 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002907 if (LHSCst == RHSCst) {
2908 SmallVector<const SCEV *, 2> Operands;
2909 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2910 return getMulExpr(Operands);
2911 }
2912
2913 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2914 // that there's a factor provided by one of the other terms. We need to
2915 // check.
2916 APInt Factor = gcd(LHSCst, RHSCst);
2917 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002918 LHSCst =
2919 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2920 RHSCst =
2921 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002922 SmallVector<const SCEV *, 2> Operands;
2923 Operands.push_back(LHSCst);
2924 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2925 LHS = getMulExpr(Operands);
2926 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002927 Mul = dyn_cast<SCEVMulExpr>(LHS);
2928 if (!Mul)
2929 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002930 }
2931 }
2932 }
2933
2934 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2935 if (Mul->getOperand(i) == RHS) {
2936 SmallVector<const SCEV *, 2> Operands;
2937 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2938 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2939 return getMulExpr(Operands);
2940 }
2941 }
2942
2943 return getUDivExpr(LHS, RHS);
2944}
Chris Lattnerd934c702004-04-02 20:23:17 +00002945
Sanjoy Dasf8570812016-05-29 00:38:22 +00002946/// Get an add recurrence expression for the specified loop. Simplify the
2947/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002948const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2949 const Loop *L,
2950 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002951 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002952 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002953 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002954 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002955 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002956 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002957 }
2958
2959 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002960 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002961}
2962
Sanjoy Dasf8570812016-05-29 00:38:22 +00002963/// Get an add recurrence expression for the specified loop. Simplify the
2964/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002965const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002966ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002967 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002968 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002969#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002970 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002971 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002972 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002973 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002974 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002975 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002976 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002977#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002978
Dan Gohmanbe928e32008-06-18 16:23:07 +00002979 if (Operands.back()->isZero()) {
2980 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002981 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002982 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002983
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002984 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2985 // use that information to infer NUW and NSW flags. However, computing a
2986 // BE count requires calling getAddRecExpr, so we may not yet have a
2987 // meaningful BE count at this point (and if we don't, we'd be stuck
2988 // with a SCEVCouldNotCompute as the cached BE count).
2989
Sanjoy Das81401d42015-01-10 23:41:24 +00002990 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002991
Dan Gohman223a5d22008-08-08 18:33:12 +00002992 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002993 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002994 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002995 if (L->contains(NestedLoop)
2996 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2997 : (!NestedLoop->contains(L) &&
2998 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002999 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00003000 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00003001 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00003002 // AddRecs require their operands be loop-invariant with respect to their
3003 // loops. Don't perform this transformation if it would break this
3004 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00003005 bool AllInvariant = all_of(
3006 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003007
Dan Gohmancc030b72009-06-26 22:36:20 +00003008 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003009 // Create a recurrence for the outer loop with the same step size.
3010 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003011 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3012 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003013 SCEV::NoWrapFlags OuterFlags =
3014 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003015
3016 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003017 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3018 return isLoopInvariant(Op, NestedLoop);
3019 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003020
Andrew Trick8b55b732011-03-14 16:50:06 +00003021 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003022 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003023 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003024 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3025 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003026 SCEV::NoWrapFlags InnerFlags =
3027 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003028 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3029 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003030 }
3031 // Reset Operands to its original state.
3032 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003033 }
3034 }
3035
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003036 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3037 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003038 FoldingSetNodeID ID;
3039 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003040 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3041 ID.AddPointer(Operands[i]);
3042 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003043 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003044 SCEVAddRecExpr *S =
3045 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3046 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003047 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3048 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003049 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3050 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003051 UniqueSCEVs.InsertNode(S, IP);
3052 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003053 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003054 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003055}
3056
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003057const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003058ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3059 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3060 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003061 // getSCEV(Base)->getType() has the same address space as Base->getType()
3062 // because SCEV::getType() preserves the address space.
3063 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3064 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3065 // instruction to its SCEV, because the Instruction may be guarded by control
3066 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003067 // context. This can be fixed similarly to how these flags are handled for
3068 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003069 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3070 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003071
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003072 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003073 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003074 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003075 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003076 for (const SCEV *IndexExpr : IndexExprs) {
3077 // Compute the (potentially symbolic) offset in bytes for this index.
3078 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3079 // For a struct, add the member offset.
3080 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3081 unsigned FieldNo = Index->getZExtValue();
3082 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3083
3084 // Add the field offset to the running total offset.
3085 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3086
3087 // Update CurTy to the type of the field at Index.
3088 CurTy = STy->getTypeAtIndex(Index);
3089 } else {
3090 // Update CurTy to its element type.
3091 CurTy = cast<SequentialType>(CurTy)->getElementType();
3092 // For an array, add the element offset, explicitly scaled.
3093 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3094 // Getelementptr indices are signed.
3095 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3096
3097 // Multiply the index by the element size to compute the element offset.
3098 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3099
3100 // Add the element offset to the running total offset.
3101 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3102 }
3103 }
3104
3105 // Add the total offset from all the GEP indices to the base.
3106 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3107}
3108
Dan Gohmanabd17092009-06-24 14:49:00 +00003109const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3110 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003111 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003112 return getSMaxExpr(Ops);
3113}
3114
Dan Gohmanaf752342009-07-07 17:06:11 +00003115const SCEV *
3116ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003117 assert(!Ops.empty() && "Cannot get empty smax!");
3118 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003119#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003120 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003121 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003122 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003123 "SCEVSMaxExpr operand types don't match!");
3124#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003125
3126 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003127 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003128
3129 // If there are any constants, fold them together.
3130 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003131 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003132 ++Idx;
3133 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003134 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003135 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003136 ConstantInt *Fold = ConstantInt::get(
3137 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003138 Ops[0] = getConstant(Fold);
3139 Ops.erase(Ops.begin()+1); // Erase the folded element
3140 if (Ops.size() == 1) return Ops[0];
3141 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003142 }
3143
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003144 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003145 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3146 Ops.erase(Ops.begin());
3147 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003148 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3149 // If we have an smax with a constant maximum-int, it will always be
3150 // maximum-int.
3151 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003152 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003153
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003154 if (Ops.size() == 1) return Ops[0];
3155 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003156
3157 // Find the first SMax
3158 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3159 ++Idx;
3160
3161 // Check to see if one of the operands is an SMax. If so, expand its operands
3162 // onto our operand list, and recurse to simplify.
3163 if (Idx < Ops.size()) {
3164 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003165 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003166 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003167 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003168 DeletedSMax = true;
3169 }
3170
3171 if (DeletedSMax)
3172 return getSMaxExpr(Ops);
3173 }
3174
3175 // Okay, check to see if the same value occurs in the operand list twice. If
3176 // so, delete one. Since we sorted the list, these values are required to
3177 // be adjacent.
3178 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003179 // X smax Y smax Y --> X smax Y
3180 // X smax Y --> X, if X is always greater than Y
3181 if (Ops[i] == Ops[i+1] ||
3182 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3183 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3184 --i; --e;
3185 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003186 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3187 --i; --e;
3188 }
3189
3190 if (Ops.size() == 1) return Ops[0];
3191
3192 assert(!Ops.empty() && "Reduced smax down to nothing!");
3193
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003194 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003195 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003196 FoldingSetNodeID ID;
3197 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003198 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3199 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003200 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003201 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003202 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3203 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003204 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3205 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003206 UniqueSCEVs.InsertNode(S, IP);
3207 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003208}
3209
Dan Gohmanabd17092009-06-24 14:49:00 +00003210const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3211 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003212 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003213 return getUMaxExpr(Ops);
3214}
3215
Dan Gohmanaf752342009-07-07 17:06:11 +00003216const SCEV *
3217ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003218 assert(!Ops.empty() && "Cannot get empty umax!");
3219 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003220#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003221 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003222 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003223 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003224 "SCEVUMaxExpr operand types don't match!");
3225#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003226
3227 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003228 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003229
3230 // If there are any constants, fold them together.
3231 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003232 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003233 ++Idx;
3234 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003235 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003236 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003237 ConstantInt *Fold = ConstantInt::get(
3238 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003239 Ops[0] = getConstant(Fold);
3240 Ops.erase(Ops.begin()+1); // Erase the folded element
3241 if (Ops.size() == 1) return Ops[0];
3242 LHSC = cast<SCEVConstant>(Ops[0]);
3243 }
3244
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003245 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003246 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3247 Ops.erase(Ops.begin());
3248 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003249 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3250 // If we have an umax with a constant maximum-int, it will always be
3251 // maximum-int.
3252 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003253 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003254
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003255 if (Ops.size() == 1) return Ops[0];
3256 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003257
3258 // Find the first UMax
3259 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3260 ++Idx;
3261
3262 // Check to see if one of the operands is a UMax. If so, expand its operands
3263 // onto our operand list, and recurse to simplify.
3264 if (Idx < Ops.size()) {
3265 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003266 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003267 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003268 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003269 DeletedUMax = true;
3270 }
3271
3272 if (DeletedUMax)
3273 return getUMaxExpr(Ops);
3274 }
3275
3276 // Okay, check to see if the same value occurs in the operand list twice. If
3277 // so, delete one. Since we sorted the list, these values are required to
3278 // be adjacent.
3279 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003280 // X umax Y umax Y --> X umax Y
3281 // X umax Y --> X, if X is always greater than Y
3282 if (Ops[i] == Ops[i+1] ||
3283 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3284 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3285 --i; --e;
3286 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003287 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3288 --i; --e;
3289 }
3290
3291 if (Ops.size() == 1) return Ops[0];
3292
3293 assert(!Ops.empty() && "Reduced umax down to nothing!");
3294
3295 // Okay, it looks like we really DO need a umax expr. Check to see if we
3296 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003297 FoldingSetNodeID ID;
3298 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003299 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3300 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003301 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003302 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003303 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3304 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003305 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3306 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003307 UniqueSCEVs.InsertNode(S, IP);
3308 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003309}
3310
Dan Gohmanabd17092009-06-24 14:49:00 +00003311const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3312 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003313 // ~smax(~x, ~y) == smin(x, y).
3314 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3315}
3316
Dan Gohmanabd17092009-06-24 14:49:00 +00003317const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3318 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003319 // ~umax(~x, ~y) == umin(x, y)
3320 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3321}
3322
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003323const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003324 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003325 // constant expression and then folding it back into a ConstantInt.
3326 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003327 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003328}
3329
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003330const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3331 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003332 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003333 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003334 // constant expression and then folding it back into a ConstantInt.
3335 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003336 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003337 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003338}
3339
Dan Gohmanaf752342009-07-07 17:06:11 +00003340const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003341 // Don't attempt to do anything other than create a SCEVUnknown object
3342 // here. createSCEV only calls getUnknown after checking for all other
3343 // interesting possibilities, and any other code that calls getUnknown
3344 // is doing so in order to hide a value from SCEV canonicalization.
3345
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003346 FoldingSetNodeID ID;
3347 ID.AddInteger(scUnknown);
3348 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003349 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003350 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3351 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3352 "Stale SCEVUnknown in uniquing map!");
3353 return S;
3354 }
3355 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3356 FirstUnknown);
3357 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003358 UniqueSCEVs.InsertNode(S, IP);
3359 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003360}
3361
Chris Lattnerd934c702004-04-02 20:23:17 +00003362//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003363// Basic SCEV Analysis and PHI Idiom Recognition Code
3364//
3365
Sanjoy Dasf8570812016-05-29 00:38:22 +00003366/// Test if values of the given type are analyzable within the SCEV
3367/// framework. This primarily includes integer types, and it can optionally
3368/// include pointer types if the ScalarEvolution class has access to
3369/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003370bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003371 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003372 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003373}
3374
Sanjoy Dasf8570812016-05-29 00:38:22 +00003375/// Return the size in bits of the specified type, for which isSCEVable must
3376/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003377uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003378 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003379 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003380}
3381
Sanjoy Dasf8570812016-05-29 00:38:22 +00003382/// Return a type with the same bitwidth as the given type and which represents
3383/// how SCEV will treat the given type, for which isSCEVable must return
3384/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003385Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003386 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3387
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003388 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003389 return Ty;
3390
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003391 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003392 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003393 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003394}
Chris Lattnerd934c702004-04-02 20:23:17 +00003395
Dan Gohmanaf752342009-07-07 17:06:11 +00003396const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003397 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003398}
3399
Sanjoy Das7d752672015-12-08 04:32:54 +00003400bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003401 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3402 auto *SU = dyn_cast<SCEVUnknown>(S);
3403 return SU && SU->getValue() == nullptr;
3404 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003405
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003406 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003407}
3408
Wei Mia49559b2016-02-04 01:27:38 +00003409bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003410 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003411 if (I != HasRecMap.end())
3412 return I->second;
3413
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003414 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003415 HasRecMap.insert({S, FoundAddRec});
3416 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003417}
3418
Wei Mi785858c2016-08-09 20:37:50 +00003419/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3420/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3421/// offset I, then return {S', I}, else return {\p S, nullptr}.
3422static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3423 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3424 if (!Add)
3425 return {S, nullptr};
3426
3427 if (Add->getNumOperands() != 2)
3428 return {S, nullptr};
3429
3430 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3431 if (!ConstOp)
3432 return {S, nullptr};
3433
3434 return {Add->getOperand(1), ConstOp->getValue()};
3435}
3436
3437/// Return the ValueOffsetPair set for \p S. \p S can be represented
3438/// by the value and offset from any ValueOffsetPair in the set.
3439SetVector<ScalarEvolution::ValueOffsetPair> *
3440ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003441 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3442 if (SI == ExprValueMap.end())
3443 return nullptr;
3444#ifndef NDEBUG
3445 if (VerifySCEVMap) {
3446 // Check there is no dangling Value in the set returned.
3447 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003448 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003449 }
3450#endif
3451 return &SI->second;
3452}
3453
Wei Mi785858c2016-08-09 20:37:50 +00003454/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3455/// cannot be used separately. eraseValueFromMap should be used to remove
3456/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003457void ScalarEvolution::eraseValueFromMap(Value *V) {
3458 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3459 if (I != ValueExprMap.end()) {
3460 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003461 // Remove {V, 0} from the set of ExprValueMap[S]
3462 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3463 SV->remove({V, nullptr});
3464
3465 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3466 const SCEV *Stripped;
3467 ConstantInt *Offset;
3468 std::tie(Stripped, Offset) = splitAddExpr(S);
3469 if (Offset != nullptr) {
3470 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3471 SV->remove({V, Offset});
3472 }
Wei Mia49559b2016-02-04 01:27:38 +00003473 ValueExprMap.erase(V);
3474 }
3475}
3476
Sanjoy Dasf8570812016-05-29 00:38:22 +00003477/// Return an existing SCEV if it exists, otherwise analyze the expression and
3478/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003479const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003480 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003481
Jingyue Wu42f1d672015-07-28 18:22:40 +00003482 const SCEV *S = getExistingSCEV(V);
3483 if (S == nullptr) {
3484 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003485 // During PHI resolution, it is possible to create two SCEVs for the same
3486 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003487 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003488 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003489 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003490 if (Pair.second) {
3491 ExprValueMap[S].insert({V, nullptr});
3492
3493 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3494 // ExprValueMap.
3495 const SCEV *Stripped = S;
3496 ConstantInt *Offset = nullptr;
3497 std::tie(Stripped, Offset) = splitAddExpr(S);
3498 // If stripped is SCEVUnknown, don't bother to save
3499 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3500 // increase the complexity of the expansion code.
3501 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3502 // because it may generate add/sub instead of GEP in SCEV expansion.
3503 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3504 !isa<GetElementPtrInst>(V))
3505 ExprValueMap[Stripped].insert({V, Offset});
3506 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003507 }
3508 return S;
3509}
3510
3511const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3512 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3513
Shuxin Yangefc4c012013-07-08 17:33:13 +00003514 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3515 if (I != ValueExprMap.end()) {
3516 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003517 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003518 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003519 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003520 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003521 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003522 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003523}
3524
Sanjoy Dasf8570812016-05-29 00:38:22 +00003525/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003526///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003527const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3528 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003529 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003530 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003531 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003532
Chris Lattner229907c2011-07-18 04:54:35 +00003533 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003534 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003535 return getMulExpr(
3536 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003537}
3538
Sanjoy Dasf8570812016-05-29 00:38:22 +00003539/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003540const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003541 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003542 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003543 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003544
Chris Lattner229907c2011-07-18 04:54:35 +00003545 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003546 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003547 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003548 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003549 return getMinusSCEV(AllOnes, V);
3550}
3551
Chris Lattnerfc877522011-01-09 22:26:35 +00003552const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003553 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003554 // Fast path: X - X --> 0.
3555 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003556 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003557
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003558 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3559 // makes it so that we cannot make much use of NUW.
3560 auto AddFlags = SCEV::FlagAnyWrap;
3561 const bool RHSIsNotMinSigned =
3562 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3563 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3564 // Let M be the minimum representable signed value. Then (-1)*RHS
3565 // signed-wraps if and only if RHS is M. That can happen even for
3566 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3567 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3568 // (-1)*RHS, we need to prove that RHS != M.
3569 //
3570 // If LHS is non-negative and we know that LHS - RHS does not
3571 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3572 // either by proving that RHS > M or that LHS >= 0.
3573 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3574 AddFlags = SCEV::FlagNSW;
3575 }
3576 }
3577
3578 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3579 // RHS is NSW and LHS >= 0.
3580 //
3581 // The difficulty here is that the NSW flag may have been proven
3582 // relative to a loop that is to be found in a recurrence in LHS and
3583 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3584 // larger scope than intended.
3585 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3586
3587 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003588}
3589
Dan Gohmanaf752342009-07-07 17:06:11 +00003590const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003591ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3592 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003593 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3594 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003595 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003596 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003597 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003598 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003599 return getTruncateExpr(V, Ty);
3600 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003601}
3602
Dan Gohmanaf752342009-07-07 17:06:11 +00003603const SCEV *
3604ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003605 Type *Ty) {
3606 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003607 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3608 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003609 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003610 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003611 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003612 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003613 return getTruncateExpr(V, Ty);
3614 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003615}
3616
Dan Gohmanaf752342009-07-07 17:06:11 +00003617const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003618ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3619 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003620 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3621 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003622 "Cannot noop or zero extend with non-integer arguments!");
3623 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3624 "getNoopOrZeroExtend cannot truncate!");
3625 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3626 return V; // No conversion
3627 return getZeroExtendExpr(V, Ty);
3628}
3629
Dan Gohmanaf752342009-07-07 17:06:11 +00003630const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003631ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3632 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003633 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3634 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003635 "Cannot noop or sign extend with non-integer arguments!");
3636 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3637 "getNoopOrSignExtend cannot truncate!");
3638 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3639 return V; // No conversion
3640 return getSignExtendExpr(V, Ty);
3641}
3642
Dan Gohmanaf752342009-07-07 17:06:11 +00003643const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003644ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3645 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003646 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3647 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003648 "Cannot noop or any extend with non-integer arguments!");
3649 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3650 "getNoopOrAnyExtend cannot truncate!");
3651 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3652 return V; // No conversion
3653 return getAnyExtendExpr(V, Ty);
3654}
3655
Dan Gohmanaf752342009-07-07 17:06:11 +00003656const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003657ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3658 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003659 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3660 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003661 "Cannot truncate or noop with non-integer arguments!");
3662 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3663 "getTruncateOrNoop cannot extend!");
3664 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3665 return V; // No conversion
3666 return getTruncateExpr(V, Ty);
3667}
3668
Dan Gohmanabd17092009-06-24 14:49:00 +00003669const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3670 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003671 const SCEV *PromotedLHS = LHS;
3672 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003673
3674 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3675 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3676 else
3677 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3678
3679 return getUMaxExpr(PromotedLHS, PromotedRHS);
3680}
3681
Dan Gohmanabd17092009-06-24 14:49:00 +00003682const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3683 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003684 const SCEV *PromotedLHS = LHS;
3685 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003686
3687 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3688 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3689 else
3690 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3691
3692 return getUMinExpr(PromotedLHS, PromotedRHS);
3693}
3694
Andrew Trick87716c92011-03-17 23:51:11 +00003695const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3696 // A pointer operand may evaluate to a nonpointer expression, such as null.
3697 if (!V->getType()->isPointerTy())
3698 return V;
3699
3700 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3701 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003702 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003703 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003704 for (const SCEV *NAryOp : NAry->operands()) {
3705 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003706 // Cannot find the base of an expression with multiple pointer operands.
3707 if (PtrOp)
3708 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003709 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003710 }
3711 }
3712 if (!PtrOp)
3713 return V;
3714 return getPointerBase(PtrOp);
3715 }
3716 return V;
3717}
3718
Sanjoy Dasf8570812016-05-29 00:38:22 +00003719/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003720static void
3721PushDefUseChildren(Instruction *I,
3722 SmallVectorImpl<Instruction *> &Worklist) {
3723 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003724 for (User *U : I->users())
3725 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003726}
3727
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003728void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003729 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003730 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003731
Dan Gohman0b89dff2009-07-25 01:13:03 +00003732 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003733 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003734 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003735 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003736 if (!Visited.insert(I).second)
3737 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003738
Sanjoy Das63914592015-10-18 00:29:20 +00003739 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003740 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003741 const SCEV *Old = It->second;
3742
Dan Gohman0b89dff2009-07-25 01:13:03 +00003743 // Short-circuit the def-use traversal if the symbolic name
3744 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003745 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003746 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003747
Dan Gohman0b89dff2009-07-25 01:13:03 +00003748 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003749 // structure, it's a PHI that's in the progress of being computed
3750 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3751 // additional loop trip count information isn't going to change anything.
3752 // In the second case, createNodeForPHI will perform the necessary
3753 // updates on its own when it gets to that point. In the third, we do
3754 // want to forget the SCEVUnknown.
3755 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003756 !isa<SCEVUnknown>(Old) ||
3757 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003758 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003759 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003760 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003761 }
3762
3763 PushDefUseChildren(I, Worklist);
3764 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003765}
Chris Lattnerd934c702004-04-02 20:23:17 +00003766
Benjamin Kramer83709b12015-11-16 09:01:28 +00003767namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003768class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3769public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003770 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003771 ScalarEvolution &SE) {
3772 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003773 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003774 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3775 }
3776
3777 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3778 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3779
3780 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3781 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3782 Valid = false;
3783 return Expr;
3784 }
3785
3786 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3787 // Only allow AddRecExprs for this loop.
3788 if (Expr->getLoop() == L)
3789 return Expr->getStart();
3790 Valid = false;
3791 return Expr;
3792 }
3793
3794 bool isValid() { return Valid; }
3795
3796private:
3797 const Loop *L;
3798 bool Valid;
3799};
3800
3801class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3802public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003803 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003804 ScalarEvolution &SE) {
3805 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003806 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003807 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3808 }
3809
3810 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3811 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3812
3813 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3814 // Only allow AddRecExprs for this loop.
3815 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3816 Valid = false;
3817 return Expr;
3818 }
3819
3820 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3821 if (Expr->getLoop() == L && Expr->isAffine())
3822 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3823 Valid = false;
3824 return Expr;
3825 }
3826 bool isValid() { return Valid; }
3827
3828private:
3829 const Loop *L;
3830 bool Valid;
3831};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003832} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003833
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003834SCEV::NoWrapFlags
3835ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3836 if (!AR->isAffine())
3837 return SCEV::FlagAnyWrap;
3838
3839 typedef OverflowingBinaryOperator OBO;
3840 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3841
3842 if (!AR->hasNoSignedWrap()) {
3843 ConstantRange AddRecRange = getSignedRange(AR);
3844 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3845
3846 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3847 Instruction::Add, IncRange, OBO::NoSignedWrap);
3848 if (NSWRegion.contains(AddRecRange))
3849 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3850 }
3851
3852 if (!AR->hasNoUnsignedWrap()) {
3853 ConstantRange AddRecRange = getUnsignedRange(AR);
3854 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3855
3856 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3857 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3858 if (NUWRegion.contains(AddRecRange))
3859 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3860 }
3861
3862 return Result;
3863}
3864
Sanjoy Das118d9192016-03-31 05:14:22 +00003865namespace {
3866/// Represents an abstract binary operation. This may exist as a
3867/// normal instruction or constant expression, or may have been
3868/// derived from an expression tree.
3869struct BinaryOp {
3870 unsigned Opcode;
3871 Value *LHS;
3872 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003873 bool IsNSW;
3874 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003875
3876 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3877 /// constant expression.
3878 Operator *Op;
3879
3880 explicit BinaryOp(Operator *Op)
3881 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003882 IsNSW(false), IsNUW(false), Op(Op) {
3883 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3884 IsNSW = OBO->hasNoSignedWrap();
3885 IsNUW = OBO->hasNoUnsignedWrap();
3886 }
3887 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003888
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003889 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3890 bool IsNUW = false)
3891 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3892 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003893};
3894}
3895
3896
3897/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003898static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003899 auto *Op = dyn_cast<Operator>(V);
3900 if (!Op)
3901 return None;
3902
3903 // Implementation detail: all the cleverness here should happen without
3904 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3905 // SCEV expressions when possible, and we should not break that.
3906
3907 switch (Op->getOpcode()) {
3908 case Instruction::Add:
3909 case Instruction::Sub:
3910 case Instruction::Mul:
3911 case Instruction::UDiv:
3912 case Instruction::And:
3913 case Instruction::Or:
3914 case Instruction::AShr:
3915 case Instruction::Shl:
3916 return BinaryOp(Op);
3917
3918 case Instruction::Xor:
3919 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3920 // If the RHS of the xor is a signbit, then this is just an add.
3921 // Instcombine turns add of signbit into xor as a strength reduction step.
3922 if (RHSC->getValue().isSignBit())
3923 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3924 return BinaryOp(Op);
3925
3926 case Instruction::LShr:
3927 // Turn logical shift right of a constant into a unsigned divide.
3928 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3929 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3930
3931 // If the shift count is not less than the bitwidth, the result of
3932 // the shift is undefined. Don't try to analyze it, because the
3933 // resolution chosen here may differ from the resolution chosen in
3934 // other parts of the compiler.
3935 if (SA->getValue().ult(BitWidth)) {
3936 Constant *X =
3937 ConstantInt::get(SA->getContext(),
3938 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3939 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3940 }
3941 }
3942 return BinaryOp(Op);
3943
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003944 case Instruction::ExtractValue: {
3945 auto *EVI = cast<ExtractValueInst>(Op);
3946 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3947 break;
3948
3949 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3950 if (!CI)
3951 break;
3952
3953 if (auto *F = CI->getCalledFunction())
3954 switch (F->getIntrinsicID()) {
3955 case Intrinsic::sadd_with_overflow:
3956 case Intrinsic::uadd_with_overflow: {
3957 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3958 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3959 CI->getArgOperand(1));
3960
3961 // Now that we know that all uses of the arithmetic-result component of
3962 // CI are guarded by the overflow check, we can go ahead and pretend
3963 // that the arithmetic is non-overflowing.
3964 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3965 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3966 CI->getArgOperand(1), /* IsNSW = */ true,
3967 /* IsNUW = */ false);
3968 else
3969 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3970 CI->getArgOperand(1), /* IsNSW = */ false,
3971 /* IsNUW*/ true);
3972 }
3973
3974 case Intrinsic::ssub_with_overflow:
3975 case Intrinsic::usub_with_overflow:
3976 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3977 CI->getArgOperand(1));
3978
3979 case Intrinsic::smul_with_overflow:
3980 case Intrinsic::umul_with_overflow:
3981 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3982 CI->getArgOperand(1));
3983 default:
3984 break;
3985 }
3986 }
3987
Sanjoy Das118d9192016-03-31 05:14:22 +00003988 default:
3989 break;
3990 }
3991
3992 return None;
3993}
3994
Sanjoy Das55015d22015-10-02 23:09:44 +00003995const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3996 const Loop *L = LI.getLoopFor(PN->getParent());
3997 if (!L || L->getHeader() != PN->getParent())
3998 return nullptr;
3999
4000 // The loop may have multiple entrances or multiple exits; we can analyze
4001 // this phi as an addrec if it has a unique entry value and a unique
4002 // backedge value.
4003 Value *BEValueV = nullptr, *StartValueV = nullptr;
4004 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4005 Value *V = PN->getIncomingValue(i);
4006 if (L->contains(PN->getIncomingBlock(i))) {
4007 if (!BEValueV) {
4008 BEValueV = V;
4009 } else if (BEValueV != V) {
4010 BEValueV = nullptr;
4011 break;
4012 }
4013 } else if (!StartValueV) {
4014 StartValueV = V;
4015 } else if (StartValueV != V) {
4016 StartValueV = nullptr;
4017 break;
4018 }
4019 }
4020 if (BEValueV && StartValueV) {
4021 // While we are analyzing this PHI node, handle its value symbolically.
4022 const SCEV *SymbolicName = getUnknown(PN);
4023 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4024 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00004025 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004026
4027 // Using this symbolic name for the PHI, analyze the value coming around
4028 // the back-edge.
4029 const SCEV *BEValue = getSCEV(BEValueV);
4030
4031 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4032 // has a special value for the first iteration of the loop.
4033
4034 // If the value coming around the backedge is an add with the symbolic
4035 // value we just inserted, then we found a simple induction variable!
4036 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4037 // If there is a single occurrence of the symbolic value, replace it
4038 // with a recurrence.
4039 unsigned FoundIndex = Add->getNumOperands();
4040 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4041 if (Add->getOperand(i) == SymbolicName)
4042 if (FoundIndex == e) {
4043 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004044 break;
4045 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004046
4047 if (FoundIndex != Add->getNumOperands()) {
4048 // Create an add with everything but the specified operand.
4049 SmallVector<const SCEV *, 8> Ops;
4050 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4051 if (i != FoundIndex)
4052 Ops.push_back(Add->getOperand(i));
4053 const SCEV *Accum = getAddExpr(Ops);
4054
4055 // This is not a valid addrec if the step amount is varying each
4056 // loop iteration, but is not itself an addrec in this loop.
4057 if (isLoopInvariant(Accum, L) ||
4058 (isa<SCEVAddRecExpr>(Accum) &&
4059 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4060 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4061
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004062 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004063 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4064 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004065 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004066 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004067 Flags = setFlags(Flags, SCEV::FlagNSW);
4068 }
4069 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4070 // If the increment is an inbounds GEP, then we know the address
4071 // space cannot be wrapped around. We cannot make any guarantee
4072 // about signed or unsigned overflow because pointers are
4073 // unsigned but we may have a negative index from the base
4074 // pointer. We can guarantee that no unsigned wrap occurs if the
4075 // indices form a positive value.
4076 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4077 Flags = setFlags(Flags, SCEV::FlagNW);
4078
4079 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4080 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4081 Flags = setFlags(Flags, SCEV::FlagNUW);
4082 }
4083
4084 // We cannot transfer nuw and nsw flags from subtraction
4085 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4086 // for instance.
4087 }
4088
4089 const SCEV *StartVal = getSCEV(StartValueV);
4090 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4091
Sanjoy Das55015d22015-10-02 23:09:44 +00004092 // Okay, for the entire analysis of this edge we assumed the PHI
4093 // to be symbolic. We now need to go back and purge all of the
4094 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004095 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004096 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004097
4098 // We can add Flags to the post-inc expression only if we
4099 // know that it us *undefined behavior* for BEValueV to
4100 // overflow.
4101 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4102 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4103 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4104
Sanjoy Das55015d22015-10-02 23:09:44 +00004105 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004106 }
4107 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004108 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004109 // Otherwise, this could be a loop like this:
4110 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4111 // In this case, j = {1,+,1} and BEValue is j.
4112 // Because the other in-value of i (0) fits the evolution of BEValue
4113 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004114 //
4115 // We can generalize this saying that i is the shifted value of BEValue
4116 // by one iteration:
4117 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4118 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4119 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4120 if (Shifted != getCouldNotCompute() &&
4121 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004122 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004123 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004124 // Okay, for the entire analysis of this edge we assumed the PHI
4125 // to be symbolic. We now need to go back and purge all of the
4126 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004127 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004128 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4129 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004130 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004131 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004132 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004133
4134 // Remove the temporary PHI node SCEV that has been inserted while intending
4135 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4136 // as it will prevent later (possibly simpler) SCEV expressions to be added
4137 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004138 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004139 }
4140
4141 return nullptr;
4142}
4143
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004144// Checks if the SCEV S is available at BB. S is considered available at BB
4145// if S can be materialized at BB without introducing a fault.
4146static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4147 BasicBlock *BB) {
4148 struct CheckAvailable {
4149 bool TraversalDone = false;
4150 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004151
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004152 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4153 BasicBlock *BB = nullptr;
4154 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004155
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004156 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4157 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004158
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004159 bool setUnavailable() {
4160 TraversalDone = true;
4161 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004162 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004163 }
4164
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004165 bool follow(const SCEV *S) {
4166 switch (S->getSCEVType()) {
4167 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4168 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004169 // These expressions are available if their operand(s) is/are.
4170 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004171
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004172 case scAddRecExpr: {
4173 // We allow add recurrences that are on the loop BB is in, or some
4174 // outer loop. This guarantees availability because the value of the
4175 // add recurrence at BB is simply the "current" value of the induction
4176 // variable. We can relax this in the future; for instance an add
4177 // recurrence on a sibling dominating loop is also available at BB.
4178 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4179 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004180 return true;
4181
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004182 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004183 }
4184
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004185 case scUnknown: {
4186 // For SCEVUnknown, we check for simple dominance.
4187 const auto *SU = cast<SCEVUnknown>(S);
4188 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004189
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004190 if (isa<Argument>(V))
4191 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004192
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004193 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4194 return false;
4195
4196 return setUnavailable();
4197 }
4198
4199 case scUDivExpr:
4200 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004201 // We do not try to smart about these at all.
4202 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004203 }
4204 llvm_unreachable("switch should be fully covered!");
4205 }
4206
4207 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004208 };
4209
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004210 CheckAvailable CA(L, BB, DT);
4211 SCEVTraversal<CheckAvailable> ST(CA);
4212
4213 ST.visitAll(S);
4214 return CA.Available;
4215}
4216
4217// Try to match a control flow sequence that branches out at BI and merges back
4218// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4219// match.
4220static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4221 Value *&C, Value *&LHS, Value *&RHS) {
4222 C = BI->getCondition();
4223
4224 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4225 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4226
4227 if (!LeftEdge.isSingleEdge())
4228 return false;
4229
4230 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4231
4232 Use &LeftUse = Merge->getOperandUse(0);
4233 Use &RightUse = Merge->getOperandUse(1);
4234
4235 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4236 LHS = LeftUse;
4237 RHS = RightUse;
4238 return true;
4239 }
4240
4241 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4242 LHS = RightUse;
4243 RHS = LeftUse;
4244 return true;
4245 }
4246
4247 return false;
4248}
4249
4250const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004251 auto IsReachable =
4252 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4253 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004254 const Loop *L = LI.getLoopFor(PN->getParent());
4255
Sanjoy Das337d4782015-10-31 23:21:40 +00004256 // We don't want to break LCSSA, even in a SCEV expression tree.
4257 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4258 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4259 return nullptr;
4260
Sanjoy Das55015d22015-10-02 23:09:44 +00004261 // Try to match
4262 //
4263 // br %cond, label %left, label %right
4264 // left:
4265 // br label %merge
4266 // right:
4267 // br label %merge
4268 // merge:
4269 // V = phi [ %x, %left ], [ %y, %right ]
4270 //
4271 // as "select %cond, %x, %y"
4272
4273 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4274 assert(IDom && "At least the entry block should dominate PN");
4275
4276 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4277 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4278
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004279 if (BI && BI->isConditional() &&
4280 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4281 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4282 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004283 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4284 }
4285
4286 return nullptr;
4287}
4288
4289const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4290 if (const SCEV *S = createAddRecFromPHI(PN))
4291 return S;
4292
4293 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4294 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004295
Dan Gohmana9c205c2010-02-25 06:57:05 +00004296 // If the PHI has a single incoming value, follow that value, unless the
4297 // PHI's incoming blocks are in a different loop, in which case doing so
4298 // risks breaking LCSSA form. Instcombine would normally zap these, but
4299 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004300 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004301 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004302 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004303
Chris Lattnerd934c702004-04-02 20:23:17 +00004304 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004305 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004306}
4307
Sanjoy Das55015d22015-10-02 23:09:44 +00004308const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4309 Value *Cond,
4310 Value *TrueVal,
4311 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004312 // Handle "constant" branch or select. This can occur for instance when a
4313 // loop pass transforms an inner loop and moves on to process the outer loop.
4314 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4315 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4316
Sanjoy Dasd0671342015-10-02 19:39:59 +00004317 // Try to match some simple smax or umax patterns.
4318 auto *ICI = dyn_cast<ICmpInst>(Cond);
4319 if (!ICI)
4320 return getUnknown(I);
4321
4322 Value *LHS = ICI->getOperand(0);
4323 Value *RHS = ICI->getOperand(1);
4324
4325 switch (ICI->getPredicate()) {
4326 case ICmpInst::ICMP_SLT:
4327 case ICmpInst::ICMP_SLE:
4328 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004329 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004330 case ICmpInst::ICMP_SGT:
4331 case ICmpInst::ICMP_SGE:
4332 // a >s b ? a+x : b+x -> smax(a, b)+x
4333 // a >s b ? b+x : a+x -> smin(a, b)+x
4334 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4335 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4336 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4337 const SCEV *LA = getSCEV(TrueVal);
4338 const SCEV *RA = getSCEV(FalseVal);
4339 const SCEV *LDiff = getMinusSCEV(LA, LS);
4340 const SCEV *RDiff = getMinusSCEV(RA, RS);
4341 if (LDiff == RDiff)
4342 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4343 LDiff = getMinusSCEV(LA, RS);
4344 RDiff = getMinusSCEV(RA, LS);
4345 if (LDiff == RDiff)
4346 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4347 }
4348 break;
4349 case ICmpInst::ICMP_ULT:
4350 case ICmpInst::ICMP_ULE:
4351 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004352 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004353 case ICmpInst::ICMP_UGT:
4354 case ICmpInst::ICMP_UGE:
4355 // a >u b ? a+x : b+x -> umax(a, b)+x
4356 // a >u b ? b+x : a+x -> umin(a, b)+x
4357 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4358 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4359 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4360 const SCEV *LA = getSCEV(TrueVal);
4361 const SCEV *RA = getSCEV(FalseVal);
4362 const SCEV *LDiff = getMinusSCEV(LA, LS);
4363 const SCEV *RDiff = getMinusSCEV(RA, RS);
4364 if (LDiff == RDiff)
4365 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4366 LDiff = getMinusSCEV(LA, RS);
4367 RDiff = getMinusSCEV(RA, LS);
4368 if (LDiff == RDiff)
4369 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4370 }
4371 break;
4372 case ICmpInst::ICMP_NE:
4373 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4374 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4375 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4376 const SCEV *One = getOne(I->getType());
4377 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4378 const SCEV *LA = getSCEV(TrueVal);
4379 const SCEV *RA = getSCEV(FalseVal);
4380 const SCEV *LDiff = getMinusSCEV(LA, LS);
4381 const SCEV *RDiff = getMinusSCEV(RA, One);
4382 if (LDiff == RDiff)
4383 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4384 }
4385 break;
4386 case ICmpInst::ICMP_EQ:
4387 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4388 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4389 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4390 const SCEV *One = getOne(I->getType());
4391 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4392 const SCEV *LA = getSCEV(TrueVal);
4393 const SCEV *RA = getSCEV(FalseVal);
4394 const SCEV *LDiff = getMinusSCEV(LA, One);
4395 const SCEV *RDiff = getMinusSCEV(RA, LS);
4396 if (LDiff == RDiff)
4397 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4398 }
4399 break;
4400 default:
4401 break;
4402 }
4403
4404 return getUnknown(I);
4405}
4406
Sanjoy Dasf8570812016-05-29 00:38:22 +00004407/// Expand GEP instructions into add and multiply operations. This allows them
4408/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004409const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004410 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004411 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004412 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004413
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004414 SmallVector<const SCEV *, 4> IndexExprs;
4415 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4416 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004417 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004418}
4419
Dan Gohmanc702fc02009-06-19 23:29:04 +00004420uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004421ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004422 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004423 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004424
Dan Gohmana30370b2009-05-04 22:02:23 +00004425 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004426 return std::min(GetMinTrailingZeros(T->getOperand()),
4427 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004428
Dan Gohmana30370b2009-05-04 22:02:23 +00004429 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004430 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4431 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4432 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004433 }
4434
Dan Gohmana30370b2009-05-04 22:02:23 +00004435 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004436 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4437 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4438 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004439 }
4440
Dan Gohmana30370b2009-05-04 22:02:23 +00004441 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004442 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004443 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004444 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004445 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004446 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004447 }
4448
Dan Gohmana30370b2009-05-04 22:02:23 +00004449 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004450 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004451 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4452 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004453 for (unsigned i = 1, e = M->getNumOperands();
4454 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004455 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004456 BitWidth);
4457 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004458 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004459
Dan Gohmana30370b2009-05-04 22:02:23 +00004460 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004461 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004462 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004463 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004464 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004465 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004466 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004467
Dan Gohmana30370b2009-05-04 22:02:23 +00004468 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004469 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004470 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004471 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004472 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004473 return MinOpRes;
4474 }
4475
Dan Gohmana30370b2009-05-04 22:02:23 +00004476 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004477 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004478 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004479 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004480 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004481 return MinOpRes;
4482 }
4483
Dan Gohmanc702fc02009-06-19 23:29:04 +00004484 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4485 // For a SCEVUnknown, ask ValueTracking.
4486 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004487 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004488 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004489 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004490 return Zeros.countTrailingOnes();
4491 }
4492
4493 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004494 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004495}
Chris Lattnerd934c702004-04-02 20:23:17 +00004496
Sanjoy Dasf8570812016-05-29 00:38:22 +00004497/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004498static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004499 if (Instruction *I = dyn_cast<Instruction>(V))
4500 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4501 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004502
4503 return None;
4504}
4505
Sanjoy Dasf8570812016-05-29 00:38:22 +00004506/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004507/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4508/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004509ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004510ScalarEvolution::getRange(const SCEV *S,
4511 ScalarEvolution::RangeSignHint SignHint) {
4512 DenseMap<const SCEV *, ConstantRange> &Cache =
4513 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4514 : SignedRanges;
4515
Dan Gohman761065e2010-11-17 02:44:44 +00004516 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004517 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4518 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004519 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004520
4521 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004522 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004523
Dan Gohman85be4332010-01-26 19:19:05 +00004524 unsigned BitWidth = getTypeSizeInBits(S->getType());
4525 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4526
Sanjoy Das91b54772015-03-09 21:43:43 +00004527 // If the value has known zeros, the maximum value will have those known zeros
4528 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004529 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004530 if (TZ != 0) {
4531 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4532 ConservativeResult =
4533 ConstantRange(APInt::getMinValue(BitWidth),
4534 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4535 else
4536 ConservativeResult = ConstantRange(
4537 APInt::getSignedMinValue(BitWidth),
4538 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4539 }
Dan Gohman85be4332010-01-26 19:19:05 +00004540
Dan Gohmane65c9172009-07-13 21:35:55 +00004541 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004542 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004543 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004544 X = X.add(getRange(Add->getOperand(i), SignHint));
4545 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004546 }
4547
4548 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004549 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004550 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004551 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4552 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004553 }
4554
4555 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004556 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004557 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004558 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4559 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004560 }
4561
4562 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004563 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004564 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004565 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4566 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004567 }
4568
4569 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004570 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4571 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4572 return setRange(UDiv, SignHint,
4573 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004574 }
4575
4576 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004577 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4578 return setRange(ZExt, SignHint,
4579 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004580 }
4581
4582 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004583 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4584 return setRange(SExt, SignHint,
4585 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004586 }
4587
4588 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004589 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4590 return setRange(Trunc, SignHint,
4591 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004592 }
4593
Dan Gohmane65c9172009-07-13 21:35:55 +00004594 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004595 // If there's no unsigned wrap, the value will never be less than its
4596 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004597 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004598 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004599 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004600 ConservativeResult = ConservativeResult.intersectWith(
4601 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004602
Dan Gohman51ad99d2010-01-21 02:09:26 +00004603 // If there's no signed wrap, and all the operands have the same sign or
4604 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004605 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004606 bool AllNonNeg = true;
4607 bool AllNonPos = true;
4608 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4609 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4610 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4611 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004612 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004613 ConservativeResult = ConservativeResult.intersectWith(
4614 ConstantRange(APInt(BitWidth, 0),
4615 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004616 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004617 ConservativeResult = ConservativeResult.intersectWith(
4618 ConstantRange(APInt::getSignedMinValue(BitWidth),
4619 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004620 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004621
4622 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004623 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004624 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004625 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4626 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004627 auto RangeFromAffine = getRangeForAffineAR(
4628 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4629 BitWidth);
4630 if (!RangeFromAffine.isFullSet())
4631 ConservativeResult =
4632 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004633
4634 auto RangeFromFactoring = getRangeViaFactoring(
4635 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4636 BitWidth);
4637 if (!RangeFromFactoring.isFullSet())
4638 ConservativeResult =
4639 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004640 }
Dan Gohmand261d272009-06-24 01:05:09 +00004641 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004642
Sanjoy Das91b54772015-03-09 21:43:43 +00004643 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004644 }
4645
Dan Gohmanc702fc02009-06-19 23:29:04 +00004646 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004647 // Check if the IR explicitly contains !range metadata.
4648 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4649 if (MDRange.hasValue())
4650 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4651
Sanjoy Das91b54772015-03-09 21:43:43 +00004652 // Split here to avoid paying the compile-time cost of calling both
4653 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4654 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004655 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004656 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4657 // For a SCEVUnknown, ask ValueTracking.
4658 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004659 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004660 if (Ones != ~Zeros + 1)
4661 ConservativeResult =
4662 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4663 } else {
4664 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4665 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004666 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004667 if (NS > 1)
4668 ConservativeResult = ConservativeResult.intersectWith(
4669 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4670 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004671 }
4672
4673 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004674 }
4675
Sanjoy Das91b54772015-03-09 21:43:43 +00004676 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004677}
4678
Sanjoy Dasb765b632016-03-02 00:57:39 +00004679ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4680 const SCEV *Step,
4681 const SCEV *MaxBECount,
4682 unsigned BitWidth) {
4683 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4684 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4685 "Precondition!");
4686
4687 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4688
4689 // Check for overflow. This must be done with ConstantRange arithmetic
4690 // because we could be called from within the ScalarEvolution overflow
4691 // checking code.
4692
4693 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4694 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
Michael Zolotukhine909a6e2016-12-20 23:03:42 +00004695 ConstantRange ZExtMaxBECountRange = MaxBECountRange.zextOrTrunc(BitWidth * 2);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004696
4697 ConstantRange StepSRange = getSignedRange(Step);
Michael Zolotukhine909a6e2016-12-20 23:03:42 +00004698 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004699
4700 ConstantRange StartURange = getUnsignedRange(Start);
4701 ConstantRange EndURange =
4702 StartURange.add(MaxBECountRange.multiply(StepSRange));
4703
4704 // Check for unsigned overflow.
Michael Zolotukhine909a6e2016-12-20 23:03:42 +00004705 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2);
4706 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004707 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4708 ZExtEndURange) {
4709 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4710 EndURange.getUnsignedMin());
4711 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4712 EndURange.getUnsignedMax());
4713 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4714 if (!IsFullRange)
4715 Result =
4716 Result.intersectWith(ConstantRange(Min, Max + 1));
4717 }
4718
4719 ConstantRange StartSRange = getSignedRange(Start);
4720 ConstantRange EndSRange =
4721 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4722
4723 // Check for signed overflow. This must be done with ConstantRange
4724 // arithmetic because we could be called from within the ScalarEvolution
4725 // overflow checking code.
Michael Zolotukhine909a6e2016-12-20 23:03:42 +00004726 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2);
4727 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004728 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4729 SExtEndSRange) {
4730 APInt Min =
4731 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4732 APInt Max =
4733 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4734 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4735 if (!IsFullRange)
4736 Result =
4737 Result.intersectWith(ConstantRange(Min, Max + 1));
4738 }
4739
4740 return Result;
4741}
4742
Sanjoy Dasbf730982016-03-02 00:57:54 +00004743ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4744 const SCEV *Step,
4745 const SCEV *MaxBECount,
4746 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004747 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4748 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4749
4750 struct SelectPattern {
4751 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004752 APInt TrueValue;
4753 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004754
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004755 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4756 const SCEV *S) {
4757 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004758 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004759
4760 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4761 "Should be!");
4762
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004763 // Peel off a constant offset:
4764 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4765 // In the future we could consider being smarter here and handle
4766 // {Start+Step,+,Step} too.
4767 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4768 return;
4769
4770 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4771 S = SA->getOperand(1);
4772 }
4773
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004774 // Peel off a cast operation
4775 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4776 CastOp = SCast->getSCEVType();
4777 S = SCast->getOperand();
4778 }
4779
Sanjoy Dasbf730982016-03-02 00:57:54 +00004780 using namespace llvm::PatternMatch;
4781
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004782 auto *SU = dyn_cast<SCEVUnknown>(S);
4783 const APInt *TrueVal, *FalseVal;
4784 if (!SU ||
4785 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4786 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004787 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004788 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004789 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004790
4791 TrueValue = *TrueVal;
4792 FalseValue = *FalseVal;
4793
4794 // Re-apply the cast we peeled off earlier
4795 if (CastOp.hasValue())
4796 switch (*CastOp) {
4797 default:
4798 llvm_unreachable("Unknown SCEV cast type!");
4799
4800 case scTruncate:
4801 TrueValue = TrueValue.trunc(BitWidth);
4802 FalseValue = FalseValue.trunc(BitWidth);
4803 break;
4804 case scZeroExtend:
4805 TrueValue = TrueValue.zext(BitWidth);
4806 FalseValue = FalseValue.zext(BitWidth);
4807 break;
4808 case scSignExtend:
4809 TrueValue = TrueValue.sext(BitWidth);
4810 FalseValue = FalseValue.sext(BitWidth);
4811 break;
4812 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004813
4814 // Re-apply the constant offset we peeled off earlier
4815 TrueValue += Offset;
4816 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004817 }
4818
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004819 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004820 };
4821
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004822 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004823 if (!StartPattern.isRecognized())
4824 return ConstantRange(BitWidth, /* isFullSet = */ true);
4825
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004826 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004827 if (!StepPattern.isRecognized())
4828 return ConstantRange(BitWidth, /* isFullSet = */ true);
4829
4830 if (StartPattern.Condition != StepPattern.Condition) {
4831 // We don't handle this case today; but we could, by considering four
4832 // possibilities below instead of two. I'm not sure if there are cases where
4833 // that will help over what getRange already does, though.
4834 return ConstantRange(BitWidth, /* isFullSet = */ true);
4835 }
4836
4837 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4838 // construct arbitrary general SCEV expressions here. This function is called
4839 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4840 // say) can end up caching a suboptimal value.
4841
Sanjoy Das6b017a12016-03-02 02:56:29 +00004842 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4843 // C2352 and C2512 (otherwise it isn't needed).
4844
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004845 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004846 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004847 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004848 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004849
Sanjoy Das1168f932016-03-02 02:34:20 +00004850 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004851 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004852 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004853 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004854
4855 return TrueRange.unionWith(FalseRange);
4856}
4857
Jingyue Wu42f1d672015-07-28 18:22:40 +00004858SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004859 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004860 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4861
4862 // Return early if there are no flags to propagate to the SCEV.
4863 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4864 if (BinOp->hasNoUnsignedWrap())
4865 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4866 if (BinOp->hasNoSignedWrap())
4867 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004868 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004869 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004870
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004871 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4872}
4873
4874bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4875 // Here we check that I is in the header of the innermost loop containing I,
4876 // since we only deal with instructions in the loop header. The actual loop we
4877 // need to check later will come from an add recurrence, but getting that
4878 // requires computing the SCEV of the operands, which can be expensive. This
4879 // check we can do cheaply to rule out some cases early.
4880 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004881 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004882 InnermostContainingLoop->getHeader() != I->getParent())
4883 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004884
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004885 // Only proceed if we can prove that I does not yield poison.
4886 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004887
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004888 // At this point we know that if I is executed, then it does not wrap
4889 // according to at least one of NSW or NUW. If I is not executed, then we do
4890 // not know if the calculation that I represents would wrap. Multiple
4891 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004892 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4893 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004894 // that guarantee for cases where I is not executed. So we need to find the
4895 // loop that I is considered in relation to and prove that I is executed for
4896 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004897 // calculates does not wrap anywhere in the loop, so then we can apply the
4898 // flags to the SCEV.
4899 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004900 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4901 // from different loops, so that we know which loop to prove that I is
4902 // executed in.
4903 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004904 // I could be an extractvalue from a call to an overflow intrinsic.
4905 // TODO: We can do better here in some cases.
4906 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4907 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004908 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004909 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004910 bool AllOtherOpsLoopInvariant = true;
4911 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4912 ++OtherOpIndex) {
4913 if (OtherOpIndex != OpIndex) {
4914 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4915 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4916 AllOtherOpsLoopInvariant = false;
4917 break;
4918 }
4919 }
4920 }
4921 if (AllOtherOpsLoopInvariant &&
4922 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4923 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004924 }
4925 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004926 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004927}
4928
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004929bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4930 // If we know that \c I can never be poison period, then that's enough.
4931 if (isSCEVExprNeverPoison(I))
4932 return true;
4933
4934 // For an add recurrence specifically, we assume that infinite loops without
4935 // side effects are undefined behavior, and then reason as follows:
4936 //
4937 // If the add recurrence is poison in any iteration, it is poison on all
4938 // future iterations (since incrementing poison yields poison). If the result
4939 // of the add recurrence is fed into the loop latch condition and the loop
4940 // does not contain any throws or exiting blocks other than the latch, we now
4941 // have the ability to "choose" whether the backedge is taken or not (by
4942 // choosing a sufficiently evil value for the poison feeding into the branch)
4943 // for every iteration including and after the one in which \p I first became
4944 // poison. There are two possibilities (let's call the iteration in which \p
4945 // I first became poison as K):
4946 //
4947 // 1. In the set of iterations including and after K, the loop body executes
4948 // no side effects. In this case executing the backege an infinte number
4949 // of times will yield undefined behavior.
4950 //
4951 // 2. In the set of iterations including and after K, the loop body executes
4952 // at least one side effect. In this case, that specific instance of side
4953 // effect is control dependent on poison, which also yields undefined
4954 // behavior.
4955
4956 auto *ExitingBB = L->getExitingBlock();
4957 auto *LatchBB = L->getLoopLatch();
4958 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4959 return false;
4960
4961 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004962 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004963
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004964 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4965 // things that are known to be fully poison under that assumption go on the
4966 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004967 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004968 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004969
4970 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004971 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004972 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004973
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004974 for (auto *PoisonUser : Poison->users()) {
4975 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4976 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4977 PoisonStack.push_back(cast<Instruction>(PoisonUser));
4978 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004979 assert(BI->isConditional() && "Only possibility!");
4980 if (BI->getParent() == LatchBB) {
4981 LatchControlDependentOnPoison = true;
4982 break;
4983 }
4984 }
4985 }
4986 }
4987
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004988 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4989}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004990
Sanjoy Das5603fc02016-09-26 02:44:07 +00004991ScalarEvolution::LoopProperties
4992ScalarEvolution::getLoopProperties(const Loop *L) {
4993 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004994
Sanjoy Das5603fc02016-09-26 02:44:07 +00004995 auto Itr = LoopPropertiesCache.find(L);
4996 if (Itr == LoopPropertiesCache.end()) {
4997 auto HasSideEffects = [](Instruction *I) {
4998 if (auto *SI = dyn_cast<StoreInst>(I))
4999 return !SI->isSimple();
5000
5001 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005002 };
5003
Sanjoy Das5603fc02016-09-26 02:44:07 +00005004 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5005 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005006
Sanjoy Das5603fc02016-09-26 02:44:07 +00005007 for (auto *BB : L->getBlocks())
5008 for (auto &I : *BB) {
5009 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5010 LP.HasNoAbnormalExits = false;
5011 if (HasSideEffects(&I))
5012 LP.HasNoSideEffects = false;
5013 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5014 break; // We're already as pessimistic as we can get.
5015 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005016
Sanjoy Das5603fc02016-09-26 02:44:07 +00005017 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005018 assert(InsertPair.second && "We just checked!");
5019 Itr = InsertPair.first;
5020 }
5021
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005022 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005023}
5024
Dan Gohmanaf752342009-07-07 17:06:11 +00005025const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005026 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005027 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005028
Dan Gohman69451a02010-03-09 23:46:50 +00005029 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005030 // Don't attempt to analyze instructions in blocks that aren't
5031 // reachable. Such instructions don't matter, and they aren't required
5032 // to obey basic rules for definitions dominating uses which this
5033 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005034 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005035 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005036 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005037 return getConstant(CI);
5038 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005039 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005040 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005041 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005042 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005043 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005044
Dan Gohman80ca01c2009-07-17 20:47:02 +00005045 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005046 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005047 switch (BO->Opcode) {
5048 case Instruction::Add: {
5049 // The simple thing to do would be to just call getSCEV on both operands
5050 // and call getAddExpr with the result. However if we're looking at a
5051 // bunch of things all added together, this can be quite inefficient,
5052 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5053 // Instead, gather up all the operands and make a single getAddExpr call.
5054 // LLVM IR canonical form means we need only traverse the left operands.
5055 SmallVector<const SCEV *, 4> AddOps;
5056 do {
5057 if (BO->Op) {
5058 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5059 AddOps.push_back(OpSCEV);
5060 break;
5061 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005062
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005063 // If a NUW or NSW flag can be applied to the SCEV for this
5064 // addition, then compute the SCEV for this addition by itself
5065 // with a separate call to getAddExpr. We need to do that
5066 // instead of pushing the operands of the addition onto AddOps,
5067 // since the flags are only known to apply to this particular
5068 // addition - they may not apply to other additions that can be
5069 // formed with operands from AddOps.
5070 const SCEV *RHS = getSCEV(BO->RHS);
5071 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5072 if (Flags != SCEV::FlagAnyWrap) {
5073 const SCEV *LHS = getSCEV(BO->LHS);
5074 if (BO->Opcode == Instruction::Sub)
5075 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5076 else
5077 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5078 break;
5079 }
Dan Gohman36bad002009-09-17 18:05:20 +00005080 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005081
5082 if (BO->Opcode == Instruction::Sub)
5083 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5084 else
5085 AddOps.push_back(getSCEV(BO->RHS));
5086
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005087 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005088 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5089 NewBO->Opcode != Instruction::Sub)) {
5090 AddOps.push_back(getSCEV(BO->LHS));
5091 break;
5092 }
5093 BO = NewBO;
5094 } while (true);
5095
5096 return getAddExpr(AddOps);
5097 }
5098
5099 case Instruction::Mul: {
5100 SmallVector<const SCEV *, 4> MulOps;
5101 do {
5102 if (BO->Op) {
5103 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5104 MulOps.push_back(OpSCEV);
5105 break;
5106 }
5107
5108 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5109 if (Flags != SCEV::FlagAnyWrap) {
5110 MulOps.push_back(
5111 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5112 break;
5113 }
5114 }
5115
5116 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005117 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005118 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5119 MulOps.push_back(getSCEV(BO->LHS));
5120 break;
5121 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005122 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005123 } while (true);
5124
5125 return getMulExpr(MulOps);
5126 }
5127 case Instruction::UDiv:
5128 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5129 case Instruction::Sub: {
5130 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5131 if (BO->Op)
5132 Flags = getNoWrapFlagsFromUB(BO->Op);
5133 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5134 }
5135 case Instruction::And:
5136 // For an expression like x&255 that merely masks off the high bits,
5137 // use zext(trunc(x)) as the SCEV expression.
5138 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5139 if (CI->isNullValue())
5140 return getSCEV(BO->RHS);
5141 if (CI->isAllOnesValue())
5142 return getSCEV(BO->LHS);
5143 const APInt &A = CI->getValue();
5144
5145 // Instcombine's ShrinkDemandedConstant may strip bits out of
5146 // constants, obscuring what would otherwise be a low-bits mask.
5147 // Use computeKnownBits to compute what ShrinkDemandedConstant
5148 // knew about to reconstruct a low-bits mask value.
5149 unsigned LZ = A.countLeadingZeros();
5150 unsigned TZ = A.countTrailingZeros();
5151 unsigned BitWidth = A.getBitWidth();
5152 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5153 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005154 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005155
5156 APInt EffectiveMask =
5157 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5158 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005159 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5160 const SCEV *LHS = getSCEV(BO->LHS);
5161 const SCEV *ShiftedLHS = nullptr;
5162 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5163 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5164 // For an expression like (x * 8) & 8, simplify the multiply.
5165 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5166 unsigned GCD = std::min(MulZeros, TZ);
5167 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5168 SmallVector<const SCEV*, 4> MulOps;
5169 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5170 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5171 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5172 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5173 }
5174 }
5175 if (!ShiftedLHS)
5176 ShiftedLHS = getUDivExpr(LHS, MulCount);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005177 return getMulExpr(
5178 getZeroExtendExpr(
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005179 getTruncateExpr(ShiftedLHS,
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005180 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5181 BO->LHS->getType()),
5182 MulCount);
5183 }
Dan Gohman36bad002009-09-17 18:05:20 +00005184 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005185 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005186
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005187 case Instruction::Or:
5188 // If the RHS of the Or is a constant, we may have something like:
5189 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5190 // optimizations will transparently handle this case.
5191 //
5192 // In order for this transformation to be safe, the LHS must be of the
5193 // form X*(2^n) and the Or constant must be less than 2^n.
5194 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5195 const SCEV *LHS = getSCEV(BO->LHS);
5196 const APInt &CIVal = CI->getValue();
5197 if (GetMinTrailingZeros(LHS) >=
5198 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5199 // Build a plain add SCEV.
5200 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5201 // If the LHS of the add was an addrec and it has no-wrap flags,
5202 // transfer the no-wrap flags, since an or won't introduce a wrap.
5203 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5204 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5205 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5206 OldAR->getNoWrapFlags());
5207 }
5208 return S;
5209 }
5210 }
5211 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005212
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005213 case Instruction::Xor:
5214 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5215 // If the RHS of xor is -1, then this is a not operation.
5216 if (CI->isAllOnesValue())
5217 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005218
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005219 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5220 // This is a variant of the check for xor with -1, and it handles
5221 // the case where instcombine has trimmed non-demanded bits out
5222 // of an xor with -1.
5223 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5224 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5225 if (LBO->getOpcode() == Instruction::And &&
5226 LCI->getValue() == CI->getValue())
5227 if (const SCEVZeroExtendExpr *Z =
5228 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5229 Type *UTy = BO->LHS->getType();
5230 const SCEV *Z0 = Z->getOperand();
5231 Type *Z0Ty = Z0->getType();
5232 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005233
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005234 // If C is a low-bits mask, the zero extend is serving to
5235 // mask off the high bits. Complement the operand and
5236 // re-apply the zext.
5237 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5238 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5239
5240 // If C is a single bit, it may be in the sign-bit position
5241 // before the zero-extend. In this case, represent the xor
5242 // using an add, which is equivalent, and re-apply the zext.
5243 APInt Trunc = CI->getValue().trunc(Z0TySize);
5244 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5245 Trunc.isSignBit())
5246 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5247 UTy);
5248 }
5249 }
5250 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005251
5252 case Instruction::Shl:
5253 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005254 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5255 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005256
5257 // If the shift count is not less than the bitwidth, the result of
5258 // the shift is undefined. Don't try to analyze it, because the
5259 // resolution chosen here may differ from the resolution chosen in
5260 // other parts of the compiler.
5261 if (SA->getValue().uge(BitWidth))
5262 break;
5263
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005264 // It is currently not resolved how to interpret NSW for left
5265 // shift by BitWidth - 1, so we avoid applying flags in that
5266 // case. Remove this check (or this comment) once the situation
5267 // is resolved. See
5268 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5269 // and http://reviews.llvm.org/D8890 .
5270 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005271 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5272 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005273
Owen Andersonedb4a702009-07-24 23:12:02 +00005274 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005275 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005276 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005277 }
5278 break;
5279
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005280 case Instruction::AShr:
5281 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5282 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5283 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5284 if (L->getOpcode() == Instruction::Shl &&
5285 L->getOperand(1) == BO->RHS) {
5286 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005287
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005288 // If the shift count is not less than the bitwidth, the result of
5289 // the shift is undefined. Don't try to analyze it, because the
5290 // resolution chosen here may differ from the resolution chosen in
5291 // other parts of the compiler.
5292 if (CI->getValue().uge(BitWidth))
5293 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005294
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005295 uint64_t Amt = BitWidth - CI->getZExtValue();
5296 if (Amt == BitWidth)
5297 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5298 return getSignExtendExpr(
5299 getTruncateExpr(getSCEV(L->getOperand(0)),
5300 IntegerType::get(getContext(), Amt)),
5301 BO->LHS->getType());
5302 }
5303 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005304 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005305 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005306
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005307 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005308 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005309 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005310
5311 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005312 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005313
5314 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005315 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005316
5317 case Instruction::BitCast:
5318 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005319 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005320 return getSCEV(U->getOperand(0));
5321 break;
5322
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005323 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5324 // lead to pointer expressions which cannot safely be expanded to GEPs,
5325 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5326 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005327
Dan Gohmanee750d12009-05-08 20:26:55 +00005328 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005329 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005330
Dan Gohman05e89732008-06-22 19:56:46 +00005331 case Instruction::PHI:
5332 return createNodeForPHI(cast<PHINode>(U));
5333
5334 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005335 // U can also be a select constant expr, which let fall through. Since
5336 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5337 // constant expressions cannot have instructions as operands, we'd have
5338 // returned getUnknown for a select constant expressions anyway.
5339 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005340 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5341 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005342 break;
5343
5344 case Instruction::Call:
5345 case Instruction::Invoke:
5346 if (Value *RV = CallSite(U).getReturnedArgOperand())
5347 return getSCEV(RV);
5348 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005349 }
5350
Dan Gohmanc8e23622009-04-21 23:15:49 +00005351 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005352}
5353
5354
5355
5356//===----------------------------------------------------------------------===//
5357// Iteration Count Computation Code
5358//
5359
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005360static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5361 if (!ExitCount)
5362 return 0;
5363
5364 ConstantInt *ExitConst = ExitCount->getValue();
5365
5366 // Guard against huge trip counts.
5367 if (ExitConst->getValue().getActiveBits() > 32)
5368 return 0;
5369
5370 // In case of integer overflow, this returns 0, which is correct.
5371 return ((unsigned)ExitConst->getZExtValue()) + 1;
5372}
5373
Chandler Carruth6666c272014-10-11 00:12:11 +00005374unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5375 if (BasicBlock *ExitingBB = L->getExitingBlock())
5376 return getSmallConstantTripCount(L, ExitingBB);
5377
5378 // No trip count information for multiple exits.
5379 return 0;
5380}
5381
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005382unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5383 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005384 assert(ExitingBlock && "Must pass a non-null exiting block!");
5385 assert(L->isLoopExiting(ExitingBlock) &&
5386 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005387 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005388 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005389 return getConstantTripCount(ExitCount);
5390}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005391
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005392unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5393 const auto *MaxExitCount =
5394 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5395 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005396}
5397
Chandler Carruth6666c272014-10-11 00:12:11 +00005398unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5399 if (BasicBlock *ExitingBB = L->getExitingBlock())
5400 return getSmallConstantTripMultiple(L, ExitingBB);
5401
5402 // No trip multiple information for multiple exits.
5403 return 0;
5404}
5405
Sanjoy Dasf8570812016-05-29 00:38:22 +00005406/// Returns the largest constant divisor of the trip count of this loop as a
5407/// normal unsigned value, if possible. This means that the actual trip count is
5408/// always a multiple of the returned value (don't forget the trip count could
5409/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005410///
5411/// Returns 1 if the trip count is unknown or not guaranteed to be the
5412/// multiple of a constant (which is also the case if the trip count is simply
5413/// constant, use getSmallConstantTripCount for that case), Will also return 1
5414/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005415///
5416/// As explained in the comments for getSmallConstantTripCount, this assumes
5417/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005418unsigned
5419ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5420 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005421 assert(ExitingBlock && "Must pass a non-null exiting block!");
5422 assert(L->isLoopExiting(ExitingBlock) &&
5423 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005424 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005425 if (ExitCount == getCouldNotCompute())
5426 return 1;
5427
5428 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005429 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005430 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5431 // to factor simple cases.
5432 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5433 TCMul = Mul->getOperand(0);
5434
5435 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5436 if (!MulC)
5437 return 1;
5438
5439 ConstantInt *Result = MulC->getValue();
5440
Hal Finkel30bd9342012-10-24 19:46:44 +00005441 // Guard against huge trip counts (this requires checking
5442 // for zero to handle the case where the trip count == -1 and the
5443 // addition wraps).
5444 if (!Result || Result->getValue().getActiveBits() > 32 ||
5445 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005446 return 1;
5447
5448 return (unsigned)Result->getZExtValue();
5449}
5450
Sanjoy Dasf8570812016-05-29 00:38:22 +00005451/// Get the expression for the number of loop iterations for which this loop is
5452/// guaranteed not to exit via ExitingBlock. Otherwise return
5453/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005454const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5455 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005456}
5457
Silviu Baranga6f444df2016-04-08 14:29:09 +00005458const SCEV *
5459ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5460 SCEVUnionPredicate &Preds) {
5461 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5462}
5463
Dan Gohmanaf752342009-07-07 17:06:11 +00005464const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005465 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005466}
5467
Sanjoy Dasf8570812016-05-29 00:38:22 +00005468/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5469/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005470const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005471 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005472}
5473
John Brawn84b21832016-10-21 11:08:48 +00005474bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5475 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5476}
5477
Sanjoy Dasf8570812016-05-29 00:38:22 +00005478/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005479static void
5480PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5481 BasicBlock *Header = L->getHeader();
5482
5483 // Push all Loop-header PHIs onto the Worklist stack.
5484 for (BasicBlock::iterator I = Header->begin();
5485 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5486 Worklist.push_back(PN);
5487}
5488
Dan Gohman2b8da352009-04-30 20:47:05 +00005489const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005490ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5491 auto &BTI = getBackedgeTakenInfo(L);
5492 if (BTI.hasFullInfo())
5493 return BTI;
5494
5495 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5496
5497 if (!Pair.second)
5498 return Pair.first->second;
5499
5500 BackedgeTakenInfo Result =
5501 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5502
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005503 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005504}
5505
5506const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005507ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005508 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005509 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005510 // update the value. The temporary CouldNotCompute value tells SCEV
5511 // code elsewhere that it shouldn't attempt to request a new
5512 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005513 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005514 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005515 if (!Pair.second)
5516 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005517
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005518 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005519 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5520 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005521 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005522
5523 if (Result.getExact(this) != getCouldNotCompute()) {
5524 assert(isLoopInvariant(Result.getExact(this), L) &&
5525 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005526 "Computed backedge-taken count isn't loop invariant for loop!");
5527 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005528 }
5529 else if (Result.getMax(this) == getCouldNotCompute() &&
5530 isa<PHINode>(L->getHeader()->begin())) {
5531 // Only count loops that have phi nodes as not being computable.
5532 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005533 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005534
Chris Lattnera337f5e2011-01-09 02:16:18 +00005535 // Now that we know more about the trip count for this loop, forget any
5536 // existing SCEV values for PHI nodes in this loop since they are only
5537 // conservative estimates made without the benefit of trip count
5538 // information. This is similar to the code in forgetLoop, except that
5539 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005540 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005541 SmallVector<Instruction *, 16> Worklist;
5542 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005543
Chris Lattnera337f5e2011-01-09 02:16:18 +00005544 SmallPtrSet<Instruction *, 8> Visited;
5545 while (!Worklist.empty()) {
5546 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005547 if (!Visited.insert(I).second)
5548 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005549
Chris Lattnera337f5e2011-01-09 02:16:18 +00005550 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005551 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005552 if (It != ValueExprMap.end()) {
5553 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005554
Chris Lattnera337f5e2011-01-09 02:16:18 +00005555 // SCEVUnknown for a PHI either means that it has an unrecognized
5556 // structure, or it's a PHI that's in the progress of being computed
5557 // by createNodeForPHI. In the former case, additional loop trip
5558 // count information isn't going to change anything. In the later
5559 // case, createNodeForPHI will perform the necessary updates on its
5560 // own when it gets to that point.
5561 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005562 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005563 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005564 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005565 if (PHINode *PN = dyn_cast<PHINode>(I))
5566 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005567 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005568
5569 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005570 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005571 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005572
5573 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005574 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005575 // recusive call to getBackedgeTakenInfo (on a different
5576 // loop), which would invalidate the iterator computed
5577 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005578 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005579}
5580
Dan Gohman880c92a2009-10-31 15:04:55 +00005581void ScalarEvolution::forgetLoop(const Loop *L) {
5582 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005583 auto RemoveLoopFromBackedgeMap =
5584 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5585 auto BTCPos = Map.find(L);
5586 if (BTCPos != Map.end()) {
5587 BTCPos->second.clear();
5588 Map.erase(BTCPos);
5589 }
5590 };
5591
5592 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5593 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005594
Dan Gohman880c92a2009-10-31 15:04:55 +00005595 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005596 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005597 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005598
Dan Gohmandc191042009-07-08 19:23:34 +00005599 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005600 while (!Worklist.empty()) {
5601 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005602 if (!Visited.insert(I).second)
5603 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005604
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005605 ValueExprMapType::iterator It =
5606 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005607 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005608 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005609 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005610 if (PHINode *PN = dyn_cast<PHINode>(I))
5611 ConstantEvolutionLoopExitValue.erase(PN);
5612 }
5613
5614 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005615 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005616
5617 // Forget all contained loops too, to avoid dangling entries in the
5618 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005619 for (Loop *I : *L)
5620 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005621
Sanjoy Das5603fc02016-09-26 02:44:07 +00005622 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005623}
5624
Eric Christopheref6d5932010-07-29 01:25:38 +00005625void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005626 Instruction *I = dyn_cast<Instruction>(V);
5627 if (!I) return;
5628
5629 // Drop information about expressions based on loop-header PHIs.
5630 SmallVector<Instruction *, 16> Worklist;
5631 Worklist.push_back(I);
5632
5633 SmallPtrSet<Instruction *, 8> Visited;
5634 while (!Worklist.empty()) {
5635 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005636 if (!Visited.insert(I).second)
5637 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005638
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005639 ValueExprMapType::iterator It =
5640 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005641 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005642 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005643 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005644 if (PHINode *PN = dyn_cast<PHINode>(I))
5645 ConstantEvolutionLoopExitValue.erase(PN);
5646 }
5647
5648 PushDefUseChildren(I, Worklist);
5649 }
5650}
5651
Sanjoy Dasf8570812016-05-29 00:38:22 +00005652/// Get the exact loop backedge taken count considering all loop exits. A
5653/// computable result can only be returned for loops with a single exit.
5654/// Returning the minimum taken count among all exits is incorrect because one
5655/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5656/// the limit of each loop test is never skipped. This is a valid assumption as
5657/// long as the loop exits via that test. For precise results, it is the
5658/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005659/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005660const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005661ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5662 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005663 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005664 if (!isComplete() || ExitNotTaken.empty())
5665 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005666
Craig Topper9f008862014-04-15 04:59:12 +00005667 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005668 for (auto &ENT : ExitNotTaken) {
5669 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005670
5671 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005672 BECount = ENT.ExactNotTaken;
5673 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005674 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005675 if (Preds && !ENT.hasAlwaysTruePredicate())
5676 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005677
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005678 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005679 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005680 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005681
Andrew Trickbbb226a2011-09-02 21:20:46 +00005682 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005683 return BECount;
5684}
5685
Sanjoy Dasf8570812016-05-29 00:38:22 +00005686/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005687const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005688ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005689 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005690 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005691 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005692 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005693
Andrew Trick3ca3f982011-07-26 17:19:55 +00005694 return SE->getCouldNotCompute();
5695}
5696
5697/// getMax - Get the max backedge taken count for the loop.
5698const SCEV *
5699ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005700 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5701 return !ENT.hasAlwaysTruePredicate();
5702 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005703
Sanjoy Das73268612016-09-26 01:10:22 +00005704 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5705 return SE->getCouldNotCompute();
5706
5707 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005708}
5709
John Brawn84b21832016-10-21 11:08:48 +00005710bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5711 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5712 return !ENT.hasAlwaysTruePredicate();
5713 };
5714 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5715}
5716
Andrew Trick9093e152013-03-26 03:14:53 +00005717bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5718 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005719 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5720 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005721 return true;
5722
Silviu Baranga6f444df2016-04-08 14:29:09 +00005723 for (auto &ENT : ExitNotTaken)
5724 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5725 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005726 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005727
Andrew Trick9093e152013-03-26 03:14:53 +00005728 return false;
5729}
5730
Andrew Trick3ca3f982011-07-26 17:19:55 +00005731/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5732/// computable exit into a persistent ExitNotTakenInfo array.
5733ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005734 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5735 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005736 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5737 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005738 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005739 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005740 std::transform(
5741 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005742 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005743 BasicBlock *ExitBB = EEI.first;
5744 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005745 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005746 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005747
5748 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5749 for (auto *Pred : EL.Predicates)
5750 Predicate->add(Pred);
5751
5752 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005753 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005754}
5755
Sanjoy Dasf8570812016-05-29 00:38:22 +00005756/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005757void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005758 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005759}
5760
Sanjoy Dasf8570812016-05-29 00:38:22 +00005761/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005762ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005763ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5764 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005765 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005766 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005767
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005768 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5769
5770 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005771 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005772 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005773 const SCEV *MustExitMaxBECount = nullptr;
5774 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005775 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005776
5777 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5778 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005779 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005780 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005781 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005782 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5783
Sanjoy Dasf0022122016-09-28 17:14:58 +00005784 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005785 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005786
5787 // 1. For each exit that can be computed, add an entry to ExitCounts.
5788 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005789 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005790 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005791 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005792 CouldComputeBECount = false;
5793 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005794 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005795
Andrew Trick839e30b2014-05-23 19:47:13 +00005796 // 2. Derive the loop's MaxBECount from each exit's max number of
5797 // non-exiting iterations. Partition the loop exits into two kinds:
5798 // LoopMustExits and LoopMayExits.
5799 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005800 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5801 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005802 // MaxBECount is the minimum EL.MaxNotTaken of computable
5803 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5804 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5805 // computable EL.MaxNotTaken.
5806 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005807 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005808 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005809 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005810 MustExitMaxOrZero = EL.MaxOrZero;
5811 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005812 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005813 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005814 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005815 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005816 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5817 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005818 else {
5819 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005820 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005821 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005822 }
Dan Gohman96212b62009-06-22 00:31:57 +00005823 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005824 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5825 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00005826 // The loop backedge will be taken the maximum or zero times if there's
5827 // a single exit that must be taken the maximum or zero times.
5828 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005829 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00005830 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00005831}
5832
Andrew Trick3ca3f982011-07-26 17:19:55 +00005833ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005834ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5835 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005836
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005837 // Okay, we've chosen an exiting block. See what condition causes us to exit
5838 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005839 // lead to the loop header.
5840 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005841 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005842 for (auto *SBB : successors(ExitingBlock))
5843 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005844 if (Exit) // Multiple exit successors.
5845 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005846 Exit = SBB;
5847 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005848 MustExecuteLoopHeader = false;
5849 }
Dan Gohmance973df2009-06-24 04:48:43 +00005850
Chris Lattner18954852007-01-07 02:24:26 +00005851 // At this point, we know we have a conditional branch that determines whether
5852 // the loop is exited. However, we don't know if the branch is executed each
5853 // time through the loop. If not, then the execution count of the branch will
5854 // not be equal to the trip count of the loop.
5855 //
5856 // Currently we check for this by checking to see if the Exit branch goes to
5857 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005858 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005859 // loop header. This is common for un-rotated loops.
5860 //
5861 // If both of those tests fail, walk up the unique predecessor chain to the
5862 // header, stopping if there is an edge that doesn't exit the loop. If the
5863 // header is reached, the execution count of the branch will be equal to the
5864 // trip count of the loop.
5865 //
5866 // More extensive analysis could be done to handle more cases here.
5867 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005868 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005869 // The simple checks failed, try climbing the unique predecessor chain
5870 // up to the header.
5871 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005872 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005873 BasicBlock *Pred = BB->getUniquePredecessor();
5874 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005875 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005876 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005877 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005878 if (PredSucc == BB)
5879 continue;
5880 // If the predecessor has a successor that isn't BB and isn't
5881 // outside the loop, assume the worst.
5882 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005883 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005884 }
5885 if (Pred == L->getHeader()) {
5886 Ok = true;
5887 break;
5888 }
5889 BB = Pred;
5890 }
5891 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005892 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005893 }
5894
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005895 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005896 TerminatorInst *Term = ExitingBlock->getTerminator();
5897 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5898 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5899 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005900 return computeExitLimitFromCond(
5901 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5902 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005903 }
5904
5905 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005906 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005907 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005908
5909 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005910}
5911
Andrew Trick3ca3f982011-07-26 17:19:55 +00005912ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005913ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005914 Value *ExitCond,
5915 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005916 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005917 bool ControlsExit,
5918 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005919 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005920 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5921 if (BO->getOpcode() == Instruction::And) {
5922 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005923 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005924 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005925 ControlsExit && !EitherMayExit,
5926 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005927 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005928 ControlsExit && !EitherMayExit,
5929 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005930 const SCEV *BECount = getCouldNotCompute();
5931 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005932 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005933 // Both conditions must be true for the loop to continue executing.
5934 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005935 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5936 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005937 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005938 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005939 BECount =
5940 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5941 if (EL0.MaxNotTaken == getCouldNotCompute())
5942 MaxBECount = EL1.MaxNotTaken;
5943 else if (EL1.MaxNotTaken == getCouldNotCompute())
5944 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005945 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005946 MaxBECount =
5947 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005948 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005949 // Both conditions must be true at the same time for the loop to exit.
5950 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005951 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005952 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5953 MaxBECount = EL0.MaxNotTaken;
5954 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5955 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005956 }
5957
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005958 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5959 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005960 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
5961 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5962 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005963 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5964 !isa<SCEVCouldNotCompute>(BECount))
5965 MaxBECount = BECount;
5966
John Brawn84b21832016-10-21 11:08:48 +00005967 return ExitLimit(BECount, MaxBECount, false,
5968 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00005969 }
5970 if (BO->getOpcode() == Instruction::Or) {
5971 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005972 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005973 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005974 ControlsExit && !EitherMayExit,
5975 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005976 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005977 ControlsExit && !EitherMayExit,
5978 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005979 const SCEV *BECount = getCouldNotCompute();
5980 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005981 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005982 // Both conditions must be false for the loop to continue executing.
5983 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005984 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5985 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005986 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005987 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005988 BECount =
5989 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5990 if (EL0.MaxNotTaken == getCouldNotCompute())
5991 MaxBECount = EL1.MaxNotTaken;
5992 else if (EL1.MaxNotTaken == getCouldNotCompute())
5993 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005994 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005995 MaxBECount =
5996 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005997 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005998 // Both conditions must be false at the same time for the loop to exit.
5999 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006000 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006001 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6002 MaxBECount = EL0.MaxNotTaken;
6003 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6004 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006005 }
6006
John Brawn84b21832016-10-21 11:08:48 +00006007 return ExitLimit(BECount, MaxBECount, false,
6008 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006009 }
6010 }
6011
6012 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006013 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006014 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6015 ExitLimit EL =
6016 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6017 if (EL.hasFullInfo() || !AllowPredicates)
6018 return EL;
6019
6020 // Try again, but use SCEV predicates this time.
6021 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6022 /*AllowPredicates=*/true);
6023 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006024
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006025 // Check for a constant condition. These are normally stripped out by
6026 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6027 // preserve the CFG and is temporarily leaving constant conditions
6028 // in place.
6029 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6030 if (L->contains(FBB) == !CI->getZExtValue())
6031 // The backedge is always taken.
6032 return getCouldNotCompute();
6033 else
6034 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006035 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006036 }
6037
Eli Friedmanebf98b02009-05-09 12:32:42 +00006038 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006039 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006040}
6041
Andrew Trick3ca3f982011-07-26 17:19:55 +00006042ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006043ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006044 ICmpInst *ExitCond,
6045 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006046 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006047 bool ControlsExit,
6048 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006049
Reid Spencer266e42b2006-12-23 06:05:41 +00006050 // If the condition was exit on true, convert the condition to exit on false
6051 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006052 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006053 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006054 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006055 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006056
6057 // Handle common loops like: for (X = "string"; *X; ++X)
6058 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6059 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006060 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006061 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006062 if (ItCnt.hasAnyInfo())
6063 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006064 }
6065
Dan Gohmanaf752342009-07-07 17:06:11 +00006066 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6067 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006068
6069 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006070 LHS = getSCEVAtScope(LHS, L);
6071 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006072
Dan Gohmance973df2009-06-24 04:48:43 +00006073 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006074 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006075 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006076 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006077 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006078 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006079 }
6080
Dan Gohman81585c12010-05-03 16:35:17 +00006081 // Simplify the operands before analyzing them.
6082 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6083
Chris Lattnerd934c702004-04-02 20:23:17 +00006084 // If we have a comparison of a chrec against a constant, try to use value
6085 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006086 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6087 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006088 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006089 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006090 ConstantRange CompRange =
6091 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006092
Dan Gohmanaf752342009-07-07 17:06:11 +00006093 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006094 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006095 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006096
Chris Lattnerd934c702004-04-02 20:23:17 +00006097 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006098 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006099 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006100 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006101 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006102 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006103 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006104 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006105 case ICmpInst::ICMP_EQ: { // while (X == Y)
6106 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006107 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006108 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006109 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006110 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006111 case ICmpInst::ICMP_SLT:
6112 case ICmpInst::ICMP_ULT: { // while (X < Y)
6113 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006114 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006115 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006116 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006117 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006118 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006119 case ICmpInst::ICMP_SGT:
6120 case ICmpInst::ICMP_UGT: { // while (X > Y)
6121 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006122 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006123 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006124 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006125 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006126 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006127 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006128 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006129 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006130 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006131
6132 auto *ExhaustiveCount =
6133 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6134
6135 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6136 return ExhaustiveCount;
6137
6138 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6139 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006140}
6141
Benjamin Kramer5a188542014-02-11 15:44:32 +00006142ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006143ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006144 SwitchInst *Switch,
6145 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006146 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006147 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6148
6149 // Give up if the exit is the default dest of a switch.
6150 if (Switch->getDefaultDest() == ExitingBlock)
6151 return getCouldNotCompute();
6152
6153 assert(L->contains(Switch->getDefaultDest()) &&
6154 "Default case must not exit the loop!");
6155 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6156 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6157
6158 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006159 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006160 if (EL.hasAnyInfo())
6161 return EL;
6162
6163 return getCouldNotCompute();
6164}
6165
Chris Lattnerec901cc2004-10-12 01:49:27 +00006166static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006167EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6168 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006169 const SCEV *InVal = SE.getConstant(C);
6170 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006171 assert(isa<SCEVConstant>(Val) &&
6172 "Evaluation of SCEV at constant didn't fold correctly?");
6173 return cast<SCEVConstant>(Val)->getValue();
6174}
6175
Sanjoy Dasf8570812016-05-29 00:38:22 +00006176/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6177/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006178ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006179ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006180 LoadInst *LI,
6181 Constant *RHS,
6182 const Loop *L,
6183 ICmpInst::Predicate predicate) {
6184
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006185 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006186
6187 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006188 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006189 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006190 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006191
6192 // Make sure that it is really a constant global we are gepping, with an
6193 // initializer, and make sure the first IDX is really 0.
6194 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006195 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006196 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6197 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006198 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006199
6200 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006201 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006202 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006203 unsigned VarIdxNum = 0;
6204 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6205 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6206 Indexes.push_back(CI);
6207 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006208 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006209 VarIdx = GEP->getOperand(i);
6210 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006211 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006212 }
6213
Andrew Trick7004e4b2012-03-26 22:33:59 +00006214 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6215 if (!VarIdx)
6216 return getCouldNotCompute();
6217
Chris Lattnerec901cc2004-10-12 01:49:27 +00006218 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6219 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006220 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006221 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006222
6223 // We can only recognize very limited forms of loop index expressions, in
6224 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006225 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006226 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006227 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6228 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006229 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006230
6231 unsigned MaxSteps = MaxBruteForceIterations;
6232 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006233 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006234 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006235 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006236
6237 // Form the GEP offset.
6238 Indexes[VarIdxNum] = Val;
6239
Chris Lattnere166a852012-01-24 05:49:24 +00006240 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6241 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006242 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006243
6244 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006245 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006246 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006247 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006248 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006249 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006250 }
6251 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006252 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006253}
6254
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006255ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6256 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6257 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6258 if (!RHS)
6259 return getCouldNotCompute();
6260
6261 const BasicBlock *Latch = L->getLoopLatch();
6262 if (!Latch)
6263 return getCouldNotCompute();
6264
6265 const BasicBlock *Predecessor = L->getLoopPredecessor();
6266 if (!Predecessor)
6267 return getCouldNotCompute();
6268
6269 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6270 // Return LHS in OutLHS and shift_opt in OutOpCode.
6271 auto MatchPositiveShift =
6272 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6273
6274 using namespace PatternMatch;
6275
6276 ConstantInt *ShiftAmt;
6277 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6278 OutOpCode = Instruction::LShr;
6279 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6280 OutOpCode = Instruction::AShr;
6281 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6282 OutOpCode = Instruction::Shl;
6283 else
6284 return false;
6285
6286 return ShiftAmt->getValue().isStrictlyPositive();
6287 };
6288
6289 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6290 //
6291 // loop:
6292 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6293 // %iv.shifted = lshr i32 %iv, <positive constant>
6294 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006295 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006296 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6297 auto MatchShiftRecurrence =
6298 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6299 Optional<Instruction::BinaryOps> PostShiftOpCode;
6300
6301 {
6302 Instruction::BinaryOps OpC;
6303 Value *V;
6304
6305 // If we encounter a shift instruction, "peel off" the shift operation,
6306 // and remember that we did so. Later when we inspect %iv's backedge
6307 // value, we will make sure that the backedge value uses the same
6308 // operation.
6309 //
6310 // Note: the peeled shift operation does not have to be the same
6311 // instruction as the one feeding into the PHI's backedge value. We only
6312 // really care about it being the same *kind* of shift instruction --
6313 // that's all that is required for our later inferences to hold.
6314 if (MatchPositiveShift(LHS, V, OpC)) {
6315 PostShiftOpCode = OpC;
6316 LHS = V;
6317 }
6318 }
6319
6320 PNOut = dyn_cast<PHINode>(LHS);
6321 if (!PNOut || PNOut->getParent() != L->getHeader())
6322 return false;
6323
6324 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6325 Value *OpLHS;
6326
6327 return
6328 // The backedge value for the PHI node must be a shift by a positive
6329 // amount
6330 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6331
6332 // of the PHI node itself
6333 OpLHS == PNOut &&
6334
6335 // and the kind of shift should be match the kind of shift we peeled
6336 // off, if any.
6337 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6338 };
6339
6340 PHINode *PN;
6341 Instruction::BinaryOps OpCode;
6342 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6343 return getCouldNotCompute();
6344
6345 const DataLayout &DL = getDataLayout();
6346
6347 // The key rationale for this optimization is that for some kinds of shift
6348 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6349 // within a finite number of iterations. If the condition guarding the
6350 // backedge (in the sense that the backedge is taken if the condition is true)
6351 // is false for the value the shift recurrence stabilizes to, then we know
6352 // that the backedge is taken only a finite number of times.
6353
6354 ConstantInt *StableValue = nullptr;
6355 switch (OpCode) {
6356 default:
6357 llvm_unreachable("Impossible case!");
6358
6359 case Instruction::AShr: {
6360 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6361 // bitwidth(K) iterations.
6362 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6363 bool KnownZero, KnownOne;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00006364 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006365 Predecessor->getTerminator(), &DT);
6366 auto *Ty = cast<IntegerType>(RHS->getType());
6367 if (KnownZero)
6368 StableValue = ConstantInt::get(Ty, 0);
6369 else if (KnownOne)
6370 StableValue = ConstantInt::get(Ty, -1, true);
6371 else
6372 return getCouldNotCompute();
6373
6374 break;
6375 }
6376 case Instruction::LShr:
6377 case Instruction::Shl:
6378 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6379 // stabilize to 0 in at most bitwidth(K) iterations.
6380 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6381 break;
6382 }
6383
6384 auto *Result =
6385 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6386 assert(Result->getType()->isIntegerTy(1) &&
6387 "Otherwise cannot be an operand to a branch instruction");
6388
6389 if (Result->isZeroValue()) {
6390 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6391 const SCEV *UpperBound =
6392 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006393 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006394 }
6395
6396 return getCouldNotCompute();
6397}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006398
Sanjoy Dasf8570812016-05-29 00:38:22 +00006399/// Return true if we can constant fold an instruction of the specified type,
6400/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006401static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006402 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006403 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6404 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006405 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006406
Chris Lattnerdd730472004-04-17 22:58:41 +00006407 if (const CallInst *CI = dyn_cast<CallInst>(I))
6408 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006409 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006410 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006411}
6412
Andrew Trick3a86ba72011-10-05 03:25:31 +00006413/// Determine whether this instruction can constant evolve within this loop
6414/// assuming its operands can all constant evolve.
6415static bool canConstantEvolve(Instruction *I, const Loop *L) {
6416 // An instruction outside of the loop can't be derived from a loop PHI.
6417 if (!L->contains(I)) return false;
6418
6419 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006420 // We don't currently keep track of the control flow needed to evaluate
6421 // PHIs, so we cannot handle PHIs inside of loops.
6422 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006423 }
6424
6425 // If we won't be able to constant fold this expression even if the operands
6426 // are constants, bail early.
6427 return CanConstantFold(I);
6428}
6429
6430/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6431/// recursing through each instruction operand until reaching a loop header phi.
6432static PHINode *
6433getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Michael Liao468fb742017-01-13 18:28:30 +00006434 DenseMap<Instruction *, PHINode *> &PHIMap,
6435 unsigned Depth) {
6436 if (Depth > MaxConstantEvolvingDepth)
6437 return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006438
6439 // Otherwise, we can evaluate this instruction if all of its operands are
6440 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006441 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006442 for (Value *Op : UseInst->operands()) {
6443 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006444
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006445 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006446 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006447
6448 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006449 if (!P)
6450 // If this operand is already visited, reuse the prior result.
6451 // We may have P != PHI if this is the deepest point at which the
6452 // inconsistent paths meet.
6453 P = PHIMap.lookup(OpInst);
6454 if (!P) {
6455 // Recurse and memoize the results, whether a phi is found or not.
6456 // This recursive call invalidates pointers into PHIMap.
Michael Liao468fb742017-01-13 18:28:30 +00006457 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006458 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006459 }
Craig Topper9f008862014-04-15 04:59:12 +00006460 if (!P)
6461 return nullptr; // Not evolving from PHI
6462 if (PHI && PHI != P)
6463 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006464 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006465 }
6466 // This is a expression evolving from a constant PHI!
6467 return PHI;
6468}
6469
Chris Lattnerdd730472004-04-17 22:58:41 +00006470/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6471/// in the loop that V is derived from. We allow arbitrary operations along the
6472/// way, but the operands of an operation must either be constants or a value
6473/// derived from a constant PHI. If this expression does not fit with these
6474/// constraints, return null.
6475static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006476 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006477 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006478
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006479 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006480 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006481
Andrew Trick3a86ba72011-10-05 03:25:31 +00006482 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006483 DenseMap<Instruction *, PHINode *> PHIMap;
Michael Liao468fb742017-01-13 18:28:30 +00006484 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
Chris Lattnerdd730472004-04-17 22:58:41 +00006485}
6486
6487/// EvaluateExpression - Given an expression that passes the
6488/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6489/// in the loop has the value PHIVal. If we can't fold this expression for some
6490/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006491static Constant *EvaluateExpression(Value *V, const Loop *L,
6492 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006493 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006494 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006495 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006496 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006497 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006498 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006499
Andrew Trick3a86ba72011-10-05 03:25:31 +00006500 if (Constant *C = Vals.lookup(I)) return C;
6501
Nick Lewyckya6674c72011-10-22 19:58:20 +00006502 // An instruction inside the loop depends on a value outside the loop that we
6503 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006504 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006505
6506 // An unmapped PHI can be due to a branch or another loop inside this loop,
6507 // or due to this not being the initial iteration through a loop where we
6508 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006509 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006510
Dan Gohmanf820bd32010-06-22 13:15:46 +00006511 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006512
6513 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006514 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6515 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006516 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006517 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006518 continue;
6519 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006520 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006521 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006522 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006523 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006524 }
6525
Nick Lewyckya6674c72011-10-22 19:58:20 +00006526 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006527 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006528 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006529 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6530 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006531 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006532 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006533 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006534}
6535
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006536
6537// If every incoming value to PN except the one for BB is a specific Constant,
6538// return that, else return nullptr.
6539static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6540 Constant *IncomingVal = nullptr;
6541
6542 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6543 if (PN->getIncomingBlock(i) == BB)
6544 continue;
6545
6546 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6547 if (!CurrentVal)
6548 return nullptr;
6549
6550 if (IncomingVal != CurrentVal) {
6551 if (IncomingVal)
6552 return nullptr;
6553 IncomingVal = CurrentVal;
6554 }
6555 }
6556
6557 return IncomingVal;
6558}
6559
Chris Lattnerdd730472004-04-17 22:58:41 +00006560/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6561/// in the header of its containing loop, we know the loop executes a
6562/// constant number of times, and the PHI node is just a recurrence
6563/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006564Constant *
6565ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006566 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006567 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006568 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006569 if (I != ConstantEvolutionLoopExitValue.end())
6570 return I->second;
6571
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006572 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006573 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006574
6575 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6576
Andrew Trick3a86ba72011-10-05 03:25:31 +00006577 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006578 BasicBlock *Header = L->getHeader();
6579 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006580
Sanjoy Dasdd709962015-10-08 18:28:36 +00006581 BasicBlock *Latch = L->getLoopLatch();
6582 if (!Latch)
6583 return nullptr;
6584
Sanjoy Das4493b402015-10-07 17:38:25 +00006585 for (auto &I : *Header) {
6586 PHINode *PHI = dyn_cast<PHINode>(&I);
6587 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006588 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006589 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006590 CurrentIterVals[PHI] = StartCST;
6591 }
6592 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006593 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006594
Sanjoy Dasdd709962015-10-08 18:28:36 +00006595 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006596
6597 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006598 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006599 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006600
Dan Gohman0bddac12009-02-24 18:55:53 +00006601 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006602 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006603 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006604 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006605 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006606 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006607
Nick Lewyckya6674c72011-10-22 19:58:20 +00006608 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006609 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006610 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006611 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006612 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006613 if (!NextPHI)
6614 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006615 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006616
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006617 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6618
Nick Lewyckya6674c72011-10-22 19:58:20 +00006619 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6620 // cease to be able to evaluate one of them or if they stop evolving,
6621 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006622 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006623 for (const auto &I : CurrentIterVals) {
6624 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006625 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006626 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006627 }
6628 // We use two distinct loops because EvaluateExpression may invalidate any
6629 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006630 for (const auto &I : PHIsToCompute) {
6631 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006632 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006633 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006634 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006635 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006636 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006637 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006638 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006639 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006640
6641 // If all entries in CurrentIterVals == NextIterVals then we can stop
6642 // iterating, the loop can't continue to change.
6643 if (StoppedEvolving)
6644 return RetVal = CurrentIterVals[PN];
6645
Andrew Trick3a86ba72011-10-05 03:25:31 +00006646 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006647 }
6648}
6649
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006650const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006651 Value *Cond,
6652 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006653 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006654 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006655
Dan Gohman866971e2010-06-19 14:17:24 +00006656 // If the loop is canonicalized, the PHI will have exactly two entries.
6657 // That's the only form we support here.
6658 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6659
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006660 DenseMap<Instruction *, Constant *> CurrentIterVals;
6661 BasicBlock *Header = L->getHeader();
6662 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6663
Sanjoy Dasdd709962015-10-08 18:28:36 +00006664 BasicBlock *Latch = L->getLoopLatch();
6665 assert(Latch && "Should follow from NumIncomingValues == 2!");
6666
Sanjoy Das4493b402015-10-07 17:38:25 +00006667 for (auto &I : *Header) {
6668 PHINode *PHI = dyn_cast<PHINode>(&I);
6669 if (!PHI)
6670 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006671 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006672 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006673 CurrentIterVals[PHI] = StartCST;
6674 }
6675 if (!CurrentIterVals.count(PN))
6676 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006677
6678 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6679 // the loop symbolically to determine when the condition gets a value of
6680 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006681 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006682 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006683 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006684 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006685 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006686
Zhou Sheng75b871f2007-01-11 12:24:14 +00006687 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006688 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006689
Reid Spencer983e3b32007-03-01 07:25:48 +00006690 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006691 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006692 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006693 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006694
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006695 // Update all the PHI nodes for the next iteration.
6696 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006697
6698 // Create a list of which PHIs we need to compute. We want to do this before
6699 // calling EvaluateExpression on them because that may invalidate iterators
6700 // into CurrentIterVals.
6701 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006702 for (const auto &I : CurrentIterVals) {
6703 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006704 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006705 PHIsToCompute.push_back(PHI);
6706 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006707 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006708 Constant *&NextPHI = NextIterVals[PHI];
6709 if (NextPHI) continue; // Already computed!
6710
Sanjoy Dasdd709962015-10-08 18:28:36 +00006711 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006712 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006713 }
6714 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006715 }
6716
6717 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006718 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006719}
6720
Dan Gohmanaf752342009-07-07 17:06:11 +00006721const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006722 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6723 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006724 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006725 for (auto &LS : Values)
6726 if (LS.first == L)
6727 return LS.second ? LS.second : V;
6728
6729 Values.emplace_back(L, nullptr);
6730
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006731 // Otherwise compute it.
6732 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006733 for (auto &LS : reverse(ValuesAtScopes[V]))
6734 if (LS.first == L) {
6735 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006736 break;
6737 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006738 return C;
6739}
6740
Nick Lewyckya6674c72011-10-22 19:58:20 +00006741/// This builds up a Constant using the ConstantExpr interface. That way, we
6742/// will return Constants for objects which aren't represented by a
6743/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6744/// Returns NULL if the SCEV isn't representable as a Constant.
6745static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006746 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006747 case scCouldNotCompute:
6748 case scAddRecExpr:
6749 break;
6750 case scConstant:
6751 return cast<SCEVConstant>(V)->getValue();
6752 case scUnknown:
6753 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6754 case scSignExtend: {
6755 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6756 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6757 return ConstantExpr::getSExt(CastOp, SS->getType());
6758 break;
6759 }
6760 case scZeroExtend: {
6761 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6762 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6763 return ConstantExpr::getZExt(CastOp, SZ->getType());
6764 break;
6765 }
6766 case scTruncate: {
6767 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6768 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6769 return ConstantExpr::getTrunc(CastOp, ST->getType());
6770 break;
6771 }
6772 case scAddExpr: {
6773 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6774 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006775 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6776 unsigned AS = PTy->getAddressSpace();
6777 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6778 C = ConstantExpr::getBitCast(C, DestPtrTy);
6779 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006780 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6781 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006782 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006783
6784 // First pointer!
6785 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006786 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006787 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006788 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006789 // The offsets have been converted to bytes. We can add bytes to an
6790 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006791 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006792 }
6793
6794 // Don't bother trying to sum two pointers. We probably can't
6795 // statically compute a load that results from it anyway.
6796 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006797 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006798
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006799 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6800 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006801 C2 = ConstantExpr::getIntegerCast(
6802 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006803 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006804 } else
6805 C = ConstantExpr::getAdd(C, C2);
6806 }
6807 return C;
6808 }
6809 break;
6810 }
6811 case scMulExpr: {
6812 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6813 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6814 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006815 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006816 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6817 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006818 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006819 C = ConstantExpr::getMul(C, C2);
6820 }
6821 return C;
6822 }
6823 break;
6824 }
6825 case scUDivExpr: {
6826 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6827 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6828 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6829 if (LHS->getType() == RHS->getType())
6830 return ConstantExpr::getUDiv(LHS, RHS);
6831 break;
6832 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006833 case scSMaxExpr:
6834 case scUMaxExpr:
6835 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006836 }
Craig Topper9f008862014-04-15 04:59:12 +00006837 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006838}
6839
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006840const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006841 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006842
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006843 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006844 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006845 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006846 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006847 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006848 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6849 if (PHINode *PN = dyn_cast<PHINode>(I))
6850 if (PN->getParent() == LI->getHeader()) {
6851 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006852 // to see if the loop that contains it has a known backedge-taken
6853 // count. If so, we may be able to force computation of the exit
6854 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006855 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006856 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006857 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006858 // Okay, we know how many times the containing loop executes. If
6859 // this is a constant evolving PHI node, get the final value at
6860 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006861 Constant *RV =
6862 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006863 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006864 }
6865 }
6866
Reid Spencere6328ca2006-12-04 21:33:23 +00006867 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006868 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006869 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006870 // result. This is particularly useful for computing loop exit values.
6871 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006872 SmallVector<Constant *, 4> Operands;
6873 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006874 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006875 if (Constant *C = dyn_cast<Constant>(Op)) {
6876 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006877 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006878 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006879
6880 // If any of the operands is non-constant and if they are
6881 // non-integer and non-pointer, don't even try to analyze them
6882 // with scev techniques.
6883 if (!isSCEVable(Op->getType()))
6884 return V;
6885
6886 const SCEV *OrigV = getSCEV(Op);
6887 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6888 MadeImprovement |= OrigV != OpV;
6889
Nick Lewyckya6674c72011-10-22 19:58:20 +00006890 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006891 if (!C) return V;
6892 if (C->getType() != Op->getType())
6893 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6894 Op->getType(),
6895 false),
6896 C, Op->getType());
6897 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006898 }
Dan Gohmance973df2009-06-24 04:48:43 +00006899
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006900 // Check to see if getSCEVAtScope actually made an improvement.
6901 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006902 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006903 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006904 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006905 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006906 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006907 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6908 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006909 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006910 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006911 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006912 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006913 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006914 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006915 }
6916 }
6917
6918 // This is some other type of SCEVUnknown, just return it.
6919 return V;
6920 }
6921
Dan Gohmana30370b2009-05-04 22:02:23 +00006922 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006923 // Avoid performing the look-up in the common case where the specified
6924 // expression has no loop-variant portions.
6925 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006926 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006927 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006928 // Okay, at least one of these operands is loop variant but might be
6929 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006930 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6931 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006932 NewOps.push_back(OpAtScope);
6933
6934 for (++i; i != e; ++i) {
6935 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006936 NewOps.push_back(OpAtScope);
6937 }
6938 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006939 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006940 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006941 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006942 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006943 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006944 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006945 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006946 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006947 }
6948 }
6949 // If we got here, all operands are loop invariant.
6950 return Comm;
6951 }
6952
Dan Gohmana30370b2009-05-04 22:02:23 +00006953 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006954 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6955 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006956 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6957 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006958 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006959 }
6960
6961 // If this is a loop recurrence for a loop that does not contain L, then we
6962 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006963 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006964 // First, attempt to evaluate each operand.
6965 // Avoid performing the look-up in the common case where the specified
6966 // expression has no loop-variant portions.
6967 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6968 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6969 if (OpAtScope == AddRec->getOperand(i))
6970 continue;
6971
6972 // Okay, at least one of these operands is loop variant but might be
6973 // foldable. Build a new instance of the folded commutative expression.
6974 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6975 AddRec->op_begin()+i);
6976 NewOps.push_back(OpAtScope);
6977 for (++i; i != e; ++i)
6978 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6979
Andrew Trick759ba082011-04-27 01:21:25 +00006980 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006981 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006982 AddRec->getNoWrapFlags(SCEV::FlagNW));
6983 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006984 // The addrec may be folded to a nonrecurrence, for example, if the
6985 // induction variable is multiplied by zero after constant folding. Go
6986 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006987 if (!AddRec)
6988 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006989 break;
6990 }
6991
6992 // If the scope is outside the addrec's loop, evaluate it by using the
6993 // loop exit value of the addrec.
6994 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006995 // To evaluate this recurrence, we need to know how many times the AddRec
6996 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006997 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006998 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006999
Eli Friedman61f67622008-08-04 23:49:06 +00007000 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007001 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007002 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007003
Dan Gohman8ca08852009-05-24 23:25:42 +00007004 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007005 }
7006
Dan Gohmana30370b2009-05-04 22:02:23 +00007007 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007008 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007009 if (Op == Cast->getOperand())
7010 return Cast; // must be loop invariant
7011 return getZeroExtendExpr(Op, Cast->getType());
7012 }
7013
Dan Gohmana30370b2009-05-04 22:02:23 +00007014 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007015 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007016 if (Op == Cast->getOperand())
7017 return Cast; // must be loop invariant
7018 return getSignExtendExpr(Op, Cast->getType());
7019 }
7020
Dan Gohmana30370b2009-05-04 22:02:23 +00007021 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007022 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007023 if (Op == Cast->getOperand())
7024 return Cast; // must be loop invariant
7025 return getTruncateExpr(Op, Cast->getType());
7026 }
7027
Torok Edwinfbcc6632009-07-14 16:55:14 +00007028 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007029}
7030
Dan Gohmanaf752342009-07-07 17:06:11 +00007031const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007032 return getSCEVAtScope(getSCEV(V), L);
7033}
7034
Sanjoy Dasf8570812016-05-29 00:38:22 +00007035/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007036///
7037/// A * X = B (mod N)
7038///
7039/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7040/// A and B isn't important.
7041///
7042/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007043static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007044 ScalarEvolution &SE) {
7045 uint32_t BW = A.getBitWidth();
7046 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
7047 assert(A != 0 && "A must be non-zero.");
7048
7049 // 1. D = gcd(A, N)
7050 //
7051 // The gcd of A and N may have only one prime factor: 2. The number of
7052 // trailing zeros in A is its multiplicity
7053 uint32_t Mult2 = A.countTrailingZeros();
7054 // D = 2^Mult2
7055
7056 // 2. Check if B is divisible by D.
7057 //
7058 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7059 // is not less than multiplicity of this prime factor for D.
7060 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007061 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007062
7063 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7064 // modulo (N / D).
7065 //
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007066 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7067 // (N / D) in general. The inverse itself always fits into BW bits, though,
7068 // so we immediately truncate it.
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007069 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7070 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007071 Mod.setBit(BW - Mult2); // Mod = N / D
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007072 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007073
7074 // 4. Compute the minimum unsigned root of the equation:
7075 // I * (B / D) mod (N / D)
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007076 // To simplify the computation, we factor out the divide by D:
7077 // (I * B mod N) / D
7078 APInt Result = (I * B).lshr(Mult2);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007079
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007080 return SE.getConstant(Result);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007081}
Chris Lattnerd934c702004-04-02 20:23:17 +00007082
Sanjoy Dasf8570812016-05-29 00:38:22 +00007083/// Find the roots of the quadratic equation for the given quadratic chrec
7084/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7085/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007086///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007087static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007088SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007089 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007090 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7091 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7092 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007093
Chris Lattnerd934c702004-04-02 20:23:17 +00007094 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007095 if (!LC || !MC || !NC)
7096 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007097
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007098 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7099 const APInt &L = LC->getAPInt();
7100 const APInt &M = MC->getAPInt();
7101 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007102 APInt Two(BitWidth, 2);
7103 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007104
Dan Gohmance973df2009-06-24 04:48:43 +00007105 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007106 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007107 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007108 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7109 // The B coefficient is M-N/2
7110 APInt B(M);
7111 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007112
Reid Spencer983e3b32007-03-01 07:25:48 +00007113 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007114 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007115
Reid Spencer983e3b32007-03-01 07:25:48 +00007116 // Compute the B^2-4ac term.
7117 APInt SqrtTerm(B);
7118 SqrtTerm *= B;
7119 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007120
Nick Lewyckyfb780832012-08-01 09:14:36 +00007121 if (SqrtTerm.isNegative()) {
7122 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007123 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007124 }
7125
Reid Spencer983e3b32007-03-01 07:25:48 +00007126 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7127 // integer value or else APInt::sqrt() will assert.
7128 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007129
Dan Gohmance973df2009-06-24 04:48:43 +00007130 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007131 // The divisions must be performed as signed divisions.
7132 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007133 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007134 if (TwoA.isMinValue())
7135 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007136
Owen Anderson47db9412009-07-22 00:24:57 +00007137 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007138
7139 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007140 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007141 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007142 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007143
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007144 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7145 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007146 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007147}
7148
Andrew Trick3ca3f982011-07-26 17:19:55 +00007149ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007150ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007151 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007152
7153 // This is only used for loops with a "x != y" exit test. The exit condition
7154 // is now expressed as a single expression, V = x-y. So the exit test is
7155 // effectively V != 0. We know and take advantage of the fact that this
7156 // expression only being used in a comparison by zero context.
7157
Sanjoy Dasf0022122016-09-28 17:14:58 +00007158 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007159 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007160 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007161 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007162 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007163 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007164 }
7165
Dan Gohman48f82222009-05-04 22:30:44 +00007166 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007167 if (!AddRec && AllowPredicates)
7168 // Try to make this an AddRec using runtime tests, in the first X
7169 // iterations of this loop, where X is the SCEV expression found by the
7170 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007171 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007172
Chris Lattnerd934c702004-04-02 20:23:17 +00007173 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007174 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007175
Chris Lattnerdff679f2011-01-09 22:39:48 +00007176 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7177 // the quadratic equation to solve it.
7178 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007179 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7180 const SCEVConstant *R1 = Roots->first;
7181 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007182 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007183 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7184 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007185 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007186 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007187
Chris Lattnerd934c702004-04-02 20:23:17 +00007188 // We can only use this value if the chrec ends up with an exact zero
7189 // value at this index. When solving for "X*X != 5", for example, we
7190 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007191 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007192 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007193 // We found a quadratic root!
7194 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007195 }
7196 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007197 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007198 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007199
Chris Lattnerdff679f2011-01-09 22:39:48 +00007200 // Otherwise we can only handle this if it is affine.
7201 if (!AddRec->isAffine())
7202 return getCouldNotCompute();
7203
7204 // If this is an affine expression, the execution count of this branch is
7205 // the minimum unsigned root of the following equation:
7206 //
7207 // Start + Step*N = 0 (mod 2^BW)
7208 //
7209 // equivalent to:
7210 //
7211 // Step*N = -Start (mod 2^BW)
7212 //
7213 // where BW is the common bit width of Start and Step.
7214
7215 // Get the initial value for the loop.
7216 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7217 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7218
7219 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007220 //
7221 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7222 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7223 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7224 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007225 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007226 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007227 return getCouldNotCompute();
7228
Andrew Trick8b55b732011-03-14 16:50:06 +00007229 // For positive steps (counting up until unsigned overflow):
7230 // N = -Start/Step (as unsigned)
7231 // For negative steps (counting down to zero):
7232 // N = Start/-Step
7233 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007234 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007235 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007236
7237 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007238 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7239 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007240 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
Eli Friedman83962652017-01-11 20:55:48 +00007241 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
Eli Friedmanbd6deda2017-01-11 21:07:15 +00007242
7243 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7244 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7245 // case, and see if we can improve the bound.
7246 //
7247 // Explicitly handling this here is necessary because getUnsignedRange
7248 // isn't context-sensitive; it doesn't know that we only care about the
7249 // range inside the loop.
7250 const SCEV *Zero = getZero(Distance->getType());
7251 const SCEV *One = getOne(Distance->getType());
7252 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7253 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7254 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7255 // as "unsigned_max(Distance + 1) - 1".
7256 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7257 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7258 }
Eli Friedman83962652017-01-11 20:55:48 +00007259 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007260 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007261
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007262 // As a special case, handle the instance where Step is a positive power of
7263 // two. In this case, determining whether Step divides Distance evenly can be
7264 // done by counting and comparing the number of trailing zeros of Step and
7265 // Distance.
7266 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007267 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007268 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7269 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7270 // case is not handled as this code is guarded by !CountDown.
7271 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007272 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7273 // Here we've constrained the equation to be of the form
7274 //
7275 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7276 //
7277 // where we're operating on a W bit wide integer domain and k is
7278 // non-negative. The smallest unsigned solution for X is the trip count.
7279 //
7280 // (0) is equivalent to:
7281 //
7282 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7283 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7284 // <=> 2^k * Distance' - X = L * 2^(W - N)
7285 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7286 //
7287 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7288 // by 2^(W - N).
7289 //
7290 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7291 //
7292 // E.g. say we're solving
7293 //
7294 // 2 * Val = 2 * X (in i8) ... (3)
7295 //
7296 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7297 //
7298 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7299 // necessarily the smallest unsigned value of X that satisfies (3).
7300 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7301 // is i8 1, not i8 -127
7302
Eli Friedmanf1f49c82017-01-18 23:56:42 +00007303 const auto *Limit = getUDivExactExpr(Distance, Step);
John Brawn84b21832016-10-21 11:08:48 +00007304 return ExitLimit(Limit, Limit, false, Predicates);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007305 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007306 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007307
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007308 // If the condition controls loop exit (the loop exits only if the expression
7309 // is true) and the addition is no-wrap we can use unsigned divide to
7310 // compute the backedge count. In this case, the step may not divide the
7311 // distance, but we don't care because if the condition is "missed" the loop
7312 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007313 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7314 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007315 const SCEV *Exact =
7316 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007317 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007318 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007319
Chris Lattnerdff679f2011-01-09 22:39:48 +00007320 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007321 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7322 const SCEV *E = SolveLinEquationWithOverflow(
7323 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
John Brawn84b21832016-10-21 11:08:48 +00007324 return ExitLimit(E, E, false, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007325 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007326 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007327}
7328
Andrew Trick3ca3f982011-07-26 17:19:55 +00007329ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007330ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007331 // Loops that look like: while (X == 0) are very strange indeed. We don't
7332 // handle them yet except for the trivial case. This could be expanded in the
7333 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007334
Chris Lattnerd934c702004-04-02 20:23:17 +00007335 // If the value is a constant, check to see if it is known to be non-zero
7336 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007337 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007338 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007339 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007340 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007341 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007342
Chris Lattnerd934c702004-04-02 20:23:17 +00007343 // We could implement others, but I really doubt anyone writes loops like
7344 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007345 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007346}
7347
Dan Gohman4e3c1132010-04-15 16:19:08 +00007348std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007349ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007350 // If the block has a unique predecessor, then there is no path from the
7351 // predecessor to the block that does not go through the direct edge
7352 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007353 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007354 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007355
7356 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007357 // If the header has a unique predecessor outside the loop, it must be
7358 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007359 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007360 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007361
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007362 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007363}
7364
Sanjoy Dasf8570812016-05-29 00:38:22 +00007365/// SCEV structural equivalence is usually sufficient for testing whether two
7366/// expressions are equal, however for the purposes of looking for a condition
7367/// guarding a loop, it can be useful to be a little more general, since a
7368/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007369///
Dan Gohmanaf752342009-07-07 17:06:11 +00007370static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007371 // Quick check to see if they are the same SCEV.
7372 if (A == B) return true;
7373
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007374 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7375 // Not all instructions that are "identical" compute the same value. For
7376 // instance, two distinct alloca instructions allocating the same type are
7377 // identical and do not read memory; but compute distinct values.
7378 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7379 };
7380
Dan Gohman450f4e02009-06-20 00:35:32 +00007381 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7382 // two different instructions with the same value. Check for this case.
7383 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7384 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7385 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7386 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007387 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007388 return true;
7389
7390 // Otherwise assume they may have a different value.
7391 return false;
7392}
7393
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007394bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007395 const SCEV *&LHS, const SCEV *&RHS,
7396 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007397 bool Changed = false;
7398
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007399 // If we hit the max recursion limit bail out.
7400 if (Depth >= 3)
7401 return false;
7402
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007403 // Canonicalize a constant to the right side.
7404 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7405 // Check for both operands constant.
7406 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7407 if (ConstantExpr::getICmp(Pred,
7408 LHSC->getValue(),
7409 RHSC->getValue())->isNullValue())
7410 goto trivially_false;
7411 else
7412 goto trivially_true;
7413 }
7414 // Otherwise swap the operands to put the constant on the right.
7415 std::swap(LHS, RHS);
7416 Pred = ICmpInst::getSwappedPredicate(Pred);
7417 Changed = true;
7418 }
7419
7420 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007421 // addrec's loop, put the addrec on the left. Also make a dominance check,
7422 // as both operands could be addrecs loop-invariant in each other's loop.
7423 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7424 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007425 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007426 std::swap(LHS, RHS);
7427 Pred = ICmpInst::getSwappedPredicate(Pred);
7428 Changed = true;
7429 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007430 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007431
7432 // If there's a constant operand, canonicalize comparisons with boundary
7433 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7434 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007435 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007436
7437 bool SimplifiedByConstantRange = false;
7438
7439 if (!ICmpInst::isEquality(Pred)) {
7440 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7441 if (ExactCR.isFullSet())
7442 goto trivially_true;
7443 else if (ExactCR.isEmptySet())
7444 goto trivially_false;
7445
7446 APInt NewRHS;
7447 CmpInst::Predicate NewPred;
7448 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7449 ICmpInst::isEquality(NewPred)) {
7450 // We were able to convert an inequality to an equality.
7451 Pred = NewPred;
7452 RHS = getConstant(NewRHS);
7453 Changed = SimplifiedByConstantRange = true;
7454 }
7455 }
7456
7457 if (!SimplifiedByConstantRange) {
7458 switch (Pred) {
7459 default:
7460 break;
7461 case ICmpInst::ICMP_EQ:
7462 case ICmpInst::ICMP_NE:
7463 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7464 if (!RA)
7465 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7466 if (const SCEVMulExpr *ME =
7467 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7468 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7469 ME->getOperand(0)->isAllOnesValue()) {
7470 RHS = AE->getOperand(1);
7471 LHS = ME->getOperand(1);
7472 Changed = true;
7473 }
7474 break;
7475
7476
7477 // The "Should have been caught earlier!" messages refer to the fact
7478 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7479 // should have fired on the corresponding cases, and canonicalized the
7480 // check to trivially_true or trivially_false.
7481
7482 case ICmpInst::ICMP_UGE:
7483 assert(!RA.isMinValue() && "Should have been caught earlier!");
7484 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007485 RHS = getConstant(RA - 1);
7486 Changed = true;
7487 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007488 case ICmpInst::ICMP_ULE:
7489 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7490 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007491 RHS = getConstant(RA + 1);
7492 Changed = true;
7493 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007494 case ICmpInst::ICMP_SGE:
7495 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7496 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007497 RHS = getConstant(RA - 1);
7498 Changed = true;
7499 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007500 case ICmpInst::ICMP_SLE:
7501 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7502 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007503 RHS = getConstant(RA + 1);
7504 Changed = true;
7505 break;
7506 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007507 }
7508 }
7509
7510 // Check for obvious equality.
7511 if (HasSameValue(LHS, RHS)) {
7512 if (ICmpInst::isTrueWhenEqual(Pred))
7513 goto trivially_true;
7514 if (ICmpInst::isFalseWhenEqual(Pred))
7515 goto trivially_false;
7516 }
7517
Dan Gohman81585c12010-05-03 16:35:17 +00007518 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7519 // adding or subtracting 1 from one of the operands.
7520 switch (Pred) {
7521 case ICmpInst::ICMP_SLE:
7522 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7523 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007524 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007525 Pred = ICmpInst::ICMP_SLT;
7526 Changed = true;
7527 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007528 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007529 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007530 Pred = ICmpInst::ICMP_SLT;
7531 Changed = true;
7532 }
7533 break;
7534 case ICmpInst::ICMP_SGE:
7535 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007536 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007537 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007538 Pred = ICmpInst::ICMP_SGT;
7539 Changed = true;
7540 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7541 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007542 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007543 Pred = ICmpInst::ICMP_SGT;
7544 Changed = true;
7545 }
7546 break;
7547 case ICmpInst::ICMP_ULE:
7548 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007549 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007550 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007551 Pred = ICmpInst::ICMP_ULT;
7552 Changed = true;
7553 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007554 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007555 Pred = ICmpInst::ICMP_ULT;
7556 Changed = true;
7557 }
7558 break;
7559 case ICmpInst::ICMP_UGE:
7560 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007561 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007562 Pred = ICmpInst::ICMP_UGT;
7563 Changed = true;
7564 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007565 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007566 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007567 Pred = ICmpInst::ICMP_UGT;
7568 Changed = true;
7569 }
7570 break;
7571 default:
7572 break;
7573 }
7574
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007575 // TODO: More simplifications are possible here.
7576
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007577 // Recursively simplify until we either hit a recursion limit or nothing
7578 // changes.
7579 if (Changed)
7580 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7581
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007582 return Changed;
7583
7584trivially_true:
7585 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007586 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007587 Pred = ICmpInst::ICMP_EQ;
7588 return true;
7589
7590trivially_false:
7591 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007592 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007593 Pred = ICmpInst::ICMP_NE;
7594 return true;
7595}
7596
Dan Gohmane65c9172009-07-13 21:35:55 +00007597bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7598 return getSignedRange(S).getSignedMax().isNegative();
7599}
7600
7601bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7602 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7603}
7604
7605bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7606 return !getSignedRange(S).getSignedMin().isNegative();
7607}
7608
7609bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7610 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7611}
7612
7613bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7614 return isKnownNegative(S) || isKnownPositive(S);
7615}
7616
7617bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7618 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007619 // Canonicalize the inputs first.
7620 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7621
Dan Gohman07591692010-04-11 22:16:48 +00007622 // If LHS or RHS is an addrec, check to see if the condition is true in
7623 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007624 // If LHS and RHS are both addrec, both conditions must be true in
7625 // every iteration of the loop.
7626 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7627 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7628 bool LeftGuarded = false;
7629 bool RightGuarded = false;
7630 if (LAR) {
7631 const Loop *L = LAR->getLoop();
7632 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7633 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7634 if (!RAR) return true;
7635 LeftGuarded = true;
7636 }
7637 }
7638 if (RAR) {
7639 const Loop *L = RAR->getLoop();
7640 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7641 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7642 if (!LAR) return true;
7643 RightGuarded = true;
7644 }
7645 }
7646 if (LeftGuarded && RightGuarded)
7647 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007648
Sanjoy Das7d910f22015-10-02 18:50:30 +00007649 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7650 return true;
7651
Dan Gohman07591692010-04-11 22:16:48 +00007652 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007653 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007654}
7655
Sanjoy Das5dab2052015-07-27 21:42:49 +00007656bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7657 ICmpInst::Predicate Pred,
7658 bool &Increasing) {
7659 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7660
7661#ifndef NDEBUG
7662 // Verify an invariant: inverting the predicate should turn a monotonically
7663 // increasing change to a monotonically decreasing one, and vice versa.
7664 bool IncreasingSwapped;
7665 bool ResultSwapped = isMonotonicPredicateImpl(
7666 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7667
7668 assert(Result == ResultSwapped && "should be able to analyze both!");
7669 if (ResultSwapped)
7670 assert(Increasing == !IncreasingSwapped &&
7671 "monotonicity should flip as we flip the predicate");
7672#endif
7673
7674 return Result;
7675}
7676
7677bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7678 ICmpInst::Predicate Pred,
7679 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007680
7681 // A zero step value for LHS means the induction variable is essentially a
7682 // loop invariant value. We don't really depend on the predicate actually
7683 // flipping from false to true (for increasing predicates, and the other way
7684 // around for decreasing predicates), all we care about is that *if* the
7685 // predicate changes then it only changes from false to true.
7686 //
7687 // A zero step value in itself is not very useful, but there may be places
7688 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7689 // as general as possible.
7690
Sanjoy Das366acc12015-08-06 20:43:41 +00007691 switch (Pred) {
7692 default:
7693 return false; // Conservative answer
7694
7695 case ICmpInst::ICMP_UGT:
7696 case ICmpInst::ICMP_UGE:
7697 case ICmpInst::ICMP_ULT:
7698 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007699 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007700 return false;
7701
7702 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007703 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007704
7705 case ICmpInst::ICMP_SGT:
7706 case ICmpInst::ICMP_SGE:
7707 case ICmpInst::ICMP_SLT:
7708 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007709 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007710 return false;
7711
7712 const SCEV *Step = LHS->getStepRecurrence(*this);
7713
7714 if (isKnownNonNegative(Step)) {
7715 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7716 return true;
7717 }
7718
7719 if (isKnownNonPositive(Step)) {
7720 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7721 return true;
7722 }
7723
7724 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007725 }
7726
Sanjoy Das5dab2052015-07-27 21:42:49 +00007727 }
7728
Sanjoy Das366acc12015-08-06 20:43:41 +00007729 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007730}
7731
7732bool ScalarEvolution::isLoopInvariantPredicate(
7733 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7734 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7735 const SCEV *&InvariantRHS) {
7736
7737 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7738 if (!isLoopInvariant(RHS, L)) {
7739 if (!isLoopInvariant(LHS, L))
7740 return false;
7741
7742 std::swap(LHS, RHS);
7743 Pred = ICmpInst::getSwappedPredicate(Pred);
7744 }
7745
7746 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7747 if (!ArLHS || ArLHS->getLoop() != L)
7748 return false;
7749
7750 bool Increasing;
7751 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7752 return false;
7753
7754 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7755 // true as the loop iterates, and the backedge is control dependent on
7756 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7757 //
7758 // * if the predicate was false in the first iteration then the predicate
7759 // is never evaluated again, since the loop exits without taking the
7760 // backedge.
7761 // * if the predicate was true in the first iteration then it will
7762 // continue to be true for all future iterations since it is
7763 // monotonically increasing.
7764 //
7765 // For both the above possibilities, we can replace the loop varying
7766 // predicate with its value on the first iteration of the loop (which is
7767 // loop invariant).
7768 //
7769 // A similar reasoning applies for a monotonically decreasing predicate, by
7770 // replacing true with false and false with true in the above two bullets.
7771
7772 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7773
7774 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7775 return false;
7776
7777 InvariantPred = Pred;
7778 InvariantLHS = ArLHS->getStart();
7779 InvariantRHS = RHS;
7780 return true;
7781}
7782
Sanjoy Das401e6312016-02-01 20:48:10 +00007783bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7784 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007785 if (HasSameValue(LHS, RHS))
7786 return ICmpInst::isTrueWhenEqual(Pred);
7787
Dan Gohman07591692010-04-11 22:16:48 +00007788 // This code is split out from isKnownPredicate because it is called from
7789 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007790
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007791 auto CheckRanges =
7792 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7793 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7794 .contains(RangeLHS);
7795 };
7796
7797 // The check at the top of the function catches the case where the values are
7798 // known to be equal.
7799 if (Pred == CmpInst::ICMP_EQ)
7800 return false;
7801
7802 if (Pred == CmpInst::ICMP_NE)
7803 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7804 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7805 isKnownNonZero(getMinusSCEV(LHS, RHS));
7806
7807 if (CmpInst::isSigned(Pred))
7808 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7809
7810 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007811}
7812
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007813bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7814 const SCEV *LHS,
7815 const SCEV *RHS) {
7816
7817 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7818 // Return Y via OutY.
7819 auto MatchBinaryAddToConst =
7820 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7821 SCEV::NoWrapFlags ExpectedFlags) {
7822 const SCEV *NonConstOp, *ConstOp;
7823 SCEV::NoWrapFlags FlagsPresent;
7824
7825 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7826 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7827 return false;
7828
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007829 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007830 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7831 };
7832
7833 APInt C;
7834
7835 switch (Pred) {
7836 default:
7837 break;
7838
7839 case ICmpInst::ICMP_SGE:
7840 std::swap(LHS, RHS);
7841 case ICmpInst::ICMP_SLE:
7842 // X s<= (X + C)<nsw> if C >= 0
7843 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7844 return true;
7845
7846 // (X + C)<nsw> s<= X if C <= 0
7847 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7848 !C.isStrictlyPositive())
7849 return true;
7850 break;
7851
7852 case ICmpInst::ICMP_SGT:
7853 std::swap(LHS, RHS);
7854 case ICmpInst::ICMP_SLT:
7855 // X s< (X + C)<nsw> if C > 0
7856 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7857 C.isStrictlyPositive())
7858 return true;
7859
7860 // (X + C)<nsw> s< X if C < 0
7861 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7862 return true;
7863 break;
7864 }
7865
7866 return false;
7867}
7868
Sanjoy Das7d910f22015-10-02 18:50:30 +00007869bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7870 const SCEV *LHS,
7871 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007872 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007873 return false;
7874
7875 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7876 // the stack can result in exponential time complexity.
7877 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7878
7879 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7880 //
7881 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7882 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7883 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7884 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7885 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007886 return isKnownNonNegative(RHS) &&
7887 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7888 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007889}
7890
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007891bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7892 ICmpInst::Predicate Pred,
7893 const SCEV *LHS, const SCEV *RHS) {
7894 // No need to even try if we know the module has no guards.
7895 if (!HasGuards)
7896 return false;
7897
7898 return any_of(*BB, [&](Instruction &I) {
7899 using namespace llvm::PatternMatch;
7900
7901 Value *Condition;
7902 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7903 m_Value(Condition))) &&
7904 isImpliedCond(Pred, LHS, RHS, Condition, false);
7905 });
7906}
7907
Dan Gohmane65c9172009-07-13 21:35:55 +00007908/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7909/// protected by a conditional between LHS and RHS. This is used to
7910/// to eliminate casts.
7911bool
7912ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7913 ICmpInst::Predicate Pred,
7914 const SCEV *LHS, const SCEV *RHS) {
7915 // Interpret a null as meaning no loop, where there is obviously no guard
7916 // (interprocedural conditions notwithstanding).
7917 if (!L) return true;
7918
Sanjoy Das401e6312016-02-01 20:48:10 +00007919 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7920 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007921
Dan Gohmane65c9172009-07-13 21:35:55 +00007922 BasicBlock *Latch = L->getLoopLatch();
7923 if (!Latch)
7924 return false;
7925
7926 BranchInst *LoopContinuePredicate =
7927 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007928 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7929 isImpliedCond(Pred, LHS, RHS,
7930 LoopContinuePredicate->getCondition(),
7931 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7932 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007933
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007934 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007935 // -- that can lead to O(n!) time complexity.
7936 if (WalkingBEDominatingConds)
7937 return false;
7938
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007939 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007940
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007941 // See if we can exploit a trip count to prove the predicate.
7942 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7943 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7944 if (LatchBECount != getCouldNotCompute()) {
7945 // We know that Latch branches back to the loop header exactly
7946 // LatchBECount times. This means the backdege condition at Latch is
7947 // equivalent to "{0,+,1} u< LatchBECount".
7948 Type *Ty = LatchBECount->getType();
7949 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7950 const SCEV *LoopCounter =
7951 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7952 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7953 LatchBECount))
7954 return true;
7955 }
7956
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007957 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007958 for (auto &AssumeVH : AC.assumptions()) {
7959 if (!AssumeVH)
7960 continue;
7961 auto *CI = cast<CallInst>(AssumeVH);
7962 if (!DT.dominates(CI, Latch->getTerminator()))
7963 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007964
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007965 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7966 return true;
7967 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007968
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007969 // If the loop is not reachable from the entry block, we risk running into an
7970 // infinite loop as we walk up into the dom tree. These loops do not matter
7971 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007972 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007973 return false;
7974
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007975 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7976 return true;
7977
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007978 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7979 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007980
7981 assert(DTN && "should reach the loop header before reaching the root!");
7982
7983 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007984 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7985 return true;
7986
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007987 BasicBlock *PBB = BB->getSinglePredecessor();
7988 if (!PBB)
7989 continue;
7990
7991 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7992 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7993 continue;
7994
7995 Value *Condition = ContinuePredicate->getCondition();
7996
7997 // If we have an edge `E` within the loop body that dominates the only
7998 // latch, the condition guarding `E` also guards the backedge. This
7999 // reasoning works only for loops with a single latch.
8000
8001 BasicBlockEdge DominatingEdge(PBB, BB);
8002 if (DominatingEdge.isSingleEdge()) {
8003 // We're constructively (and conservatively) enumerating edges within the
8004 // loop body that dominate the latch. The dominator tree better agree
8005 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008006 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008007
8008 if (isImpliedCond(Pred, LHS, RHS, Condition,
8009 BB != ContinuePredicate->getSuccessor(0)))
8010 return true;
8011 }
8012 }
8013
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008014 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008015}
8016
Dan Gohmane65c9172009-07-13 21:35:55 +00008017bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008018ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8019 ICmpInst::Predicate Pred,
8020 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008021 // Interpret a null as meaning no loop, where there is obviously no guard
8022 // (interprocedural conditions notwithstanding).
8023 if (!L) return false;
8024
Sanjoy Das401e6312016-02-01 20:48:10 +00008025 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8026 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008027
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008028 // Starting at the loop predecessor, climb up the predecessor chain, as long
8029 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008030 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008031 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008032 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008033 Pair.first;
8034 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008035
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008036 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8037 return true;
8038
Dan Gohman2a62fd92008-08-12 20:17:31 +00008039 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008040 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008041 if (!LoopEntryPredicate ||
8042 LoopEntryPredicate->isUnconditional())
8043 continue;
8044
Dan Gohmane18c2d62010-08-10 23:46:30 +00008045 if (isImpliedCond(Pred, LHS, RHS,
8046 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008047 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008048 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008049 }
8050
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008051 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008052 for (auto &AssumeVH : AC.assumptions()) {
8053 if (!AssumeVH)
8054 continue;
8055 auto *CI = cast<CallInst>(AssumeVH);
8056 if (!DT.dominates(CI, L->getHeader()))
8057 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008058
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008059 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8060 return true;
8061 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008062
Dan Gohman2a62fd92008-08-12 20:17:31 +00008063 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008064}
8065
Dan Gohmane18c2d62010-08-10 23:46:30 +00008066bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008067 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008068 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008069 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008070 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008071 return false;
8072
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008073 auto ClearOnExit =
8074 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8075
Dan Gohman8b0a4192010-03-01 17:49:51 +00008076 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008078 if (BO->getOpcode() == Instruction::And) {
8079 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008080 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8081 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008082 } else if (BO->getOpcode() == Instruction::Or) {
8083 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008084 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8085 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008086 }
8087 }
8088
Dan Gohmane18c2d62010-08-10 23:46:30 +00008089 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008090 if (!ICI) return false;
8091
Andrew Trickfa594032012-11-29 18:35:13 +00008092 // Now that we found a conditional branch that dominates the loop or controls
8093 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008094 ICmpInst::Predicate FoundPred;
8095 if (Inverse)
8096 FoundPred = ICI->getInversePredicate();
8097 else
8098 FoundPred = ICI->getPredicate();
8099
8100 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8101 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008102
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008103 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8104}
8105
8106bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8107 const SCEV *RHS,
8108 ICmpInst::Predicate FoundPred,
8109 const SCEV *FoundLHS,
8110 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008111 // Balance the types.
8112 if (getTypeSizeInBits(LHS->getType()) <
8113 getTypeSizeInBits(FoundLHS->getType())) {
8114 if (CmpInst::isSigned(Pred)) {
8115 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8116 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8117 } else {
8118 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8119 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8120 }
8121 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008122 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008123 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008124 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8125 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8126 } else {
8127 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8128 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8129 }
8130 }
8131
Dan Gohman430f0cc2009-07-21 23:03:19 +00008132 // Canonicalize the query to match the way instcombine will have
8133 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008134 if (SimplifyICmpOperands(Pred, LHS, RHS))
8135 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008136 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008137 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8138 if (FoundLHS == FoundRHS)
8139 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008140
8141 // Check to see if we can make the LHS or RHS match.
8142 if (LHS == FoundRHS || RHS == FoundLHS) {
8143 if (isa<SCEVConstant>(RHS)) {
8144 std::swap(FoundLHS, FoundRHS);
8145 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8146 } else {
8147 std::swap(LHS, RHS);
8148 Pred = ICmpInst::getSwappedPredicate(Pred);
8149 }
8150 }
8151
8152 // Check whether the found predicate is the same as the desired predicate.
8153 if (FoundPred == Pred)
8154 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8155
8156 // Check whether swapping the found predicate makes it the same as the
8157 // desired predicate.
8158 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8159 if (isa<SCEVConstant>(RHS))
8160 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8161 else
8162 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8163 RHS, LHS, FoundLHS, FoundRHS);
8164 }
8165
Sanjoy Das6e78b172015-10-22 19:57:34 +00008166 // Unsigned comparison is the same as signed comparison when both the operands
8167 // are non-negative.
8168 if (CmpInst::isUnsigned(FoundPred) &&
8169 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8170 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8171 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8172
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008173 // Check if we can make progress by sharpening ranges.
8174 if (FoundPred == ICmpInst::ICMP_NE &&
8175 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8176
8177 const SCEVConstant *C = nullptr;
8178 const SCEV *V = nullptr;
8179
8180 if (isa<SCEVConstant>(FoundLHS)) {
8181 C = cast<SCEVConstant>(FoundLHS);
8182 V = FoundRHS;
8183 } else {
8184 C = cast<SCEVConstant>(FoundRHS);
8185 V = FoundLHS;
8186 }
8187
8188 // The guarding predicate tells us that C != V. If the known range
8189 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8190 // range we consider has to correspond to same signedness as the
8191 // predicate we're interested in folding.
8192
8193 APInt Min = ICmpInst::isSigned(Pred) ?
8194 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8195
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008196 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008197 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8198 // This is true even if (Min + 1) wraps around -- in case of
8199 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8200
8201 APInt SharperMin = Min + 1;
8202
8203 switch (Pred) {
8204 case ICmpInst::ICMP_SGE:
8205 case ICmpInst::ICMP_UGE:
8206 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8207 // RHS, we're done.
8208 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8209 getConstant(SharperMin)))
8210 return true;
8211
8212 case ICmpInst::ICMP_SGT:
8213 case ICmpInst::ICMP_UGT:
8214 // We know from the range information that (V `Pred` Min ||
8215 // V == Min). We know from the guarding condition that !(V
8216 // == Min). This gives us
8217 //
8218 // V `Pred` Min || V == Min && !(V == Min)
8219 // => V `Pred` Min
8220 //
8221 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8222
8223 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8224 return true;
8225
8226 default:
8227 // No change
8228 break;
8229 }
8230 }
8231 }
8232
Dan Gohman430f0cc2009-07-21 23:03:19 +00008233 // Check whether the actual condition is beyond sufficient.
8234 if (FoundPred == ICmpInst::ICMP_EQ)
8235 if (ICmpInst::isTrueWhenEqual(Pred))
8236 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8237 return true;
8238 if (Pred == ICmpInst::ICMP_NE)
8239 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8240 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8241 return true;
8242
8243 // Otherwise assume the worst.
8244 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008245}
8246
Sanjoy Das1ed69102015-10-13 02:53:27 +00008247bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8248 const SCEV *&L, const SCEV *&R,
8249 SCEV::NoWrapFlags &Flags) {
8250 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8251 if (!AE || AE->getNumOperands() != 2)
8252 return false;
8253
8254 L = AE->getOperand(0);
8255 R = AE->getOperand(1);
8256 Flags = AE->getNoWrapFlags();
8257 return true;
8258}
8259
Sanjoy Das0b1af852016-07-23 00:28:56 +00008260Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8261 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008262 // We avoid subtracting expressions here because this function is usually
8263 // fairly deep in the call stack (i.e. is called many times).
8264
Sanjoy Das96709c42015-09-25 23:53:45 +00008265 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8266 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8267 const auto *MAR = cast<SCEVAddRecExpr>(More);
8268
8269 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008270 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008271
8272 // We look at affine expressions only; not for correctness but to keep
8273 // getStepRecurrence cheap.
8274 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008275 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008276
Sanjoy Das1ed69102015-10-13 02:53:27 +00008277 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008278 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008279
8280 Less = LAR->getStart();
8281 More = MAR->getStart();
8282
8283 // fall through
8284 }
8285
8286 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008287 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8288 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008289 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008290 }
8291
8292 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008293 SCEV::NoWrapFlags Flags;
8294 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008295 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008296 if (R == More)
8297 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008298
Sanjoy Das1ed69102015-10-13 02:53:27 +00008299 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008300 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008301 if (R == Less)
8302 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008303
Sanjoy Das0b1af852016-07-23 00:28:56 +00008304 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008305}
8306
8307bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8308 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8309 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8310 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8311 return false;
8312
8313 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8314 if (!AddRecLHS)
8315 return false;
8316
8317 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8318 if (!AddRecFoundLHS)
8319 return false;
8320
8321 // We'd like to let SCEV reason about control dependencies, so we constrain
8322 // both the inequalities to be about add recurrences on the same loop. This
8323 // way we can use isLoopEntryGuardedByCond later.
8324
8325 const Loop *L = AddRecFoundLHS->getLoop();
8326 if (L != AddRecLHS->getLoop())
8327 return false;
8328
8329 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8330 //
8331 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8332 // ... (2)
8333 //
8334 // Informal proof for (2), assuming (1) [*]:
8335 //
8336 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8337 //
8338 // Then
8339 //
8340 // FoundLHS s< FoundRHS s< INT_MIN - C
8341 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8342 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8343 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8344 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8345 // <=> FoundLHS + C s< FoundRHS + C
8346 //
8347 // [*]: (1) can be proved by ruling out overflow.
8348 //
8349 // [**]: This can be proved by analyzing all the four possibilities:
8350 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8351 // (A s>= 0, B s>= 0).
8352 //
8353 // Note:
8354 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8355 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8356 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8357 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8358 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8359 // C)".
8360
Sanjoy Das0b1af852016-07-23 00:28:56 +00008361 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8362 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8363 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008364 return false;
8365
Sanjoy Das0b1af852016-07-23 00:28:56 +00008366 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008367 return true;
8368
Sanjoy Das96709c42015-09-25 23:53:45 +00008369 APInt FoundRHSLimit;
8370
8371 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008372 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008373 } else {
8374 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008375 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008376 }
8377
8378 // Try to prove (1) or (2), as needed.
8379 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8380 getConstant(FoundRHSLimit));
8381}
8382
Dan Gohman430f0cc2009-07-21 23:03:19 +00008383bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8384 const SCEV *LHS, const SCEV *RHS,
8385 const SCEV *FoundLHS,
8386 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008387 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8388 return true;
8389
Sanjoy Das96709c42015-09-25 23:53:45 +00008390 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8391 return true;
8392
Dan Gohman430f0cc2009-07-21 23:03:19 +00008393 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8394 FoundLHS, FoundRHS) ||
8395 // ~x < ~y --> x > y
8396 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8397 getNotSCEV(FoundRHS),
8398 getNotSCEV(FoundLHS));
8399}
8400
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008401
8402/// If Expr computes ~A, return A else return nullptr
8403static const SCEV *MatchNotExpr(const SCEV *Expr) {
8404 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008405 if (!Add || Add->getNumOperands() != 2 ||
8406 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008407 return nullptr;
8408
8409 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008410 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8411 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008412 return nullptr;
8413
8414 return AddRHS->getOperand(1);
8415}
8416
8417
8418/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8419template<typename MaxExprType>
8420static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8421 const SCEV *Candidate) {
8422 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8423 if (!MaxExpr) return false;
8424
Sanjoy Das347d2722015-12-01 07:49:27 +00008425 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008426}
8427
8428
8429/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8430template<typename MaxExprType>
8431static bool IsMinConsistingOf(ScalarEvolution &SE,
8432 const SCEV *MaybeMinExpr,
8433 const SCEV *Candidate) {
8434 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8435 if (!MaybeMaxExpr)
8436 return false;
8437
8438 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8439}
8440
Hal Finkela8d205f2015-08-19 01:51:51 +00008441static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8442 ICmpInst::Predicate Pred,
8443 const SCEV *LHS, const SCEV *RHS) {
8444
8445 // If both sides are affine addrecs for the same loop, with equal
8446 // steps, and we know the recurrences don't wrap, then we only
8447 // need to check the predicate on the starting values.
8448
8449 if (!ICmpInst::isRelational(Pred))
8450 return false;
8451
8452 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8453 if (!LAR)
8454 return false;
8455 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8456 if (!RAR)
8457 return false;
8458 if (LAR->getLoop() != RAR->getLoop())
8459 return false;
8460 if (!LAR->isAffine() || !RAR->isAffine())
8461 return false;
8462
8463 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8464 return false;
8465
Hal Finkelff08a2e2015-08-19 17:26:07 +00008466 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8467 SCEV::FlagNSW : SCEV::FlagNUW;
8468 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008469 return false;
8470
8471 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8472}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008473
8474/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8475/// expression?
8476static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8477 ICmpInst::Predicate Pred,
8478 const SCEV *LHS, const SCEV *RHS) {
8479 switch (Pred) {
8480 default:
8481 return false;
8482
8483 case ICmpInst::ICMP_SGE:
8484 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008485 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008486 case ICmpInst::ICMP_SLE:
8487 return
8488 // min(A, ...) <= A
8489 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8490 // A <= max(A, ...)
8491 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8492
8493 case ICmpInst::ICMP_UGE:
8494 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008495 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008496 case ICmpInst::ICMP_ULE:
8497 return
8498 // min(A, ...) <= A
8499 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8500 // A <= max(A, ...)
8501 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8502 }
8503
8504 llvm_unreachable("covered switch fell through?!");
8505}
8506
Dan Gohmane65c9172009-07-13 21:35:55 +00008507bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008508ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8509 const SCEV *LHS, const SCEV *RHS,
8510 const SCEV *FoundLHS,
8511 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008512 auto IsKnownPredicateFull =
8513 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008514 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008515 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008516 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8517 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008518 };
8519
Dan Gohmane65c9172009-07-13 21:35:55 +00008520 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008521 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8522 case ICmpInst::ICMP_EQ:
8523 case ICmpInst::ICMP_NE:
8524 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8525 return true;
8526 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008527 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008528 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008529 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8530 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008531 return true;
8532 break;
8533 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008534 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008535 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8536 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008537 return true;
8538 break;
8539 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008540 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008541 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8542 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008543 return true;
8544 break;
8545 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008546 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008547 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8548 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008549 return true;
8550 break;
8551 }
8552
8553 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008554}
8555
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008556bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8557 const SCEV *LHS,
8558 const SCEV *RHS,
8559 const SCEV *FoundLHS,
8560 const SCEV *FoundRHS) {
8561 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8562 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8563 // reduce the compile time impact of this optimization.
8564 return false;
8565
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008566 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008567 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008568 return false;
8569
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008570 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008571
8572 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8573 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8574 ConstantRange FoundLHSRange =
8575 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8576
Sanjoy Das095f5b22016-07-22 20:47:55 +00008577 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8578 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008579
8580 // We can also compute the range of values for `LHS` that satisfy the
8581 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008582 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008583 ConstantRange SatisfyingLHSRange =
8584 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8585
8586 // The antecedent implies the consequent if every value of `LHS` that
8587 // satisfies the antecedent also satisfies the consequent.
8588 return SatisfyingLHSRange.contains(LHSRange);
8589}
8590
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008591bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8592 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008593 assert(isKnownPositive(Stride) && "Positive stride expected!");
8594
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008595 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008596
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008597 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008598 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008599
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008600 if (IsSigned) {
8601 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8602 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8603 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8604 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008605
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008606 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8607 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008608 }
Dan Gohman01048422009-06-21 23:46:38 +00008609
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008610 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8611 APInt MaxValue = APInt::getMaxValue(BitWidth);
8612 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8613 .getUnsignedMax();
8614
8615 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8616 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8617}
8618
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008619bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8620 bool IsSigned, bool NoWrap) {
8621 if (NoWrap) return false;
8622
8623 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008624 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008625
8626 if (IsSigned) {
8627 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8628 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8629 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8630 .getSignedMax();
8631
8632 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8633 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8634 }
8635
8636 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8637 APInt MinValue = APInt::getMinValue(BitWidth);
8638 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8639 .getUnsignedMax();
8640
8641 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8642 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8643}
8644
Johannes Doerfert2683e562015-02-09 12:34:23 +00008645const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008646 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008647 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008648 Delta = Equality ? getAddExpr(Delta, Step)
8649 : getAddExpr(Delta, getMinusSCEV(Step, One));
8650 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008651}
8652
Andrew Trick3ca3f982011-07-26 17:19:55 +00008653ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008654ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008655 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008656 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008657 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008658 // We handle only IV < Invariant
8659 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008660 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008661
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008662 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008663 bool PredicatedIV = false;
8664
8665 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008666 // Try to make this an AddRec using runtime tests, in the first X
8667 // iterations of this loop, where X is the SCEV expression found by the
8668 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008669 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008670 PredicatedIV = true;
8671 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008672
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008673 // Avoid weird loops
8674 if (!IV || IV->getLoop() != L || !IV->isAffine())
8675 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008676
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008677 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008678 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008679
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008680 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008681
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008682 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008683
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008684 // Avoid negative or zero stride values.
8685 if (!PositiveStride) {
8686 // We can compute the correct backedge taken count for loops with unknown
8687 // strides if we can prove that the loop is not an infinite loop with side
8688 // effects. Here's the loop structure we are trying to handle -
8689 //
8690 // i = start
8691 // do {
8692 // A[i] = i;
8693 // i += s;
8694 // } while (i < end);
8695 //
8696 // The backedge taken count for such loops is evaluated as -
8697 // (max(end, start + stride) - start - 1) /u stride
8698 //
8699 // The additional preconditions that we need to check to prove correctness
8700 // of the above formula is as follows -
8701 //
8702 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8703 // NoWrap flag).
8704 // b) loop is single exit with no side effects.
8705 //
8706 //
8707 // Precondition a) implies that if the stride is negative, this is a single
8708 // trip loop. The backedge taken count formula reduces to zero in this case.
8709 //
8710 // Precondition b) implies that the unknown stride cannot be zero otherwise
8711 // we have UB.
8712 //
8713 // The positive stride case is the same as isKnownPositive(Stride) returning
8714 // true (original behavior of the function).
8715 //
8716 // We want to make sure that the stride is truly unknown as there are edge
8717 // cases where ScalarEvolution propagates no wrap flags to the
8718 // post-increment/decrement IV even though the increment/decrement operation
8719 // itself is wrapping. The computed backedge taken count may be wrong in
8720 // such cases. This is prevented by checking that the stride is not known to
8721 // be either positive or non-positive. For example, no wrap flags are
8722 // propagated to the post-increment IV of this loop with a trip count of 2 -
8723 //
8724 // unsigned char i;
8725 // for(i=127; i<128; i+=129)
8726 // A[i] = i;
8727 //
8728 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8729 !loopHasNoSideEffects(L))
8730 return getCouldNotCompute();
8731
8732 } else if (!Stride->isOne() &&
8733 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8734 // Avoid proven overflow cases: this will ensure that the backedge taken
8735 // count will not generate any unsigned overflow. Relaxed no-overflow
8736 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8737 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008738 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008739
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008740 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8741 : ICmpInst::ICMP_ULT;
8742 const SCEV *Start = IV->getStart();
8743 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00008744 // If the backedge is taken at least once, then it will be taken
8745 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8746 // is the LHS value of the less-than comparison the first time it is evaluated
8747 // and End is the RHS.
8748 const SCEV *BECountIfBackedgeTaken =
8749 computeBECount(getMinusSCEV(End, Start), Stride, false);
8750 // If the loop entry is guarded by the result of the backedge test of the
8751 // first loop iteration, then we know the backedge will be taken at least
8752 // once and so the backedge taken count is as above. If not then we use the
8753 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8754 // as if the backedge is taken at least once max(End,Start) is End and so the
8755 // result is as above, and if not max(End,Start) is Start so we get a backedge
8756 // count of zero.
8757 const SCEV *BECount;
8758 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8759 BECount = BECountIfBackedgeTaken;
8760 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008761 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00008762 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8763 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008764
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008765 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00008766 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008767 if (isa<SCEVConstant>(BECount))
8768 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00008769 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00008770 // If we know exactly how many times the backedge will be taken if it's
8771 // taken at least once, then the backedge count will either be that or
8772 // zero.
8773 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00008774 MaxOrZero = true;
8775 } else {
John Brawnecf79302016-10-18 10:10:53 +00008776 // Calculate the maximum backedge count based on the range of values
8777 // permitted by Start, End, and Stride.
8778 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8779 : getUnsignedRange(Start).getUnsignedMin();
8780
8781 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8782
8783 APInt StrideForMaxBECount;
8784
8785 if (PositiveStride)
8786 StrideForMaxBECount =
8787 IsSigned ? getSignedRange(Stride).getSignedMin()
8788 : getUnsignedRange(Stride).getUnsignedMin();
8789 else
8790 // Using a stride of 1 is safe when computing max backedge taken count for
8791 // a loop with unknown stride.
8792 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8793
8794 APInt Limit =
8795 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8796 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8797
8798 // Although End can be a MAX expression we estimate MaxEnd considering only
8799 // the case End = RHS. This is safe because in the other case (End - Start)
8800 // is zero, leading to a zero maximum backedge taken count.
8801 APInt MaxEnd =
8802 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8803 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8804
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008805 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008806 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00008807 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008808
8809 if (isa<SCEVCouldNotCompute>(MaxBECount))
8810 MaxBECount = BECount;
8811
John Brawn84b21832016-10-21 11:08:48 +00008812 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008813}
8814
8815ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008816ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008817 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008818 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008819 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008820 // We handle only IV > Invariant
8821 if (!isLoopInvariant(RHS, L))
8822 return getCouldNotCompute();
8823
8824 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008825 if (!IV && AllowPredicates)
8826 // Try to make this an AddRec using runtime tests, in the first X
8827 // iterations of this loop, where X is the SCEV expression found by the
8828 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008829 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008830
8831 // Avoid weird loops
8832 if (!IV || IV->getLoop() != L || !IV->isAffine())
8833 return getCouldNotCompute();
8834
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008835 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008836 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8837
8838 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8839
8840 // Avoid negative or zero stride values
8841 if (!isKnownPositive(Stride))
8842 return getCouldNotCompute();
8843
8844 // Avoid proven overflow cases: this will ensure that the backedge taken count
8845 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008846 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008847 // behaviors like the case of C language.
8848 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8849 return getCouldNotCompute();
8850
8851 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8852 : ICmpInst::ICMP_UGT;
8853
8854 const SCEV *Start = IV->getStart();
8855 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008856 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8857 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008858
8859 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8860
8861 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8862 : getUnsignedRange(Start).getUnsignedMax();
8863
8864 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8865 : getUnsignedRange(Stride).getUnsignedMin();
8866
8867 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8868 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8869 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8870
8871 // Although End can be a MIN expression we estimate MinEnd considering only
8872 // the case End = RHS. This is safe because in the other case (Start - End)
8873 // is zero, leading to a zero maximum backedge taken count.
8874 APInt MinEnd =
8875 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8876 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8877
8878
8879 const SCEV *MaxBECount = getCouldNotCompute();
8880 if (isa<SCEVConstant>(BECount))
8881 MaxBECount = BECount;
8882 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008883 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008884 getConstant(MinStride), false);
8885
8886 if (isa<SCEVCouldNotCompute>(MaxBECount))
8887 MaxBECount = BECount;
8888
John Brawn84b21832016-10-21 11:08:48 +00008889 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00008890}
8891
Benjamin Kramerc321e532016-06-08 19:09:22 +00008892const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008893 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008894 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008895 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008896
8897 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008898 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008899 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008900 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008901 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008902 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008903 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008904 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008905 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008906 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008907 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008908 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008909 }
8910
8911 // The only time we can solve this is when we have all constant indices.
8912 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008913 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008914 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008915
8916 // Okay at this point we know that all elements of the chrec are constants and
8917 // that the start element is zero.
8918
8919 // First check to see if the range contains zero. If not, the first
8920 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008921 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008922 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008923 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008924
Chris Lattnerd934c702004-04-02 20:23:17 +00008925 if (isAffine()) {
8926 // If this is an affine expression then we have this situation:
8927 // Solve {0,+,A} in Range === Ax in Range
8928
Nick Lewycky52460262007-07-16 02:08:00 +00008929 // We know that zero is in the range. If A is positive then we know that
8930 // the upper value of the range must be the first possible exit value.
8931 // If A is negative then the lower of the range is the last possible loop
8932 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008933 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008934 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008935 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008936
Nick Lewycky52460262007-07-16 02:08:00 +00008937 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008938 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008939 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008940
8941 // Evaluate at the exit value. If we really did fall out of the valid
8942 // range, then we computed our trip count, otherwise wrap around or other
8943 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008944 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008945 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008946 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008947
8948 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008949 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008950 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008951 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008952 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008953 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008954 } else if (isQuadratic()) {
8955 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8956 // quadratic equation to solve it. To do this, we must frame our problem in
8957 // terms of figuring out when zero is crossed, instead of when
8958 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008959 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008960 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00008961 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008962
8963 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008964 if (auto Roots =
8965 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008966 const SCEVConstant *R1 = Roots->first;
8967 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008968 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008969 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8970 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008971 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008972 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008973
Chris Lattnerd934c702004-04-02 20:23:17 +00008974 // Make sure the root is not off by one. The returned iteration should
8975 // not be in the range, but the previous one should be. When solving
8976 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00008977 ConstantInt *R1Val =
8978 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008979 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008980 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008981 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008982 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008983
Dan Gohmana37eaf22007-10-22 18:31:58 +00008984 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008985 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008986 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00008987 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008988 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008989
Chris Lattnerd934c702004-04-02 20:23:17 +00008990 // If R1 was not in the range, then it is a good return value. Make
8991 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008992 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008993 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008994 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008995 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008996 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00008997 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008998 }
8999 }
9000 }
9001
Dan Gohman31efa302009-04-18 17:58:19 +00009002 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009003}
9004
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009005// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009006static inline bool containsUndefs(const SCEV *S) {
9007 return SCEVExprContains(S, [](const SCEV *S) {
9008 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9009 return isa<UndefValue>(SU->getValue());
9010 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9011 return isa<UndefValue>(SC->getValue());
9012 return false;
9013 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009014}
9015
9016namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009017// Collect all steps of SCEV expressions.
9018struct SCEVCollectStrides {
9019 ScalarEvolution &SE;
9020 SmallVectorImpl<const SCEV *> &Strides;
9021
9022 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9023 : SE(SE), Strides(S) {}
9024
9025 bool follow(const SCEV *S) {
9026 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9027 Strides.push_back(AR->getStepRecurrence(SE));
9028 return true;
9029 }
9030 bool isDone() const { return false; }
9031};
9032
9033// Collect all SCEVUnknown and SCEVMulExpr expressions.
9034struct SCEVCollectTerms {
9035 SmallVectorImpl<const SCEV *> &Terms;
9036
9037 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9038 : Terms(T) {}
9039
9040 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009041 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9042 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009043 if (!containsUndefs(S))
9044 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009045
9046 // Stop recursion: once we collected a term, do not walk its operands.
9047 return false;
9048 }
9049
9050 // Keep looking.
9051 return true;
9052 }
9053 bool isDone() const { return false; }
9054};
Tobias Grosser374bce02015-10-12 08:02:00 +00009055
9056// Check if a SCEV contains an AddRecExpr.
9057struct SCEVHasAddRec {
9058 bool &ContainsAddRec;
9059
9060 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9061 ContainsAddRec = false;
9062 }
9063
9064 bool follow(const SCEV *S) {
9065 if (isa<SCEVAddRecExpr>(S)) {
9066 ContainsAddRec = true;
9067
9068 // Stop recursion: once we collected a term, do not walk its operands.
9069 return false;
9070 }
9071
9072 // Keep looking.
9073 return true;
9074 }
9075 bool isDone() const { return false; }
9076};
9077
9078// Find factors that are multiplied with an expression that (possibly as a
9079// subexpression) contains an AddRecExpr. In the expression:
9080//
9081// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9082//
9083// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9084// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9085// parameters as they form a product with an induction variable.
9086//
9087// This collector expects all array size parameters to be in the same MulExpr.
9088// It might be necessary to later add support for collecting parameters that are
9089// spread over different nested MulExpr.
9090struct SCEVCollectAddRecMultiplies {
9091 SmallVectorImpl<const SCEV *> &Terms;
9092 ScalarEvolution &SE;
9093
9094 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9095 : Terms(T), SE(SE) {}
9096
9097 bool follow(const SCEV *S) {
9098 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9099 bool HasAddRec = false;
9100 SmallVector<const SCEV *, 0> Operands;
9101 for (auto Op : Mul->operands()) {
9102 if (isa<SCEVUnknown>(Op)) {
9103 Operands.push_back(Op);
9104 } else {
9105 bool ContainsAddRec;
9106 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9107 visitAll(Op, ContiansAddRec);
9108 HasAddRec |= ContainsAddRec;
9109 }
9110 }
9111 if (Operands.size() == 0)
9112 return true;
9113
9114 if (!HasAddRec)
9115 return false;
9116
9117 Terms.push_back(SE.getMulExpr(Operands));
9118 // Stop recursion: once we collected a term, do not walk its operands.
9119 return false;
9120 }
9121
9122 // Keep looking.
9123 return true;
9124 }
9125 bool isDone() const { return false; }
9126};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009127}
Sebastian Pop448712b2014-05-07 18:01:20 +00009128
Tobias Grosser374bce02015-10-12 08:02:00 +00009129/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9130/// two places:
9131/// 1) The strides of AddRec expressions.
9132/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009133void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9134 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009135 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009136 SCEVCollectStrides StrideCollector(*this, Strides);
9137 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009138
9139 DEBUG({
9140 dbgs() << "Strides:\n";
9141 for (const SCEV *S : Strides)
9142 dbgs() << *S << "\n";
9143 });
9144
9145 for (const SCEV *S : Strides) {
9146 SCEVCollectTerms TermCollector(Terms);
9147 visitAll(S, TermCollector);
9148 }
9149
9150 DEBUG({
9151 dbgs() << "Terms:\n";
9152 for (const SCEV *T : Terms)
9153 dbgs() << *T << "\n";
9154 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009155
9156 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9157 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009158}
9159
Sebastian Popb1a548f2014-05-12 19:01:53 +00009160static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009161 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009162 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009163 int Last = Terms.size() - 1;
9164 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009165
Sebastian Pop448712b2014-05-07 18:01:20 +00009166 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009167 if (Last == 0) {
9168 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009169 SmallVector<const SCEV *, 2> Qs;
9170 for (const SCEV *Op : M->operands())
9171 if (!isa<SCEVConstant>(Op))
9172 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009173
Sebastian Pope30bd352014-05-27 22:41:56 +00009174 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009175 }
9176
Sebastian Pope30bd352014-05-27 22:41:56 +00009177 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009178 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009179 }
9180
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009181 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009182 // Normalize the terms before the next call to findArrayDimensionsRec.
9183 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009184 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009185
9186 // Bail out when GCD does not evenly divide one of the terms.
9187 if (!R->isZero())
9188 return false;
9189
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009190 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009191 }
9192
Tobias Grosser3080cf12014-05-08 07:55:34 +00009193 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009194 Terms.erase(
9195 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9196 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009197
Sebastian Pop448712b2014-05-07 18:01:20 +00009198 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009199 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9200 return false;
9201
Sebastian Pope30bd352014-05-27 22:41:56 +00009202 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009203 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009204}
Sebastian Popc62c6792013-11-12 22:47:20 +00009205
Sebastian Pop448712b2014-05-07 18:01:20 +00009206
9207// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009208static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009209 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009210 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009211 return true;
9212 return false;
9213}
9214
9215// Return the number of product terms in S.
9216static inline int numberOfTerms(const SCEV *S) {
9217 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9218 return Expr->getNumOperands();
9219 return 1;
9220}
9221
Sebastian Popa6e58602014-05-27 22:41:45 +00009222static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9223 if (isa<SCEVConstant>(T))
9224 return nullptr;
9225
9226 if (isa<SCEVUnknown>(T))
9227 return T;
9228
9229 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9230 SmallVector<const SCEV *, 2> Factors;
9231 for (const SCEV *Op : M->operands())
9232 if (!isa<SCEVConstant>(Op))
9233 Factors.push_back(Op);
9234
9235 return SE.getMulExpr(Factors);
9236 }
9237
9238 return T;
9239}
9240
9241/// Return the size of an element read or written by Inst.
9242const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9243 Type *Ty;
9244 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9245 Ty = Store->getValueOperand()->getType();
9246 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009247 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009248 else
9249 return nullptr;
9250
9251 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9252 return getSizeOfExpr(ETy, Ty);
9253}
9254
Sebastian Popa6e58602014-05-27 22:41:45 +00009255void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9256 SmallVectorImpl<const SCEV *> &Sizes,
9257 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009258 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009259 return;
9260
9261 // Early return when Terms do not contain parameters: we do not delinearize
9262 // non parametric SCEVs.
9263 if (!containsParameters(Terms))
9264 return;
9265
9266 DEBUG({
9267 dbgs() << "Terms:\n";
9268 for (const SCEV *T : Terms)
9269 dbgs() << *T << "\n";
9270 });
9271
9272 // Remove duplicates.
9273 std::sort(Terms.begin(), Terms.end());
9274 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9275
9276 // Put larger terms first.
9277 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9278 return numberOfTerms(LHS) > numberOfTerms(RHS);
9279 });
9280
Sebastian Popa6e58602014-05-27 22:41:45 +00009281 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9282
Tobias Grosser374bce02015-10-12 08:02:00 +00009283 // Try to divide all terms by the element size. If term is not divisible by
9284 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009285 for (const SCEV *&Term : Terms) {
9286 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009287 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009288 if (!Q->isZero())
9289 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009290 }
9291
9292 SmallVector<const SCEV *, 4> NewTerms;
9293
9294 // Remove constant factors.
9295 for (const SCEV *T : Terms)
9296 if (const SCEV *NewT = removeConstantFactors(SE, T))
9297 NewTerms.push_back(NewT);
9298
Sebastian Pop448712b2014-05-07 18:01:20 +00009299 DEBUG({
9300 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009301 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009302 dbgs() << *T << "\n";
9303 });
9304
Sebastian Popa6e58602014-05-27 22:41:45 +00009305 if (NewTerms.empty() ||
9306 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009307 Sizes.clear();
9308 return;
9309 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009310
Sebastian Popa6e58602014-05-27 22:41:45 +00009311 // The last element to be pushed into Sizes is the size of an element.
9312 Sizes.push_back(ElementSize);
9313
Sebastian Pop448712b2014-05-07 18:01:20 +00009314 DEBUG({
9315 dbgs() << "Sizes:\n";
9316 for (const SCEV *S : Sizes)
9317 dbgs() << *S << "\n";
9318 });
9319}
9320
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009321void ScalarEvolution::computeAccessFunctions(
9322 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9323 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009324
Sebastian Popb1a548f2014-05-12 19:01:53 +00009325 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009326 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009327 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009328
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009329 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009330 if (!AR->isAffine())
9331 return;
9332
9333 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009334 int Last = Sizes.size() - 1;
9335 for (int i = Last; i >= 0; i--) {
9336 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009337 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009338
9339 DEBUG({
9340 dbgs() << "Res: " << *Res << "\n";
9341 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9342 dbgs() << "Res divided by Sizes[i]:\n";
9343 dbgs() << "Quotient: " << *Q << "\n";
9344 dbgs() << "Remainder: " << *R << "\n";
9345 });
9346
9347 Res = Q;
9348
Sebastian Popa6e58602014-05-27 22:41:45 +00009349 // Do not record the last subscript corresponding to the size of elements in
9350 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009351 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009352
9353 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009354 if (isa<SCEVAddRecExpr>(R)) {
9355 Subscripts.clear();
9356 Sizes.clear();
9357 return;
9358 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009359
Sebastian Pop448712b2014-05-07 18:01:20 +00009360 continue;
9361 }
9362
9363 // Record the access function for the current subscript.
9364 Subscripts.push_back(R);
9365 }
9366
9367 // Also push in last position the remainder of the last division: it will be
9368 // the access function of the innermost dimension.
9369 Subscripts.push_back(Res);
9370
9371 std::reverse(Subscripts.begin(), Subscripts.end());
9372
9373 DEBUG({
9374 dbgs() << "Subscripts:\n";
9375 for (const SCEV *S : Subscripts)
9376 dbgs() << *S << "\n";
9377 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009378}
9379
Sebastian Popc62c6792013-11-12 22:47:20 +00009380/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9381/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009382/// is the offset start of the array. The SCEV->delinearize algorithm computes
9383/// the multiples of SCEV coefficients: that is a pattern matching of sub
9384/// expressions in the stride and base of a SCEV corresponding to the
9385/// computation of a GCD (greatest common divisor) of base and stride. When
9386/// SCEV->delinearize fails, it returns the SCEV unchanged.
9387///
9388/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9389///
9390/// void foo(long n, long m, long o, double A[n][m][o]) {
9391///
9392/// for (long i = 0; i < n; i++)
9393/// for (long j = 0; j < m; j++)
9394/// for (long k = 0; k < o; k++)
9395/// A[i][j][k] = 1.0;
9396/// }
9397///
9398/// the delinearization input is the following AddRec SCEV:
9399///
9400/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9401///
9402/// From this SCEV, we are able to say that the base offset of the access is %A
9403/// because it appears as an offset that does not divide any of the strides in
9404/// the loops:
9405///
9406/// CHECK: Base offset: %A
9407///
9408/// and then SCEV->delinearize determines the size of some of the dimensions of
9409/// the array as these are the multiples by which the strides are happening:
9410///
9411/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9412///
9413/// Note that the outermost dimension remains of UnknownSize because there are
9414/// no strides that would help identifying the size of the last dimension: when
9415/// the array has been statically allocated, one could compute the size of that
9416/// dimension by dividing the overall size of the array by the size of the known
9417/// dimensions: %m * %o * 8.
9418///
9419/// Finally delinearize provides the access functions for the array reference
9420/// that does correspond to A[i][j][k] of the above C testcase:
9421///
9422/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9423///
9424/// The testcases are checking the output of a function pass:
9425/// DelinearizationPass that walks through all loads and stores of a function
9426/// asking for the SCEV of the memory access with respect to all enclosing
9427/// loops, calling SCEV->delinearize on that and printing the results.
9428
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009429void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009430 SmallVectorImpl<const SCEV *> &Subscripts,
9431 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009432 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009433 // First step: collect parametric terms.
9434 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009435 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009436
Sebastian Popb1a548f2014-05-12 19:01:53 +00009437 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009438 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009439
Sebastian Pop448712b2014-05-07 18:01:20 +00009440 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009441 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009442
Sebastian Popb1a548f2014-05-12 19:01:53 +00009443 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009444 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009445
Sebastian Pop448712b2014-05-07 18:01:20 +00009446 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009447 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009448
Sebastian Pop28e6b972014-05-27 22:41:51 +00009449 if (Subscripts.empty())
9450 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009451
Sebastian Pop448712b2014-05-07 18:01:20 +00009452 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009453 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009454 dbgs() << "ArrayDecl[UnknownSize]";
9455 for (const SCEV *S : Sizes)
9456 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009457
Sebastian Pop444621a2014-05-09 22:45:02 +00009458 dbgs() << "\nArrayRef";
9459 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009460 dbgs() << "[" << *S << "]";
9461 dbgs() << "\n";
9462 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009463}
Chris Lattnerd934c702004-04-02 20:23:17 +00009464
9465//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009466// SCEVCallbackVH Class Implementation
9467//===----------------------------------------------------------------------===//
9468
Dan Gohmand33a0902009-05-19 19:22:47 +00009469void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009470 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009471 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9472 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009473 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009474 // this now dangles!
9475}
9476
Dan Gohman7a066722010-07-28 01:09:07 +00009477void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009478 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009479
Dan Gohman48f82222009-05-04 22:30:44 +00009480 // Forget all the expressions associated with users of the old value,
9481 // so that future queries will recompute the expressions using the new
9482 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009483 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009484 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009485 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009486 while (!Worklist.empty()) {
9487 User *U = Worklist.pop_back_val();
9488 // Deleting the Old value will cause this to dangle. Postpone
9489 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009490 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009491 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009492 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009493 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009494 if (PHINode *PN = dyn_cast<PHINode>(U))
9495 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009496 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009497 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009498 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009499 // Delete the Old value.
9500 if (PHINode *PN = dyn_cast<PHINode>(Old))
9501 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009502 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009503 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009504}
9505
Dan Gohmand33a0902009-05-19 19:22:47 +00009506ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009507 : CallbackVH(V), SE(se) {}
9508
9509//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009510// ScalarEvolution Class Implementation
9511//===----------------------------------------------------------------------===//
9512
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009513ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009514 AssumptionCache &AC, DominatorTree &DT,
9515 LoopInfo &LI)
9516 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009517 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009518 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9519 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009520 FirstUnknown(nullptr) {
9521
9522 // To use guards for proving predicates, we need to scan every instruction in
9523 // relevant basic blocks, and not just terminators. Doing this is a waste of
9524 // time if the IR does not actually contain any calls to
9525 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9526 //
9527 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9528 // to _add_ guards to the module when there weren't any before, and wants
9529 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9530 // efficient in lieu of being smart in that rather obscure case.
9531
9532 auto *GuardDecl = F.getParent()->getFunction(
9533 Intrinsic::getName(Intrinsic::experimental_guard));
9534 HasGuards = GuardDecl && !GuardDecl->use_empty();
9535}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009536
9537ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009538 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009539 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009540 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009541 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009542 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009543 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009544 PredicatedBackedgeTakenCounts(
9545 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009546 ConstantEvolutionLoopExitValue(
9547 std::move(Arg.ConstantEvolutionLoopExitValue)),
9548 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9549 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009550 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009551 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009552 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9553 SignedRanges(std::move(Arg.SignedRanges)),
9554 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009555 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009556 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9557 FirstUnknown(Arg.FirstUnknown) {
9558 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009559}
9560
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009561ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009562 // Iterate through all the SCEVUnknown instances and call their
9563 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009564 for (SCEVUnknown *U = FirstUnknown; U;) {
9565 SCEVUnknown *Tmp = U;
9566 U = U->Next;
9567 Tmp->~SCEVUnknown();
9568 }
Craig Topper9f008862014-04-15 04:59:12 +00009569 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009570
Wei Mia49559b2016-02-04 01:27:38 +00009571 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009572 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009573 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009574
9575 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9576 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009577 for (auto &BTCI : BackedgeTakenCounts)
9578 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009579 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9580 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009581
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009582 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009583 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009584 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009585}
9586
Dan Gohmanc8e23622009-04-21 23:15:49 +00009587bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009588 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009589}
9590
Dan Gohmanc8e23622009-04-21 23:15:49 +00009591static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009592 const Loop *L) {
9593 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009594 for (Loop *I : *L)
9595 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009596
Dan Gohmanbc694912010-01-09 18:17:45 +00009597 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009598 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009599 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009600
Dan Gohmancb0efec2009-12-18 01:14:11 +00009601 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009602 L->getExitBlocks(ExitBlocks);
9603 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009604 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009605
Dan Gohman0bddac12009-02-24 18:55:53 +00009606 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9607 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009608 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009609 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009610 }
9611
Dan Gohmanbc694912010-01-09 18:17:45 +00009612 OS << "\n"
9613 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009614 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009615 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009616
9617 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9618 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009619 if (SE->isBackedgeTakenCountMaxOrZero(L))
9620 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009621 } else {
9622 OS << "Unpredictable max backedge-taken count. ";
9623 }
9624
Silviu Baranga6f444df2016-04-08 14:29:09 +00009625 OS << "\n"
9626 "Loop ";
9627 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9628 OS << ": ";
9629
9630 SCEVUnionPredicate Pred;
9631 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9632 if (!isa<SCEVCouldNotCompute>(PBT)) {
9633 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9634 OS << " Predicates:\n";
9635 Pred.print(OS, 4);
9636 } else {
9637 OS << "Unpredictable predicated backedge-taken count. ";
9638 }
Dan Gohman69942932009-06-24 00:33:16 +00009639 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009640}
9641
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009642static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9643 switch (LD) {
9644 case ScalarEvolution::LoopVariant:
9645 return "Variant";
9646 case ScalarEvolution::LoopInvariant:
9647 return "Invariant";
9648 case ScalarEvolution::LoopComputable:
9649 return "Computable";
9650 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009651 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009652}
9653
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009654void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009655 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009656 // out SCEV values of all instructions that are interesting. Doing
9657 // this potentially causes it to create new SCEV objects though,
9658 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009659 // observable from outside the class though, so casting away the
9660 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009661 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009662
Dan Gohmanbc694912010-01-09 18:17:45 +00009663 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009664 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009665 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009666 for (Instruction &I : instructions(F))
9667 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9668 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009669 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009670 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009671 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009672 if (!isa<SCEVCouldNotCompute>(SV)) {
9673 OS << " U: ";
9674 SE.getUnsignedRange(SV).print(OS);
9675 OS << " S: ";
9676 SE.getSignedRange(SV).print(OS);
9677 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009678
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009679 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009680
Dan Gohmanaf752342009-07-07 17:06:11 +00009681 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009682 if (AtUse != SV) {
9683 OS << " --> ";
9684 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009685 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9686 OS << " U: ";
9687 SE.getUnsignedRange(AtUse).print(OS);
9688 OS << " S: ";
9689 SE.getSignedRange(AtUse).print(OS);
9690 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009691 }
9692
9693 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009694 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009695 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009696 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009697 OS << "<<Unknown>>";
9698 } else {
9699 OS << *ExitValue;
9700 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009701
9702 bool First = true;
9703 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9704 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009705 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009706 First = false;
9707 } else {
9708 OS << ", ";
9709 }
9710
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009711 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9712 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009713 }
9714
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009715 for (auto *InnerL : depth_first(L)) {
9716 if (InnerL == L)
9717 continue;
9718 if (First) {
9719 OS << "\t\t" "LoopDispositions: { ";
9720 First = false;
9721 } else {
9722 OS << ", ";
9723 }
9724
9725 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9726 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9727 }
9728
9729 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009730 }
9731
Chris Lattnerd934c702004-04-02 20:23:17 +00009732 OS << "\n";
9733 }
9734
Dan Gohmanbc694912010-01-09 18:17:45 +00009735 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009736 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009737 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009738 for (Loop *I : LI)
9739 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009740}
Dan Gohmane20f8242009-04-21 00:47:46 +00009741
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009742ScalarEvolution::LoopDisposition
9743ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009744 auto &Values = LoopDispositions[S];
9745 for (auto &V : Values) {
9746 if (V.getPointer() == L)
9747 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009748 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009749 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009750 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009751 auto &Values2 = LoopDispositions[S];
9752 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9753 if (V.getPointer() == L) {
9754 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009755 break;
9756 }
9757 }
9758 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009759}
9760
9761ScalarEvolution::LoopDisposition
9762ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009763 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009764 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009765 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009766 case scTruncate:
9767 case scZeroExtend:
9768 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009769 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009770 case scAddRecExpr: {
9771 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9772
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009773 // If L is the addrec's loop, it's computable.
9774 if (AR->getLoop() == L)
9775 return LoopComputable;
9776
Dan Gohmanafd6db92010-11-17 21:23:15 +00009777 // Add recurrences are never invariant in the function-body (null loop).
9778 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009779 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009780
9781 // This recurrence is variant w.r.t. L if L contains AR's loop.
9782 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009783 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009784
9785 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9786 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009787 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009788
9789 // This recurrence is variant w.r.t. L if any of its operands
9790 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009791 for (auto *Op : AR->operands())
9792 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009793 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009794
9795 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009796 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009797 }
9798 case scAddExpr:
9799 case scMulExpr:
9800 case scUMaxExpr:
9801 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009802 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009803 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9804 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009805 if (D == LoopVariant)
9806 return LoopVariant;
9807 if (D == LoopComputable)
9808 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009809 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009810 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009811 }
9812 case scUDivExpr: {
9813 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009814 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9815 if (LD == LoopVariant)
9816 return LoopVariant;
9817 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9818 if (RD == LoopVariant)
9819 return LoopVariant;
9820 return (LD == LoopInvariant && RD == LoopInvariant) ?
9821 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009822 }
9823 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009824 // All non-instruction values are loop invariant. All instructions are loop
9825 // invariant if they are not contained in the specified loop.
9826 // Instructions are never considered invariant in the function body
9827 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009828 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009829 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9830 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009831 case scCouldNotCompute:
9832 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009833 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009834 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009835}
9836
9837bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9838 return getLoopDisposition(S, L) == LoopInvariant;
9839}
9840
9841bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9842 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009843}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009844
Dan Gohman8ea83d82010-11-18 00:34:22 +00009845ScalarEvolution::BlockDisposition
9846ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009847 auto &Values = BlockDispositions[S];
9848 for (auto &V : Values) {
9849 if (V.getPointer() == BB)
9850 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009851 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009852 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009853 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009854 auto &Values2 = BlockDispositions[S];
9855 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9856 if (V.getPointer() == BB) {
9857 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009858 break;
9859 }
9860 }
9861 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009862}
9863
Dan Gohman8ea83d82010-11-18 00:34:22 +00009864ScalarEvolution::BlockDisposition
9865ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009866 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009867 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009868 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009869 case scTruncate:
9870 case scZeroExtend:
9871 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009872 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009873 case scAddRecExpr: {
9874 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009875 // to test for proper dominance too, because the instruction which
9876 // produces the addrec's value is a PHI, and a PHI effectively properly
9877 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009878 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009879 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009880 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009881
9882 // Fall through into SCEVNAryExpr handling.
9883 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009884 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009885 case scAddExpr:
9886 case scMulExpr:
9887 case scUMaxExpr:
9888 case scSMaxExpr: {
9889 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009890 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009891 for (const SCEV *NAryOp : NAry->operands()) {
9892 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009893 if (D == DoesNotDominateBlock)
9894 return DoesNotDominateBlock;
9895 if (D == DominatesBlock)
9896 Proper = false;
9897 }
9898 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009899 }
9900 case scUDivExpr: {
9901 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009902 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9903 BlockDisposition LD = getBlockDisposition(LHS, BB);
9904 if (LD == DoesNotDominateBlock)
9905 return DoesNotDominateBlock;
9906 BlockDisposition RD = getBlockDisposition(RHS, BB);
9907 if (RD == DoesNotDominateBlock)
9908 return DoesNotDominateBlock;
9909 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9910 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009911 }
9912 case scUnknown:
9913 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009914 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9915 if (I->getParent() == BB)
9916 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009917 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009918 return ProperlyDominatesBlock;
9919 return DoesNotDominateBlock;
9920 }
9921 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009922 case scCouldNotCompute:
9923 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009924 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009925 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009926}
9927
9928bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9929 return getBlockDisposition(S, BB) >= DominatesBlock;
9930}
9931
9932bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9933 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009934}
Dan Gohman534749b2010-11-17 22:27:42 +00009935
9936bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009937 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +00009938}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009939
9940void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9941 ValuesAtScopes.erase(S);
9942 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009943 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009944 UnsignedRanges.erase(S);
9945 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009946 ExprValueMap.erase(S);
9947 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009948
Silviu Baranga6f444df2016-04-08 14:29:09 +00009949 auto RemoveSCEVFromBackedgeMap =
9950 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9951 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9952 BackedgeTakenInfo &BEInfo = I->second;
9953 if (BEInfo.hasOperand(S, this)) {
9954 BEInfo.clear();
9955 Map.erase(I++);
9956 } else
9957 ++I;
9958 }
9959 };
9960
9961 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9962 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009963}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009964
9965typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009966
Alp Tokercb402912014-01-24 17:20:08 +00009967/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009968static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9969 size_t Pos = 0;
9970 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9971 Str.replace(Pos, From.size(), To.data(), To.size());
9972 Pos += To.size();
9973 }
9974}
9975
Benjamin Kramer214935e2012-10-26 17:31:32 +00009976/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9977static void
9978getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009979 std::string &S = Map[L];
9980 if (S.empty()) {
9981 raw_string_ostream OS(S);
9982 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009983
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009984 // false and 0 are semantically equivalent. This can happen in dead loops.
9985 replaceSubString(OS.str(), "false", "0");
9986 // Remove wrap flags, their use in SCEV is highly fragile.
9987 // FIXME: Remove this when SCEV gets smarter about them.
9988 replaceSubString(OS.str(), "<nw>", "");
9989 replaceSubString(OS.str(), "<nsw>", "");
9990 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009991 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009992
JF Bastien61ad8b32015-12-23 18:18:53 +00009993 for (auto *R : reverse(*L))
9994 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009995}
9996
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009997void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009998 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9999
10000 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10001 // FIXME: It would be much better to store actual values instead of strings,
10002 // but SCEV pointers will change if we drop the caches.
10003 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010004 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010005 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10006
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010007 // Gather stringified backedge taken counts for all loops using a fresh
10008 // ScalarEvolution object.
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010009 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010010 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10011 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010012
10013 // Now compare whether they're the same with and without caches. This allows
10014 // verifying that no pass changed the cache.
10015 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10016 "New loops suddenly appeared!");
10017
10018 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10019 OldE = BackedgeDumpsOld.end(),
10020 NewI = BackedgeDumpsNew.begin();
10021 OldI != OldE; ++OldI, ++NewI) {
10022 assert(OldI->first == NewI->first && "Loop order changed!");
10023
10024 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10025 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010026 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010027 // means that a pass is buggy or SCEV has to learn a new pattern but is
10028 // usually not harmful.
10029 if (OldI->second != NewI->second &&
10030 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010031 NewI->second.find("undef") == std::string::npos &&
10032 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010033 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010034 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010035 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010036 << "' changed from '" << OldI->second
10037 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010038 std::abort();
10039 }
10040 }
10041
10042 // TODO: Verify more things.
10043}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010044
Chandler Carruth082c1832017-01-09 07:44:34 +000010045bool ScalarEvolution::invalidate(
10046 Function &F, const PreservedAnalyses &PA,
10047 FunctionAnalysisManager::Invalidator &Inv) {
10048 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10049 // of its dependencies is invalidated.
10050 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10051 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10052 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10053 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10054 Inv.invalidate<LoopAnalysis>(F, PA);
10055}
10056
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010057AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010058
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010059ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010060 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010061 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010062 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010063 AM.getResult<DominatorTreeAnalysis>(F),
10064 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010065}
10066
10067PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010068ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010069 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010070 return PreservedAnalyses::all();
10071}
10072
10073INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10074 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010075INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010076INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10077INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10078INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10079INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10080 "Scalar Evolution Analysis", false, true)
10081char ScalarEvolutionWrapperPass::ID = 0;
10082
10083ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10084 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10085}
10086
10087bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10088 SE.reset(new ScalarEvolution(
10089 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010090 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010091 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10092 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10093 return false;
10094}
10095
10096void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10097
10098void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10099 SE->print(OS);
10100}
10101
10102void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10103 if (!VerifySCEV)
10104 return;
10105
10106 SE->verify();
10107}
10108
10109void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10110 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010111 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010112 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10113 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10114 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10115}
Silviu Barangae3c05342015-11-02 14:41:02 +000010116
10117const SCEVPredicate *
10118ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10119 const SCEVConstant *RHS) {
10120 FoldingSetNodeID ID;
10121 // Unique this node based on the arguments
10122 ID.AddInteger(SCEVPredicate::P_Equal);
10123 ID.AddPointer(LHS);
10124 ID.AddPointer(RHS);
10125 void *IP = nullptr;
10126 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10127 return S;
10128 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10129 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10130 UniquePreds.InsertNode(Eq, IP);
10131 return Eq;
10132}
10133
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010134const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10135 const SCEVAddRecExpr *AR,
10136 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10137 FoldingSetNodeID ID;
10138 // Unique this node based on the arguments
10139 ID.AddInteger(SCEVPredicate::P_Wrap);
10140 ID.AddPointer(AR);
10141 ID.AddInteger(AddedFlags);
10142 void *IP = nullptr;
10143 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10144 return S;
10145 auto *OF = new (SCEVAllocator)
10146 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10147 UniquePreds.InsertNode(OF, IP);
10148 return OF;
10149}
10150
Benjamin Kramer83709b12015-11-16 09:01:28 +000010151namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010152
Silviu Barangae3c05342015-11-02 14:41:02 +000010153class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10154public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010155 /// Rewrites \p S in the context of a loop L and the SCEV predication
10156 /// infrastructure.
10157 ///
10158 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10159 /// equivalences present in \p Pred.
10160 ///
10161 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10162 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010163 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010164 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10165 SCEVUnionPredicate *Pred) {
10166 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010167 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010168 }
10169
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010170 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010171 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10172 SCEVUnionPredicate *Pred)
10173 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010174
10175 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010176 if (Pred) {
10177 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10178 for (auto *Pred : ExprPreds)
10179 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10180 if (IPred->getLHS() == Expr)
10181 return IPred->getRHS();
10182 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010183
10184 return Expr;
10185 }
10186
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010187 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10188 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010189 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010190 if (AR && AR->getLoop() == L && AR->isAffine()) {
10191 // This couldn't be folded because the operand didn't have the nuw
10192 // flag. Add the nusw flag as an assumption that we could make.
10193 const SCEV *Step = AR->getStepRecurrence(SE);
10194 Type *Ty = Expr->getType();
10195 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10196 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10197 SE.getSignExtendExpr(Step, Ty), L,
10198 AR->getNoWrapFlags());
10199 }
10200 return SE.getZeroExtendExpr(Operand, Expr->getType());
10201 }
10202
10203 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10204 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010205 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010206 if (AR && AR->getLoop() == L && AR->isAffine()) {
10207 // This couldn't be folded because the operand didn't have the nsw
10208 // flag. Add the nssw flag as an assumption that we could make.
10209 const SCEV *Step = AR->getStepRecurrence(SE);
10210 Type *Ty = Expr->getType();
10211 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10212 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10213 SE.getSignExtendExpr(Step, Ty), L,
10214 AR->getNoWrapFlags());
10215 }
10216 return SE.getSignExtendExpr(Operand, Expr->getType());
10217 }
10218
Silviu Barangae3c05342015-11-02 14:41:02 +000010219private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010220 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10221 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10222 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010223 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010224 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010225 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010226 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010227 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010228 return true;
10229 }
10230
Sanjoy Dasf0022122016-09-28 17:14:58 +000010231 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10232 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010233 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010234};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010235} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010236
Sanjoy Das807d33d2016-02-20 01:44:10 +000010237const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010238 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010239 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010240}
10241
Sanjoy Dasf0022122016-09-28 17:14:58 +000010242const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10243 const SCEV *S, const Loop *L,
10244 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10245
10246 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10247 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010248 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10249
10250 if (!AddRec)
10251 return nullptr;
10252
10253 // Since the transformation was successful, we can now transfer the SCEV
10254 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010255 for (auto *P : TransformPreds)
10256 Preds.insert(P);
10257
Silviu Barangad68ed852016-03-23 15:29:30 +000010258 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010259}
10260
10261/// SCEV predicates
10262SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10263 SCEVPredicateKind Kind)
10264 : FastID(ID), Kind(Kind) {}
10265
10266SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10267 const SCEVUnknown *LHS,
10268 const SCEVConstant *RHS)
10269 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10270
10271bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010272 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010273
10274 if (!Op)
10275 return false;
10276
10277 return Op->LHS == LHS && Op->RHS == RHS;
10278}
10279
10280bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10281
10282const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10283
10284void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10285 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10286}
10287
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010288SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10289 const SCEVAddRecExpr *AR,
10290 IncrementWrapFlags Flags)
10291 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10292
10293const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10294
10295bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10296 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10297
10298 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10299}
10300
10301bool SCEVWrapPredicate::isAlwaysTrue() const {
10302 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10303 IncrementWrapFlags IFlags = Flags;
10304
10305 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10306 IFlags = clearFlags(IFlags, IncrementNSSW);
10307
10308 return IFlags == IncrementAnyWrap;
10309}
10310
10311void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10312 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10313 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10314 OS << "<nusw>";
10315 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10316 OS << "<nssw>";
10317 OS << "\n";
10318}
10319
10320SCEVWrapPredicate::IncrementWrapFlags
10321SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10322 ScalarEvolution &SE) {
10323 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10324 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10325
10326 // We can safely transfer the NSW flag as NSSW.
10327 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10328 ImpliedFlags = IncrementNSSW;
10329
10330 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10331 // If the increment is positive, the SCEV NUW flag will also imply the
10332 // WrapPredicate NUSW flag.
10333 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10334 if (Step->getValue()->getValue().isNonNegative())
10335 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10336 }
10337
10338 return ImpliedFlags;
10339}
10340
Silviu Barangae3c05342015-11-02 14:41:02 +000010341/// Union predicates don't get cached so create a dummy set ID for it.
10342SCEVUnionPredicate::SCEVUnionPredicate()
10343 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10344
10345bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010346 return all_of(Preds,
10347 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010348}
10349
10350ArrayRef<const SCEVPredicate *>
10351SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10352 auto I = SCEVToPreds.find(Expr);
10353 if (I == SCEVToPreds.end())
10354 return ArrayRef<const SCEVPredicate *>();
10355 return I->second;
10356}
10357
10358bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010359 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010360 return all_of(Set->Preds,
10361 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010362
10363 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10364 if (ScevPredsIt == SCEVToPreds.end())
10365 return false;
10366 auto &SCEVPreds = ScevPredsIt->second;
10367
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010368 return any_of(SCEVPreds,
10369 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010370}
10371
10372const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10373
10374void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10375 for (auto Pred : Preds)
10376 Pred->print(OS, Depth);
10377}
10378
10379void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010380 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010381 for (auto Pred : Set->Preds)
10382 add(Pred);
10383 return;
10384 }
10385
10386 if (implies(N))
10387 return;
10388
10389 const SCEV *Key = N->getExpr();
10390 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10391 " associated expression!");
10392
10393 SCEVToPreds[Key].push_back(N);
10394 Preds.push_back(N);
10395}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010396
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010397PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10398 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010399 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010400
10401const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10402 const SCEV *Expr = SE.getSCEV(V);
10403 RewriteEntry &Entry = RewriteMap[Expr];
10404
10405 // If we already have an entry and the version matches, return it.
10406 if (Entry.second && Generation == Entry.first)
10407 return Entry.second;
10408
10409 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010410 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010411 if (Entry.second)
10412 Expr = Entry.second;
10413
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010414 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010415 Entry = {Generation, NewSCEV};
10416
10417 return NewSCEV;
10418}
10419
Silviu Baranga6f444df2016-04-08 14:29:09 +000010420const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10421 if (!BackedgeCount) {
10422 SCEVUnionPredicate BackedgePred;
10423 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10424 addPredicate(BackedgePred);
10425 }
10426 return BackedgeCount;
10427}
10428
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010429void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10430 if (Preds.implies(&Pred))
10431 return;
10432 Preds.add(&Pred);
10433 updateGeneration();
10434}
10435
10436const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10437 return Preds;
10438}
10439
10440void PredicatedScalarEvolution::updateGeneration() {
10441 // If the generation number wrapped recompute everything.
10442 if (++Generation == 0) {
10443 for (auto &II : RewriteMap) {
10444 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010445 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010446 }
10447 }
10448}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010449
10450void PredicatedScalarEvolution::setNoOverflow(
10451 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10452 const SCEV *Expr = getSCEV(V);
10453 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10454
10455 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10456
10457 // Clear the statically implied flags.
10458 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10459 addPredicate(*SE.getWrapPredicate(AR, Flags));
10460
10461 auto II = FlagsMap.insert({V, Flags});
10462 if (!II.second)
10463 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10464}
10465
10466bool PredicatedScalarEvolution::hasNoOverflow(
10467 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10468 const SCEV *Expr = getSCEV(V);
10469 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10470
10471 Flags = SCEVWrapPredicate::clearFlags(
10472 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10473
10474 auto II = FlagsMap.find(V);
10475
10476 if (II != FlagsMap.end())
10477 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10478
10479 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10480}
10481
Silviu Barangad68ed852016-03-23 15:29:30 +000010482const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010483 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010484 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10485 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010486
10487 if (!New)
10488 return nullptr;
10489
Sanjoy Dasf0022122016-09-28 17:14:58 +000010490 for (auto *P : NewPreds)
10491 Preds.add(P);
10492
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010493 updateGeneration();
10494 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10495 return New;
10496}
10497
Silviu Baranga6f444df2016-04-08 14:29:09 +000010498PredicatedScalarEvolution::PredicatedScalarEvolution(
10499 const PredicatedScalarEvolution &Init)
10500 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10501 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010502 for (const auto &I : Init.FlagsMap)
10503 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010504}
Silviu Barangab77365b2016-04-14 16:08:45 +000010505
10506void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10507 // For each block.
10508 for (auto *BB : L.getBlocks())
10509 for (auto &I : *BB) {
10510 if (!SE.isSCEVable(I.getType()))
10511 continue;
10512
10513 auto *Expr = SE.getSCEV(&I);
10514 auto II = RewriteMap.find(Expr);
10515
10516 if (II == RewriteMap.end())
10517 continue;
10518
10519 // Don't print things that are not interesting.
10520 if (II->second.second == Expr)
10521 continue;
10522
10523 OS.indent(Depth) << "[PSE]" << I << ":\n";
10524 OS.indent(Depth + 2) << *Expr << "\n";
10525 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10526 }
10527}