blob: af366aba1bb74e99cb1330ed5416830fca8968c5 [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
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000135static cl::opt<unsigned> MaxSCEVCompareDepth(
136 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
137 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
138 cl::init(32));
139
140static cl::opt<unsigned> MaxValueCompareDepth(
141 "scalar-evolution-max-value-compare-depth", cl::Hidden,
142 cl::desc("Maximum depth of recursive value complexity comparisons"),
143 cl::init(2));
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000144
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000145static cl::opt<unsigned>
146 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
147 cl::desc("Maximum depth of recursive AddExpr"),
148 cl::init(32));
149
Michael Liao468fb742017-01-13 18:28:30 +0000150static cl::opt<unsigned> MaxConstantEvolvingDepth(
151 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
152 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
153
Chris Lattnerd934c702004-04-02 20:23:17 +0000154//===----------------------------------------------------------------------===//
155// SCEV class definitions
156//===----------------------------------------------------------------------===//
157
158//===----------------------------------------------------------------------===//
159// Implementation of the SCEV class.
160//
Dan Gohman3423e722009-06-30 20:13:32 +0000161
Matthias Braun8c209aa2017-01-28 02:02:38 +0000162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
163LLVM_DUMP_METHOD void SCEV::dump() const {
Davide Italiano2071f4c2015-10-25 19:55:24 +0000164 print(dbgs());
165 dbgs() << '\n';
166}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000167#endif
Davide Italiano2071f4c2015-10-25 19:55:24 +0000168
Dan Gohman534749b2010-11-17 22:27:42 +0000169void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000170 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000171 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000172 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000173 return;
174 case scTruncate: {
175 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
176 const SCEV *Op = Trunc->getOperand();
177 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
178 << *Trunc->getType() << ")";
179 return;
180 }
181 case scZeroExtend: {
182 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
183 const SCEV *Op = ZExt->getOperand();
184 OS << "(zext " << *Op->getType() << " " << *Op << " to "
185 << *ZExt->getType() << ")";
186 return;
187 }
188 case scSignExtend: {
189 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
190 const SCEV *Op = SExt->getOperand();
191 OS << "(sext " << *Op->getType() << " " << *Op << " to "
192 << *SExt->getType() << ")";
193 return;
194 }
195 case scAddRecExpr: {
196 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
197 OS << "{" << *AR->getOperand(0);
198 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
199 OS << ",+," << *AR->getOperand(i);
200 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000201 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000202 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000203 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000204 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000205 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000206 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
207 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000208 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000209 OS << ">";
210 return;
211 }
212 case scAddExpr:
213 case scMulExpr:
214 case scUMaxExpr:
215 case scSMaxExpr: {
216 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000217 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000218 switch (NAry->getSCEVType()) {
219 case scAddExpr: OpStr = " + "; break;
220 case scMulExpr: OpStr = " * "; break;
221 case scUMaxExpr: OpStr = " umax "; break;
222 case scSMaxExpr: OpStr = " smax "; break;
223 }
224 OS << "(";
225 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
226 I != E; ++I) {
227 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000228 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000229 OS << OpStr;
230 }
231 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000232 switch (NAry->getSCEVType()) {
233 case scAddExpr:
234 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000235 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000236 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000237 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000238 OS << "<nsw>";
239 }
Dan Gohman534749b2010-11-17 22:27:42 +0000240 return;
241 }
242 case scUDivExpr: {
243 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
244 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
245 return;
246 }
247 case scUnknown: {
248 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000249 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000250 if (U->isSizeOf(AllocTy)) {
251 OS << "sizeof(" << *AllocTy << ")";
252 return;
253 }
254 if (U->isAlignOf(AllocTy)) {
255 OS << "alignof(" << *AllocTy << ")";
256 return;
257 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000258
Chris Lattner229907c2011-07-18 04:54:35 +0000259 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000260 Constant *FieldNo;
261 if (U->isOffsetOf(CTy, FieldNo)) {
262 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000263 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000264 OS << ")";
265 return;
266 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000267
Dan Gohman534749b2010-11-17 22:27:42 +0000268 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000269 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000270 return;
271 }
272 case scCouldNotCompute:
273 OS << "***COULDNOTCOMPUTE***";
274 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000275 }
276 llvm_unreachable("Unknown SCEV kind!");
277}
278
Chris Lattner229907c2011-07-18 04:54:35 +0000279Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000280 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000281 case scConstant:
282 return cast<SCEVConstant>(this)->getType();
283 case scTruncate:
284 case scZeroExtend:
285 case scSignExtend:
286 return cast<SCEVCastExpr>(this)->getType();
287 case scAddRecExpr:
288 case scMulExpr:
289 case scUMaxExpr:
290 case scSMaxExpr:
291 return cast<SCEVNAryExpr>(this)->getType();
292 case scAddExpr:
293 return cast<SCEVAddExpr>(this)->getType();
294 case scUDivExpr:
295 return cast<SCEVUDivExpr>(this)->getType();
296 case scUnknown:
297 return cast<SCEVUnknown>(this)->getType();
298 case scCouldNotCompute:
299 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000300 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000301 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000302}
303
Dan Gohmanbe928e32008-06-18 16:23:07 +0000304bool SCEV::isZero() const {
305 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
306 return SC->getValue()->isZero();
307 return false;
308}
309
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000310bool SCEV::isOne() const {
311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312 return SC->getValue()->isOne();
313 return false;
314}
Chris Lattnerd934c702004-04-02 20:23:17 +0000315
Dan Gohman18a96bb2009-06-24 00:30:26 +0000316bool SCEV::isAllOnesValue() const {
317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318 return SC->getValue()->isAllOnesValue();
319 return false;
320}
321
Andrew Trick881a7762012-01-07 00:27:31 +0000322bool SCEV::isNonConstantNegative() const {
323 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
324 if (!Mul) return false;
325
326 // If there is a constant factor, it will be first.
327 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
328 if (!SC) return false;
329
330 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000331 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000332}
333
Owen Anderson04052ec2009-06-22 21:57:23 +0000334SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000335 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000336
Chris Lattnerd934c702004-04-02 20:23:17 +0000337bool SCEVCouldNotCompute::classof(const SCEV *S) {
338 return S->getSCEVType() == scCouldNotCompute;
339}
340
Dan Gohmanaf752342009-07-07 17:06:11 +0000341const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000342 FoldingSetNodeID ID;
343 ID.AddInteger(scConstant);
344 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000345 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000346 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000347 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000348 UniqueSCEVs.InsertNode(S, IP);
349 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350}
Chris Lattnerd934c702004-04-02 20:23:17 +0000351
Nick Lewycky31eaca52014-01-27 10:04:03 +0000352const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000353 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000354}
355
Dan Gohmanaf752342009-07-07 17:06:11 +0000356const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000357ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
358 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000359 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000360}
361
Dan Gohman24ceda82010-06-18 19:54:20 +0000362SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000363 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000364 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000365
Dan Gohman24ceda82010-06-18 19:54:20 +0000366SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000367 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000368 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000369 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
370 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000371 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000372}
Chris Lattnerd934c702004-04-02 20:23:17 +0000373
Dan Gohman24ceda82010-06-18 19:54:20 +0000374SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000375 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000376 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000377 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
378 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000379 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000380}
381
Dan Gohman24ceda82010-06-18 19:54:20 +0000382SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000383 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000384 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000385 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
386 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000387 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000388}
389
Dan Gohman7cac9572010-08-02 23:49:30 +0000390void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000391 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000392 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000393
394 // Remove this SCEVUnknown from the uniquing map.
395 SE->UniqueSCEVs.RemoveNode(this);
396
397 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000398 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000399}
400
401void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000402 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000403 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000404
405 // Remove this SCEVUnknown from the uniquing map.
406 SE->UniqueSCEVs.RemoveNode(this);
407
408 // Update this SCEVUnknown to point to the new value. This is needed
409 // because there may still be outstanding SCEVs which still point to
410 // this SCEVUnknown.
411 setValPtr(New);
412}
413
Chris Lattner229907c2011-07-18 04:54:35 +0000414bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000415 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000416 if (VCE->getOpcode() == Instruction::PtrToInt)
417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000418 if (CE->getOpcode() == Instruction::GetElementPtr &&
419 CE->getOperand(0)->isNullValue() &&
420 CE->getNumOperands() == 2)
421 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
422 if (CI->isOne()) {
423 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
424 ->getElementType();
425 return true;
426 }
Dan Gohmancf913832010-01-28 02:15:55 +0000427
428 return false;
429}
430
Chris Lattner229907c2011-07-18 04:54:35 +0000431bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000437 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000438 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000439 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000440 if (!STy->isPacked() &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(1)->isNullValue()) {
443 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
444 if (CI->isOne() &&
445 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000446 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000447 AllocTy = STy->getElementType(1);
448 return true;
449 }
450 }
451 }
Dan Gohmancf913832010-01-28 02:15:55 +0000452
453 return false;
454}
455
Chris Lattner229907c2011-07-18 04:54:35 +0000456bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000457 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000458 if (VCE->getOpcode() == Instruction::PtrToInt)
459 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
460 if (CE->getOpcode() == Instruction::GetElementPtr &&
461 CE->getNumOperands() == 3 &&
462 CE->getOperand(0)->isNullValue() &&
463 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000464 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000465 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
466 // Ignore vector types here so that ScalarEvolutionExpander doesn't
467 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000468 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000469 CTy = Ty;
470 FieldNo = CE->getOperand(2);
471 return true;
472 }
473 }
474
475 return false;
476}
477
Chris Lattnereb3e8402004-06-20 06:23:15 +0000478//===----------------------------------------------------------------------===//
479// SCEV Utilities
480//===----------------------------------------------------------------------===//
481
Sanjoy Das17078692016-10-31 03:32:43 +0000482/// Compare the two values \p LV and \p RV in terms of their "complexity" where
483/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
484/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
485/// have been previously deemed to be "equally complex" by this routine. It is
486/// intended to avoid exponential time complexity in cases like:
487///
488/// %a = f(%x, %y)
489/// %b = f(%a, %a)
490/// %c = f(%b, %b)
491///
492/// %d = f(%x, %y)
493/// %e = f(%d, %d)
494/// %f = f(%e, %e)
495///
496/// CompareValueComplexity(%f, %c)
497///
498/// Since we do not continue running this routine on expression trees once we
499/// have seen unequal values, there is no need to track them in the cache.
500static int
501CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
502 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000503 unsigned Depth) {
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000504 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000505 return 0;
506
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000507 // Order pointer values after integer values. This helps SCEVExpander form
508 // GEPs.
509 bool LIsPointer = LV->getType()->isPointerTy(),
510 RIsPointer = RV->getType()->isPointerTy();
511 if (LIsPointer != RIsPointer)
512 return (int)LIsPointer - (int)RIsPointer;
513
514 // Compare getValueID values.
515 unsigned LID = LV->getValueID(), RID = RV->getValueID();
516 if (LID != RID)
517 return (int)LID - (int)RID;
518
519 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000520 if (const auto *LA = dyn_cast<Argument>(LV)) {
521 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000522 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
523 return (int)LArgNo - (int)RArgNo;
524 }
525
Sanjoy Das299e6722016-10-30 23:52:56 +0000526 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
527 const auto *RGV = cast<GlobalValue>(RV);
528
529 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
530 auto LT = GV->getLinkage();
531 return !(GlobalValue::isPrivateLinkage(LT) ||
532 GlobalValue::isInternalLinkage(LT));
533 };
534
535 // Use the names to distinguish the two values, but only if the
536 // names are semantically important.
537 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
538 return LGV->getName().compare(RGV->getName());
539 }
540
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000541 // For instructions, compare their loop depth, and their operand count. This
542 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000543 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
544 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000545
546 // Compare loop depths.
547 const BasicBlock *LParent = LInst->getParent(),
548 *RParent = RInst->getParent();
549 if (LParent != RParent) {
550 unsigned LDepth = LI->getLoopDepth(LParent),
551 RDepth = LI->getLoopDepth(RParent);
552 if (LDepth != RDepth)
553 return (int)LDepth - (int)RDepth;
554 }
555
556 // Compare the number of operands.
557 unsigned LNumOps = LInst->getNumOperands(),
558 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000559 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000560 return (int)LNumOps - (int)RNumOps;
561
Sanjoy Das17078692016-10-31 03:32:43 +0000562 for (unsigned Idx : seq(0u, LNumOps)) {
563 int Result =
564 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000565 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000566 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000567 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000568 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000569 }
570
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000571 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000572 return 0;
573}
574
Sanjoy Das237c8452016-09-27 18:01:48 +0000575// Return negative, zero, or positive, if LHS is less than, equal to, or greater
576// than RHS, respectively. A three-way result allows recursive comparisons to be
577// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000578static int CompareSCEVComplexity(
579 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
580 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
581 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000582 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
583 if (LHS == RHS)
584 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000585
Sanjoy Das237c8452016-09-27 18:01:48 +0000586 // Primarily, sort the SCEVs by their getSCEVType().
587 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
588 if (LType != RType)
589 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000590
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000591 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000592 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000593 // Aside from the getSCEVType() ordering, the particular ordering
594 // isn't very important except that it's beneficial to be consistent,
595 // so that (a + b) and (b + a) don't end up as different expressions.
596 switch (static_cast<SCEVTypes>(LType)) {
597 case scUnknown: {
598 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
599 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000600
Sanjoy Das17078692016-10-31 03:32:43 +0000601 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000602 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
603 Depth + 1);
604 if (X == 0)
605 EqCacheSCEV.insert({LHS, RHS});
606 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000607 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000608
Sanjoy Das237c8452016-09-27 18:01:48 +0000609 case scConstant: {
610 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
611 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
612
613 // Compare constant values.
614 const APInt &LA = LC->getAPInt();
615 const APInt &RA = RC->getAPInt();
616 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
617 if (LBitWidth != RBitWidth)
618 return (int)LBitWidth - (int)RBitWidth;
619 return LA.ult(RA) ? -1 : 1;
620 }
621
622 case scAddRecExpr: {
623 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
624 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
625
626 // Compare addrec loop depths.
627 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
628 if (LLoop != RLoop) {
629 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
630 if (LDepth != RDepth)
631 return (int)LDepth - (int)RDepth;
632 }
633
634 // Addrec complexity grows with operand count.
635 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
636 if (LNumOps != RNumOps)
637 return (int)LNumOps - (int)RNumOps;
638
639 // Lexicographically compare.
640 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000641 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
642 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000643 if (X != 0)
644 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000645 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000646 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000647 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000648 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000649
650 case scAddExpr:
651 case scMulExpr:
652 case scSMaxExpr:
653 case scUMaxExpr: {
654 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
655 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
656
657 // Lexicographically compare n-ary expressions.
658 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
659 if (LNumOps != RNumOps)
660 return (int)LNumOps - (int)RNumOps;
661
662 for (unsigned i = 0; i != LNumOps; ++i) {
663 if (i >= RNumOps)
664 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000665 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
666 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000667 if (X != 0)
668 return X;
669 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000670 EqCacheSCEV.insert({LHS, RHS});
671 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000672 }
673
674 case scUDivExpr: {
675 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
676 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
677
678 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000679 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
680 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000681 if (X != 0)
682 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000683 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
684 Depth + 1);
685 if (X == 0)
686 EqCacheSCEV.insert({LHS, RHS});
687 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000688 }
689
690 case scTruncate:
691 case scZeroExtend:
692 case scSignExtend: {
693 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
694 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
695
696 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000697 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
698 RC->getOperand(), Depth + 1);
699 if (X == 0)
700 EqCacheSCEV.insert({LHS, RHS});
701 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000702 }
703
704 case scCouldNotCompute:
705 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
706 }
707 llvm_unreachable("Unknown SCEV kind!");
708}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000709
Sanjoy Dasf8570812016-05-29 00:38:22 +0000710/// Given a list of SCEV objects, order them by their complexity, and group
711/// objects of the same complexity together by value. When this routine is
712/// finished, we know that any duplicates in the vector are consecutive and that
713/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000714///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000715/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000716/// results from this routine. In other words, we don't want the results of
717/// this to depend on where the addresses of various SCEV objects happened to
718/// land in memory.
719///
Dan Gohmanaf752342009-07-07 17:06:11 +0000720static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000721 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000722 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000723
724 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000725 if (Ops.size() == 2) {
726 // This is the common case, which also happens to be trivially simple.
727 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000728 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000729 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000730 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000731 return;
732 }
733
Dan Gohman24ceda82010-06-18 19:54:20 +0000734 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000735 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000736 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
737 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000738 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000739
740 // Now that we are sorted by complexity, group elements of the same
741 // complexity. Note that this is, at worst, N^2, but the vector is likely to
742 // be extremely short in practice. Note that we take this approach because we
743 // do not want to depend on the addresses of the objects we are grouping.
744 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
745 const SCEV *S = Ops[i];
746 unsigned Complexity = S->getSCEVType();
747
748 // If there are any objects of the same complexity and same value as this
749 // one, group them.
750 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
751 if (Ops[j] == S) { // Found a duplicate.
752 // Move it to immediately after i'th element.
753 std::swap(Ops[i+1], Ops[j]);
754 ++i; // no need to rescan it.
755 if (i == e-2) return; // Done!
756 }
757 }
758 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000759}
760
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000761// Returns the size of the SCEV S.
762static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000763 struct FindSCEVSize {
764 int Size;
765 FindSCEVSize() : Size(0) {}
766
767 bool follow(const SCEV *S) {
768 ++Size;
769 // Keep looking at all operands of S.
770 return true;
771 }
772 bool isDone() const {
773 return false;
774 }
775 };
776
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000777 FindSCEVSize F;
778 SCEVTraversal<FindSCEVSize> ST(F);
779 ST.visitAll(S);
780 return F.Size;
781}
782
783namespace {
784
David Majnemer4e879362014-12-14 09:12:33 +0000785struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000786public:
787 // Computes the Quotient and Remainder of the division of Numerator by
788 // Denominator.
789 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
790 const SCEV *Denominator, const SCEV **Quotient,
791 const SCEV **Remainder) {
792 assert(Numerator && Denominator && "Uninitialized SCEV");
793
David Majnemer4e879362014-12-14 09:12:33 +0000794 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000795
796 // Check for the trivial case here to avoid having to check for it in the
797 // rest of the code.
798 if (Numerator == Denominator) {
799 *Quotient = D.One;
800 *Remainder = D.Zero;
801 return;
802 }
803
804 if (Numerator->isZero()) {
805 *Quotient = D.Zero;
806 *Remainder = D.Zero;
807 return;
808 }
809
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000810 // A simple case when N/1. The quotient is N.
811 if (Denominator->isOne()) {
812 *Quotient = Numerator;
813 *Remainder = D.Zero;
814 return;
815 }
816
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000817 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000818 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000819 const SCEV *Q, *R;
820 *Quotient = Numerator;
821 for (const SCEV *Op : T->operands()) {
822 divide(SE, *Quotient, Op, &Q, &R);
823 *Quotient = Q;
824
825 // Bail out when the Numerator is not divisible by one of the terms of
826 // the Denominator.
827 if (!R->isZero()) {
828 *Quotient = D.Zero;
829 *Remainder = Numerator;
830 return;
831 }
832 }
833 *Remainder = D.Zero;
834 return;
835 }
836
837 D.visit(Numerator);
838 *Quotient = D.Quotient;
839 *Remainder = D.Remainder;
840 }
841
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000842 // Except in the trivial case described above, we do not know how to divide
843 // Expr by Denominator for the following functions with empty implementation.
844 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
845 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
846 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
847 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
848 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
849 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
850 void visitUnknown(const SCEVUnknown *Numerator) {}
851 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
852
David Majnemer4e879362014-12-14 09:12:33 +0000853 void visitConstant(const SCEVConstant *Numerator) {
854 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000855 APInt NumeratorVal = Numerator->getAPInt();
856 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000857 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
858 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
859
860 if (NumeratorBW > DenominatorBW)
861 DenominatorVal = DenominatorVal.sext(NumeratorBW);
862 else if (NumeratorBW < DenominatorBW)
863 NumeratorVal = NumeratorVal.sext(DenominatorBW);
864
865 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
866 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
867 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
868 Quotient = SE.getConstant(QuotientVal);
869 Remainder = SE.getConstant(RemainderVal);
870 return;
871 }
872 }
873
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000874 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
875 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000876 if (!Numerator->isAffine())
877 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000878 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
879 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000880 // Bail out if the types do not match.
881 Type *Ty = Denominator->getType();
882 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000883 Ty != StepQ->getType() || Ty != StepR->getType())
884 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000885 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
886 Numerator->getNoWrapFlags());
887 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
888 Numerator->getNoWrapFlags());
889 }
890
891 void visitAddExpr(const SCEVAddExpr *Numerator) {
892 SmallVector<const SCEV *, 2> Qs, Rs;
893 Type *Ty = Denominator->getType();
894
895 for (const SCEV *Op : Numerator->operands()) {
896 const SCEV *Q, *R;
897 divide(SE, Op, Denominator, &Q, &R);
898
899 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000900 if (Ty != Q->getType() || Ty != R->getType())
901 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000902
903 Qs.push_back(Q);
904 Rs.push_back(R);
905 }
906
907 if (Qs.size() == 1) {
908 Quotient = Qs[0];
909 Remainder = Rs[0];
910 return;
911 }
912
913 Quotient = SE.getAddExpr(Qs);
914 Remainder = SE.getAddExpr(Rs);
915 }
916
917 void visitMulExpr(const SCEVMulExpr *Numerator) {
918 SmallVector<const SCEV *, 2> Qs;
919 Type *Ty = Denominator->getType();
920
921 bool FoundDenominatorTerm = false;
922 for (const SCEV *Op : Numerator->operands()) {
923 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000924 if (Ty != Op->getType())
925 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000926
927 if (FoundDenominatorTerm) {
928 Qs.push_back(Op);
929 continue;
930 }
931
932 // Check whether Denominator divides one of the product operands.
933 const SCEV *Q, *R;
934 divide(SE, Op, Denominator, &Q, &R);
935 if (!R->isZero()) {
936 Qs.push_back(Op);
937 continue;
938 }
939
940 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000941 if (Ty != Q->getType())
942 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000943
944 FoundDenominatorTerm = true;
945 Qs.push_back(Q);
946 }
947
948 if (FoundDenominatorTerm) {
949 Remainder = Zero;
950 if (Qs.size() == 1)
951 Quotient = Qs[0];
952 else
953 Quotient = SE.getMulExpr(Qs);
954 return;
955 }
956
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000957 if (!isa<SCEVUnknown>(Denominator))
958 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000959
960 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
961 ValueToValueMap RewriteMap;
962 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
963 cast<SCEVConstant>(Zero)->getValue();
964 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
965
966 if (Remainder->isZero()) {
967 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
968 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
969 cast<SCEVConstant>(One)->getValue();
970 Quotient =
971 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
972 return;
973 }
974
975 // Quotient is (Numerator - Remainder) divided by Denominator.
976 const SCEV *Q, *R;
977 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000978 // This SCEV does not seem to simplify: fail the division here.
979 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
980 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000981 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000982 if (R != Zero)
983 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000984 Quotient = Q;
985 }
986
987private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000988 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
989 const SCEV *Denominator)
990 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000991 Zero = SE.getZero(Denominator->getType());
992 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000993
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000994 // We generally do not know how to divide Expr by Denominator. We
995 // initialize the division to a "cannot divide" state to simplify the rest
996 // of the code.
997 cannotDivide(Numerator);
998 }
999
1000 // Convenience function for giving up on the division. We set the quotient to
1001 // be equal to zero and the remainder to be equal to the numerator.
1002 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +00001003 Quotient = Zero;
1004 Remainder = Numerator;
1005 }
1006
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001007 ScalarEvolution &SE;
1008 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +00001009};
1010
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001011}
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001012
Chris Lattnerd934c702004-04-02 20:23:17 +00001013//===----------------------------------------------------------------------===//
1014// Simple SCEV method implementations
1015//===----------------------------------------------------------------------===//
1016
Sanjoy Dasf8570812016-05-29 00:38:22 +00001017/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +00001018static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +00001019 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001020 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001021 // Handle the simplest case efficiently.
1022 if (K == 1)
1023 return SE.getTruncateOrZeroExtend(It, ResultTy);
1024
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001025 // We are using the following formula for BC(It, K):
1026 //
1027 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1028 //
Eli Friedman61f67622008-08-04 23:49:06 +00001029 // Suppose, W is the bitwidth of the return value. We must be prepared for
1030 // overflow. Hence, we must assure that the result of our computation is
1031 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1032 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001033 //
Eli Friedman61f67622008-08-04 23:49:06 +00001034 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001035 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001036 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1037 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001038 //
Eli Friedman61f67622008-08-04 23:49:06 +00001039 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001040 //
Eli Friedman61f67622008-08-04 23:49:06 +00001041 // This formula is trivially equivalent to the previous formula. However,
1042 // this formula can be implemented much more efficiently. The trick is that
1043 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1044 // arithmetic. To do exact division in modular arithmetic, all we have
1045 // to do is multiply by the inverse. Therefore, this step can be done at
1046 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001047 //
Eli Friedman61f67622008-08-04 23:49:06 +00001048 // The next issue is how to safely do the division by 2^T. The way this
1049 // is done is by doing the multiplication step at a width of at least W + T
1050 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1051 // when we perform the division by 2^T (which is equivalent to a right shift
1052 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1053 // truncated out after the division by 2^T.
1054 //
1055 // In comparison to just directly using the first formula, this technique
1056 // is much more efficient; using the first formula requires W * K bits,
1057 // but this formula less than W + K bits. Also, the first formula requires
1058 // a division step, whereas this formula only requires multiplies and shifts.
1059 //
1060 // It doesn't matter whether the subtraction step is done in the calculation
1061 // width or the input iteration count's width; if the subtraction overflows,
1062 // the result must be zero anyway. We prefer here to do it in the width of
1063 // the induction variable because it helps a lot for certain cases; CodeGen
1064 // isn't smart enough to ignore the overflow, which leads to much less
1065 // efficient code if the width of the subtraction is wider than the native
1066 // register width.
1067 //
1068 // (It's possible to not widen at all by pulling out factors of 2 before
1069 // the multiplication; for example, K=2 can be calculated as
1070 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1071 // extra arithmetic, so it's not an obvious win, and it gets
1072 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001073
Eli Friedman61f67622008-08-04 23:49:06 +00001074 // Protection from insane SCEVs; this bound is conservative,
1075 // but it probably doesn't matter.
1076 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001077 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001078
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001079 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001080
Eli Friedman61f67622008-08-04 23:49:06 +00001081 // Calculate K! / 2^T and T; we divide out the factors of two before
1082 // multiplying for calculating K! / 2^T to avoid overflow.
1083 // Other overflow doesn't matter because we only care about the bottom
1084 // W bits of the result.
1085 APInt OddFactorial(W, 1);
1086 unsigned T = 1;
1087 for (unsigned i = 3; i <= K; ++i) {
1088 APInt Mult(W, i);
1089 unsigned TwoFactors = Mult.countTrailingZeros();
1090 T += TwoFactors;
1091 Mult = Mult.lshr(TwoFactors);
1092 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001093 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001094
Eli Friedman61f67622008-08-04 23:49:06 +00001095 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001096 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001097
Dan Gohman8b0a4192010-03-01 17:49:51 +00001098 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001099 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001100
1101 // Calculate the multiplicative inverse of K! / 2^T;
1102 // this multiplication factor will perform the exact division by
1103 // K! / 2^T.
1104 APInt Mod = APInt::getSignedMinValue(W+1);
1105 APInt MultiplyFactor = OddFactorial.zext(W+1);
1106 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1107 MultiplyFactor = MultiplyFactor.trunc(W);
1108
1109 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001110 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001111 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001112 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001113 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001114 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001115 Dividend = SE.getMulExpr(Dividend,
1116 SE.getTruncateOrZeroExtend(S, CalculationTy));
1117 }
1118
1119 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001120 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001121
1122 // Truncate the result, and divide by K! / 2^T.
1123
1124 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1125 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001126}
1127
Sanjoy Dasf8570812016-05-29 00:38:22 +00001128/// Return the value of this chain of recurrences at the specified iteration
1129/// number. We can evaluate this recurrence by multiplying each element in the
1130/// chain by the binomial coefficient corresponding to it. In other words, we
1131/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001132///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001133/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001134///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001135/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001136///
Dan Gohmanaf752342009-07-07 17:06:11 +00001137const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001138 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001139 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001140 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001141 // The computation is correct in the face of overflow provided that the
1142 // multiplication is performed _after_ the evaluation of the binomial
1143 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001144 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001145 if (isa<SCEVCouldNotCompute>(Coeff))
1146 return Coeff;
1147
1148 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001149 }
1150 return Result;
1151}
1152
Chris Lattnerd934c702004-04-02 20:23:17 +00001153//===----------------------------------------------------------------------===//
1154// SCEV Expression folder implementations
1155//===----------------------------------------------------------------------===//
1156
Dan Gohmanaf752342009-07-07 17:06:11 +00001157const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001158 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001159 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001160 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001161 assert(isSCEVable(Ty) &&
1162 "This is not a conversion to a SCEVable type!");
1163 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001164
Dan Gohman3a302cb2009-07-13 20:50:19 +00001165 FoldingSetNodeID ID;
1166 ID.AddInteger(scTruncate);
1167 ID.AddPointer(Op);
1168 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001169 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001170 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1171
Dan Gohman3423e722009-06-30 20:13:32 +00001172 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001173 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001174 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001175 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001176
Dan Gohman79af8542009-04-22 16:20:48 +00001177 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001178 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001179 return getTruncateExpr(ST->getOperand(), Ty);
1180
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001181 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001182 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001183 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1184
1185 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001186 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001187 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1188
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001189 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001190 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001191 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1192 SmallVector<const SCEV *, 4> Operands;
1193 bool hasTrunc = false;
1194 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1195 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001196 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1197 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001198 Operands.push_back(S);
1199 }
1200 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001201 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001202 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001203 }
1204
Nick Lewycky5c901f32011-01-19 18:56:00 +00001205 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001206 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001207 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1208 SmallVector<const SCEV *, 4> Operands;
1209 bool hasTrunc = false;
1210 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1211 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001212 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1213 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001214 Operands.push_back(S);
1215 }
1216 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001217 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001218 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001219 }
1220
Dan Gohman5a728c92009-06-18 16:24:47 +00001221 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001222 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001223 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001224 for (const SCEV *Op : AddRec->operands())
1225 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001226 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001227 }
1228
Dan Gohman89dd42a2010-06-25 18:47:08 +00001229 // The cast wasn't folded; create an explicit cast node. We can reuse
1230 // the existing insert position since if we get here, we won't have
1231 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001232 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1233 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001234 UniqueSCEVs.InsertNode(S, IP);
1235 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001236}
1237
Sanjoy Das4153f472015-02-18 01:47:07 +00001238// Get the limit of a recurrence such that incrementing by Step cannot cause
1239// signed overflow as long as the value of the recurrence within the
1240// loop does not exceed this limit before incrementing.
1241static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1242 ICmpInst::Predicate *Pred,
1243 ScalarEvolution *SE) {
1244 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1245 if (SE->isKnownPositive(Step)) {
1246 *Pred = ICmpInst::ICMP_SLT;
1247 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1248 SE->getSignedRange(Step).getSignedMax());
1249 }
1250 if (SE->isKnownNegative(Step)) {
1251 *Pred = ICmpInst::ICMP_SGT;
1252 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1253 SE->getSignedRange(Step).getSignedMin());
1254 }
1255 return nullptr;
1256}
1257
1258// Get the limit of a recurrence such that incrementing by Step cannot cause
1259// unsigned overflow as long as the value of the recurrence within the loop does
1260// not exceed this limit before incrementing.
1261static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1262 ICmpInst::Predicate *Pred,
1263 ScalarEvolution *SE) {
1264 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1265 *Pred = ICmpInst::ICMP_ULT;
1266
1267 return SE->getConstant(APInt::getMinValue(BitWidth) -
1268 SE->getUnsignedRange(Step).getUnsignedMax());
1269}
1270
1271namespace {
1272
1273struct ExtendOpTraitsBase {
1274 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1275};
1276
1277// Used to make code generic over signed and unsigned overflow.
1278template <typename ExtendOp> struct ExtendOpTraits {
1279 // Members present:
1280 //
1281 // static const SCEV::NoWrapFlags WrapType;
1282 //
1283 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1284 //
1285 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1286 // ICmpInst::Predicate *Pred,
1287 // ScalarEvolution *SE);
1288};
1289
1290template <>
1291struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1292 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1293
1294 static const GetExtendExprTy GetExtendExpr;
1295
1296 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1297 ICmpInst::Predicate *Pred,
1298 ScalarEvolution *SE) {
1299 return getSignedOverflowLimitForStep(Step, Pred, SE);
1300 }
1301};
1302
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001303const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001304 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1305
1306template <>
1307struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1308 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1309
1310 static const GetExtendExprTy GetExtendExpr;
1311
1312 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1313 ICmpInst::Predicate *Pred,
1314 ScalarEvolution *SE) {
1315 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1316 }
1317};
1318
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001319const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001320 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001321}
Sanjoy Das4153f472015-02-18 01:47:07 +00001322
1323// The recurrence AR has been shown to have no signed/unsigned wrap or something
1324// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1325// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1326// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1327// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1328// expression "Step + sext/zext(PreIncAR)" is congruent with
1329// "sext/zext(PostIncAR)"
1330template <typename ExtendOpTy>
1331static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1332 ScalarEvolution *SE) {
1333 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1334 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1335
1336 const Loop *L = AR->getLoop();
1337 const SCEV *Start = AR->getStart();
1338 const SCEV *Step = AR->getStepRecurrence(*SE);
1339
1340 // Check for a simple looking step prior to loop entry.
1341 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1342 if (!SA)
1343 return nullptr;
1344
1345 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1346 // subtraction is expensive. For this purpose, perform a quick and dirty
1347 // difference, by checking for Step in the operand list.
1348 SmallVector<const SCEV *, 4> DiffOps;
1349 for (const SCEV *Op : SA->operands())
1350 if (Op != Step)
1351 DiffOps.push_back(Op);
1352
1353 if (DiffOps.size() == SA->getNumOperands())
1354 return nullptr;
1355
1356 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1357 // `Step`:
1358
1359 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001360 auto PreStartFlags =
1361 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1362 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001363 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1364 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1365
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001366 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1367 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001368 //
1369
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001370 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1371 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1372 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001373 return PreStart;
1374
1375 // 2. Direct overflow check on the step operation's expression.
1376 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1377 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1378 const SCEV *OperandExtendedStart =
1379 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1380 (SE->*GetExtendExpr)(Step, WideTy));
1381 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1382 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1383 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1384 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1385 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1386 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1387 }
1388 return PreStart;
1389 }
1390
1391 // 3. Loop precondition.
1392 ICmpInst::Predicate Pred;
1393 const SCEV *OverflowLimit =
1394 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1395
1396 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001397 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001398 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001399
Sanjoy Das4153f472015-02-18 01:47:07 +00001400 return nullptr;
1401}
1402
1403// Get the normalized zero or sign extended expression for this AddRec's Start.
1404template <typename ExtendOpTy>
1405static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1406 ScalarEvolution *SE) {
1407 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1408
1409 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1410 if (!PreStart)
1411 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1412
1413 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1414 (SE->*GetExtendExpr)(PreStart, Ty));
1415}
1416
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001417// Try to prove away overflow by looking at "nearby" add recurrences. A
1418// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1419// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1420//
1421// Formally:
1422//
1423// {S,+,X} == {S-T,+,X} + T
1424// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1425//
1426// If ({S-T,+,X} + T) does not overflow ... (1)
1427//
1428// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1429//
1430// If {S-T,+,X} does not overflow ... (2)
1431//
1432// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1433// == {Ext(S-T)+Ext(T),+,Ext(X)}
1434//
1435// If (S-T)+T does not overflow ... (3)
1436//
1437// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1438// == {Ext(S),+,Ext(X)} == LHS
1439//
1440// Thus, if (1), (2) and (3) are true for some T, then
1441// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1442//
1443// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1444// does not overflow" restricted to the 0th iteration. Therefore we only need
1445// to check for (1) and (2).
1446//
1447// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1448// is `Delta` (defined below).
1449//
1450template <typename ExtendOpTy>
1451bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1452 const SCEV *Step,
1453 const Loop *L) {
1454 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1455
1456 // We restrict `Start` to a constant to prevent SCEV from spending too much
1457 // time here. It is correct (but more expensive) to continue with a
1458 // non-constant `Start` and do a general SCEV subtraction to compute
1459 // `PreStart` below.
1460 //
1461 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1462 if (!StartC)
1463 return false;
1464
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001465 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001466
1467 for (unsigned Delta : {-2, -1, 1, 2}) {
1468 const SCEV *PreStart = getConstant(StartAI - Delta);
1469
Sanjoy Das42801102015-10-23 06:57:21 +00001470 FoldingSetNodeID ID;
1471 ID.AddInteger(scAddRecExpr);
1472 ID.AddPointer(PreStart);
1473 ID.AddPointer(Step);
1474 ID.AddPointer(L);
1475 void *IP = nullptr;
1476 const auto *PreAR =
1477 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1478
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001479 // Give up if we don't already have the add recurrence we need because
1480 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001481 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1482 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1483 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1484 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1485 DeltaS, &Pred, this);
1486 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1487 return true;
1488 }
1489 }
1490
1491 return false;
1492}
1493
Dan Gohmanaf752342009-07-07 17:06:11 +00001494const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001495 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001496 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001497 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001498 assert(isSCEVable(Ty) &&
1499 "This is not a conversion to a SCEVable type!");
1500 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001501
Dan Gohman3423e722009-06-30 20:13:32 +00001502 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001503 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1504 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001505 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001506
Dan Gohman79af8542009-04-22 16:20:48 +00001507 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001508 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001509 return getZeroExtendExpr(SZ->getOperand(), Ty);
1510
Dan Gohman74a0ba12009-07-13 20:55:53 +00001511 // Before doing any expensive analysis, check to see if we've already
1512 // computed a SCEV for this Op and Ty.
1513 FoldingSetNodeID ID;
1514 ID.AddInteger(scZeroExtend);
1515 ID.AddPointer(Op);
1516 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001517 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001518 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1519
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001520 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1521 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1522 // It's possible the bits taken off by the truncate were all zero bits. If
1523 // so, we should be able to simplify this further.
1524 const SCEV *X = ST->getOperand();
1525 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001526 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1527 unsigned NewBits = getTypeSizeInBits(Ty);
1528 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001529 CR.zextOrTrunc(NewBits)))
1530 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001531 }
1532
Dan Gohman76466372009-04-27 20:16:15 +00001533 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001534 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001535 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001536 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001537 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001538 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001539 const SCEV *Start = AR->getStart();
1540 const SCEV *Step = AR->getStepRecurrence(*this);
1541 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1542 const Loop *L = AR->getLoop();
1543
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001544 if (!AR->hasNoUnsignedWrap()) {
1545 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1546 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1547 }
1548
Dan Gohman62ef6a72009-07-25 01:22:26 +00001549 // If we have special knowledge that this addrec won't overflow,
1550 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001551 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001552 return getAddRecExpr(
1553 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1554 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001555
Dan Gohman76466372009-04-27 20:16:15 +00001556 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1557 // Note that this serves two purposes: It filters out loops that are
1558 // simply not analyzable, and it covers the case where this code is
1559 // being called from within backedge-taken count analysis, such that
1560 // attempting to ask for the backedge-taken count would likely result
1561 // in infinite recursion. In the later case, the analysis code will
1562 // cope with a conservative value, and it will take care to purge
1563 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001564 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001565 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001566 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001567 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001568
1569 // Check whether the backedge-taken count can be losslessly casted to
1570 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001571 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001572 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001573 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001574 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1575 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001576 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001577 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001578 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001579 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1580 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1581 const SCEV *WideMaxBECount =
1582 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001583 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001584 getAddExpr(WideStart,
1585 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001586 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001587 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001588 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001590 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001591 return getAddRecExpr(
1592 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1593 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001594 }
Dan Gohman76466372009-04-27 20:16:15 +00001595 // Similar to above, only this time treat the step value as signed.
1596 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001597 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001598 getAddExpr(WideStart,
1599 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001600 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001601 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001602 // Cache knowledge of AR NW, which is propagated to this AddRec.
1603 // Negative step causes unsigned wrap, but it still can't self-wrap.
1604 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001605 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001606 return getAddRecExpr(
1607 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1608 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001609 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001610 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001611 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001612
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001613 // Normally, in the cases we can prove no-overflow via a
1614 // backedge guarding condition, we can also compute a backedge
1615 // taken count for the loop. The exceptions are assumptions and
1616 // guards present in the loop -- SCEV is not great at exploiting
1617 // these to compute max backedge taken counts, but can still use
1618 // these to prove lack of overflow. Use this fact to avoid
1619 // doing extra work that may not pay off.
1620 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001621 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001622 // If the backedge is guarded by a comparison with the pre-inc
1623 // value the addrec is safe. Also, if the entry is guarded by
1624 // a comparison with the start value and the backedge is
1625 // guarded by a comparison with the post-inc value, the addrec
1626 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001627 if (isKnownPositive(Step)) {
1628 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1629 getUnsignedRange(Step).getUnsignedMax());
1630 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001631 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001632 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001633 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001634 // Cache knowledge of AR NUW, which is propagated to this
1635 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001636 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001637 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001638 return getAddRecExpr(
1639 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1640 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001641 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001642 } else if (isKnownNegative(Step)) {
1643 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1644 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001645 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1646 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001647 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001648 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001649 // Cache knowledge of AR NW, which is propagated to this
1650 // AddRec. Negative step causes unsigned wrap, but it
1651 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001652 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1653 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001654 return getAddRecExpr(
1655 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1656 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001657 }
Dan Gohman76466372009-04-27 20:16:15 +00001658 }
1659 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001660
1661 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1662 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1663 return getAddRecExpr(
1664 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1665 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1666 }
Dan Gohman76466372009-04-27 20:16:15 +00001667 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001668
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001669 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1670 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001671 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001672 // If the addition does not unsign overflow then we can, by definition,
1673 // commute the zero extension with the addition operation.
1674 SmallVector<const SCEV *, 4> Ops;
1675 for (const auto *Op : SA->operands())
1676 Ops.push_back(getZeroExtendExpr(Op, Ty));
1677 return getAddExpr(Ops, SCEV::FlagNUW);
1678 }
1679 }
1680
Dan Gohman74a0ba12009-07-13 20:55:53 +00001681 // The cast wasn't folded; create an explicit cast node.
1682 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001683 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001684 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1685 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001686 UniqueSCEVs.InsertNode(S, IP);
1687 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001688}
1689
Dan Gohmanaf752342009-07-07 17:06:11 +00001690const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001691 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001692 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001693 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001694 assert(isSCEVable(Ty) &&
1695 "This is not a conversion to a SCEVable type!");
1696 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001697
Dan Gohman3423e722009-06-30 20:13:32 +00001698 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001699 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1700 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001701 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001702
Dan Gohman79af8542009-04-22 16:20:48 +00001703 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001704 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001705 return getSignExtendExpr(SS->getOperand(), Ty);
1706
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001707 // sext(zext(x)) --> zext(x)
1708 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1709 return getZeroExtendExpr(SZ->getOperand(), Ty);
1710
Dan Gohman74a0ba12009-07-13 20:55:53 +00001711 // Before doing any expensive analysis, check to see if we've already
1712 // computed a SCEV for this Op and Ty.
1713 FoldingSetNodeID ID;
1714 ID.AddInteger(scSignExtend);
1715 ID.AddPointer(Op);
1716 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001717 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001718 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1719
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001720 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1721 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1722 // It's possible the bits taken off by the truncate were all sign bits. If
1723 // so, we should be able to simplify this further.
1724 const SCEV *X = ST->getOperand();
1725 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001726 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1727 unsigned NewBits = getTypeSizeInBits(Ty);
1728 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001729 CR.sextOrTrunc(NewBits)))
1730 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001731 }
1732
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001733 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001734 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001735 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001736 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1737 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001738 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001739 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001740 const APInt &C1 = SC1->getAPInt();
1741 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001742 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001743 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001744 return getAddExpr(getSignExtendExpr(SC1, Ty),
1745 getSignExtendExpr(SMul, Ty));
1746 }
1747 }
1748 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001749
1750 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001751 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001752 // If the addition does not sign overflow then we can, by definition,
1753 // commute the sign extension with the addition operation.
1754 SmallVector<const SCEV *, 4> Ops;
1755 for (const auto *Op : SA->operands())
1756 Ops.push_back(getSignExtendExpr(Op, Ty));
1757 return getAddExpr(Ops, SCEV::FlagNSW);
1758 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001759 }
Dan Gohman76466372009-04-27 20:16:15 +00001760 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001761 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001762 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001763 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001764 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001765 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001766 const SCEV *Start = AR->getStart();
1767 const SCEV *Step = AR->getStepRecurrence(*this);
1768 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1769 const Loop *L = AR->getLoop();
1770
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001771 if (!AR->hasNoSignedWrap()) {
1772 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1773 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1774 }
1775
Dan Gohman62ef6a72009-07-25 01:22:26 +00001776 // If we have special knowledge that this addrec won't overflow,
1777 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001778 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001779 return getAddRecExpr(
1780 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1781 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001782
Dan Gohman76466372009-04-27 20:16:15 +00001783 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1784 // Note that this serves two purposes: It filters out loops that are
1785 // simply not analyzable, and it covers the case where this code is
1786 // being called from within backedge-taken count analysis, such that
1787 // attempting to ask for the backedge-taken count would likely result
1788 // in infinite recursion. In the later case, the analysis code will
1789 // cope with a conservative value, and it will take care to purge
1790 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001791 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001792 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001793 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001794 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001795
1796 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001797 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001798 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001799 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001800 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001801 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1802 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001803 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001804 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001805 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001806 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1807 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1808 const SCEV *WideMaxBECount =
1809 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001810 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001811 getAddExpr(WideStart,
1812 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001813 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001814 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001815 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1816 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001817 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001818 return getAddRecExpr(
1819 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1820 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001821 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001822 // Similar to above, only this time treat the step value as unsigned.
1823 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001824 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001825 getAddExpr(WideStart,
1826 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001827 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001828 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001829 // If AR wraps around then
1830 //
1831 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1832 // => SAdd != OperandExtendedAdd
1833 //
1834 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1835 // (SAdd == OperandExtendedAdd => AR is NW)
1836
1837 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1838
Dan Gohman8c129d72009-07-16 17:34:36 +00001839 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001840 return getAddRecExpr(
1841 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1842 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001843 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001844 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001845 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001846
Sanjoy Das787c2462016-05-11 17:41:26 +00001847 // Normally, in the cases we can prove no-overflow via a
1848 // backedge guarding condition, we can also compute a backedge
1849 // taken count for the loop. The exceptions are assumptions and
1850 // guards present in the loop -- SCEV is not great at exploiting
1851 // these to compute max backedge taken counts, but can still use
1852 // these to prove lack of overflow. Use this fact to avoid
1853 // doing extra work that may not pay off.
1854
1855 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001856 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001857 // If the backedge is guarded by a comparison with the pre-inc
1858 // value the addrec is safe. Also, if the entry is guarded by
1859 // a comparison with the start value and the backedge is
1860 // guarded by a comparison with the post-inc value, the addrec
1861 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001862 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001863 const SCEV *OverflowLimit =
1864 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001865 if (OverflowLimit &&
1866 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1867 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1868 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1869 OverflowLimit)))) {
1870 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1871 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001872 return getAddRecExpr(
1873 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1874 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001875 }
1876 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001877
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001878 // If Start and Step are constants, check if we can apply this
1879 // transformation:
1880 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001881 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1882 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001883 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001884 const APInt &C1 = SC1->getAPInt();
1885 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001886 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1887 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001888 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001889 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1890 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001891 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1892 }
1893 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001894
1895 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1896 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1897 return getAddRecExpr(
1898 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1899 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1900 }
Dan Gohman76466372009-04-27 20:16:15 +00001901 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001902
Sanjoy Das11ef6062016-03-03 18:31:23 +00001903 // If the input value is provably positive and we could not simplify
1904 // away the sext build a zext instead.
1905 if (isKnownNonNegative(Op))
1906 return getZeroExtendExpr(Op, Ty);
1907
Dan Gohman74a0ba12009-07-13 20:55:53 +00001908 // The cast wasn't folded; create an explicit cast node.
1909 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001910 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001911 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1912 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001913 UniqueSCEVs.InsertNode(S, IP);
1914 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001915}
1916
Dan Gohman8db2edc2009-06-13 15:56:47 +00001917/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1918/// unspecified bits out to the given type.
1919///
Dan Gohmanaf752342009-07-07 17:06:11 +00001920const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001921 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001922 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1923 "This is not an extending conversion!");
1924 assert(isSCEVable(Ty) &&
1925 "This is not a conversion to a SCEVable type!");
1926 Ty = getEffectiveSCEVType(Ty);
1927
1928 // Sign-extend negative constants.
1929 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001930 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001931 return getSignExtendExpr(Op, Ty);
1932
1933 // Peel off a truncate cast.
1934 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001935 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001936 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1937 return getAnyExtendExpr(NewOp, Ty);
1938 return getTruncateOrNoop(NewOp, Ty);
1939 }
1940
1941 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001942 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001943 if (!isa<SCEVZeroExtendExpr>(ZExt))
1944 return ZExt;
1945
1946 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001947 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001948 if (!isa<SCEVSignExtendExpr>(SExt))
1949 return SExt;
1950
Dan Gohman51ad99d2010-01-21 02:09:26 +00001951 // Force the cast to be folded into the operands of an addrec.
1952 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1953 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001954 for (const SCEV *Op : AR->operands())
1955 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001956 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001957 }
1958
Dan Gohman8db2edc2009-06-13 15:56:47 +00001959 // If the expression is obviously signed, use the sext cast value.
1960 if (isa<SCEVSMaxExpr>(Op))
1961 return SExt;
1962
1963 // Absent any other information, use the zext cast value.
1964 return ZExt;
1965}
1966
Sanjoy Dasf8570812016-05-29 00:38:22 +00001967/// Process the given Ops list, which is a list of operands to be added under
1968/// the given scale, update the given map. This is a helper function for
1969/// getAddRecExpr. As an example of what it does, given a sequence of operands
1970/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001971///
Tobias Grosserba49e422014-03-05 10:37:17 +00001972/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001973///
1974/// where A and B are constants, update the map with these values:
1975///
1976/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1977///
1978/// and add 13 + A*B*29 to AccumulatedConstant.
1979/// This will allow getAddRecExpr to produce this:
1980///
1981/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1982///
1983/// This form often exposes folding opportunities that are hidden in
1984/// the original operand list.
1985///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001986/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001987/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1988/// the common case where no interesting opportunities are present, and
1989/// is also used as a check to avoid infinite recursion.
1990///
1991static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001992CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001993 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001994 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001995 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001996 const APInt &Scale,
1997 ScalarEvolution &SE) {
1998 bool Interesting = false;
1999
Dan Gohman45073042010-06-18 19:12:32 +00002000 // Iterate over the add operands. They are sorted, with constants first.
2001 unsigned i = 0;
2002 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2003 ++i;
2004 // Pull a buried constant out to the outside.
2005 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2006 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002007 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00002008 }
2009
2010 // Next comes everything else. We're especially interested in multiplies
2011 // here, but they're in the middle, so just visit the rest with one loop.
2012 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002013 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2014 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2015 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002016 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002017 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2018 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002019 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002020 Interesting |=
2021 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002022 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002023 NewScale, SE);
2024 } else {
2025 // A multiplication of a constant with some other value. Update
2026 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002027 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2028 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002029 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002030 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002031 NewOps.push_back(Pair.first->first);
2032 } else {
2033 Pair.first->second += NewScale;
2034 // The map already had an entry for this value, which may indicate
2035 // a folding opportunity.
2036 Interesting = true;
2037 }
2038 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002039 } else {
2040 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002041 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002042 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002043 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002044 NewOps.push_back(Pair.first->first);
2045 } else {
2046 Pair.first->second += Scale;
2047 // The map already had an entry for this value, which may indicate
2048 // a folding opportunity.
2049 Interesting = true;
2050 }
2051 }
2052 }
2053
2054 return Interesting;
2055}
2056
Sanjoy Das81401d42015-01-10 23:41:24 +00002057// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2058// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2059// can't-overflow flags for the operation if possible.
2060static SCEV::NoWrapFlags
2061StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2062 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002063 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002064 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002065 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002066
2067 bool CanAnalyze =
2068 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2069 (void)CanAnalyze;
2070 assert(CanAnalyze && "don't call from other places!");
2071
2072 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2073 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002074 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002075
2076 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002077 auto IsKnownNonNegative = [&](const SCEV *S) {
2078 return SE->isKnownNonNegative(S);
2079 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002080
Sanjoy Das3b827c72015-11-29 23:40:53 +00002081 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002082 Flags =
2083 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002084
Sanjoy Das8f274152015-10-22 19:57:19 +00002085 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2086
2087 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2088 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2089
2090 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2091 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2092
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002093 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002094 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002095 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2096 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002097 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2098 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2099 }
2100 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002101 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2102 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002103 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2104 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2105 }
2106 }
2107
2108 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002109}
2110
Sanjoy Dasf8570812016-05-29 00:38:22 +00002111/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002112const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002113 SCEV::NoWrapFlags Flags,
2114 unsigned Depth) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002115 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2116 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002117 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002118 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002119#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002120 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002121 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002122 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002123 "SCEVAddExpr operand types don't match!");
2124#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002125
2126 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002127 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002128
Sanjoy Das64895612015-10-09 02:44:45 +00002129 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2130
Chris Lattnerd934c702004-04-02 20:23:17 +00002131 // If there are any constants, fold them together.
2132 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002133 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002134 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002135 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002136 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002137 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002138 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002139 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002140 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002141 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002142 }
2143
2144 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002145 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002146 Ops.erase(Ops.begin());
2147 --Idx;
2148 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002149
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002150 if (Ops.size() == 1) return Ops[0];
2151 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002152
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002153 // Limit recursion calls depth
2154 if (Depth > MaxAddExprDepth)
2155 return getOrCreateAddExpr(Ops, Flags);
2156
Dan Gohman15871f22010-08-27 21:39:59 +00002157 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002158 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002159 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002160 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002161 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002162 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002163 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002164 // Scan ahead to count how many equal operands there are.
2165 unsigned Count = 2;
2166 while (i+Count != e && Ops[i+Count] == Ops[i])
2167 ++Count;
2168 // Merge the values into a multiply.
2169 const SCEV *Scale = getConstant(Ty, Count);
2170 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2171 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002172 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002173 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002174 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002175 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002176 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002177 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002178 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002179 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002180
Dan Gohman2e55cc52009-05-08 21:03:19 +00002181 // Check for truncates. If all the operands are truncated from the same
2182 // type, see if factoring out the truncate would permit the result to be
2183 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2184 // if the contents of the resulting outer trunc fold to something simple.
2185 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2186 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002187 Type *DstType = Trunc->getType();
2188 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002189 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002190 bool Ok = true;
2191 // Check all the operands to see if they can be represented in the
2192 // source type of the truncate.
2193 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2194 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2195 if (T->getOperand()->getType() != SrcType) {
2196 Ok = false;
2197 break;
2198 }
2199 LargeOps.push_back(T->getOperand());
2200 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002201 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002202 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002203 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002204 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2205 if (const SCEVTruncateExpr *T =
2206 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2207 if (T->getOperand()->getType() != SrcType) {
2208 Ok = false;
2209 break;
2210 }
2211 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002212 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002213 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002214 } else {
2215 Ok = false;
2216 break;
2217 }
2218 }
2219 if (Ok)
2220 LargeOps.push_back(getMulExpr(LargeMulOps));
2221 } else {
2222 Ok = false;
2223 break;
2224 }
2225 }
2226 if (Ok) {
2227 // Evaluate the expression in the larger type.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002228 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002229 // If it folds to something simple, use it. Otherwise, don't.
2230 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2231 return getTruncateExpr(Fold, DstType);
2232 }
2233 }
2234
2235 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2237 ++Idx;
2238
2239 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002240 if (Idx < Ops.size()) {
2241 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002242 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Daniil Fukalovb09dac52017-01-26 13:33:17 +00002243 if (Ops.size() > AddOpsInlineThreshold ||
2244 Add->getNumOperands() > AddOpsInlineThreshold)
2245 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002246 // If we have an add, expand the add operands onto the end of the operands
2247 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002248 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002249 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002250 DeletedAdd = true;
2251 }
2252
2253 // If we deleted at least one add, we added operands to the end of the list,
2254 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002255 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002256 if (DeletedAdd)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002257 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002258 }
2259
2260 // Skip over the add expression until we get to a multiply.
2261 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2262 ++Idx;
2263
Dan Gohman038d02e2009-06-14 22:58:51 +00002264 // Check to see if there are any folding opportunities present with
2265 // operands multiplied by constant values.
2266 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2267 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002268 DenseMap<const SCEV *, APInt> M;
2269 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002270 APInt AccumulatedConstant(BitWidth, 0);
2271 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002272 Ops.data(), Ops.size(),
2273 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002274 struct APIntCompare {
2275 bool operator()(const APInt &LHS, const APInt &RHS) const {
2276 return LHS.ult(RHS);
2277 }
2278 };
2279
Dan Gohman038d02e2009-06-14 22:58:51 +00002280 // Some interesting folding opportunity is present, so its worthwhile to
2281 // re-generate the operands list. Group the operands by constant scale,
2282 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002283 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002284 for (const SCEV *NewOp : NewOps)
2285 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002286 // Re-generate the operands list.
2287 Ops.clear();
2288 if (AccumulatedConstant != 0)
2289 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002290 for (auto &MulOp : MulOpLists)
2291 if (MulOp.first != 0)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002292 Ops.push_back(getMulExpr(
2293 getConstant(MulOp.first),
2294 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002295 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002296 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002297 if (Ops.size() == 1)
2298 return Ops[0];
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002299 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman038d02e2009-06-14 22:58:51 +00002300 }
2301 }
2302
Chris Lattnerd934c702004-04-02 20:23:17 +00002303 // If we are adding something to a multiply expression, make sure the
2304 // something is not already an operand of the multiply. If so, merge it into
2305 // the multiply.
2306 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002307 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002308 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002309 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002310 if (isa<SCEVConstant>(MulOpSCEV))
2311 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002312 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002313 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002314 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002315 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002316 if (Mul->getNumOperands() != 2) {
2317 // If the multiply has more than two operands, we must get the
2318 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002319 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2320 Mul->op_begin()+MulOp);
2321 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002322 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002323 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002324 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2325 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman157847f2010-08-12 14:52:55 +00002326 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002327 if (Ops.size() == 2) return OuterMul;
2328 if (AddOp < Idx) {
2329 Ops.erase(Ops.begin()+AddOp);
2330 Ops.erase(Ops.begin()+Idx-1);
2331 } else {
2332 Ops.erase(Ops.begin()+Idx);
2333 Ops.erase(Ops.begin()+AddOp-1);
2334 }
2335 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002336 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002337 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002338
Chris Lattnerd934c702004-04-02 20:23:17 +00002339 // Check this multiply against other multiplies being added together.
2340 for (unsigned OtherMulIdx = Idx+1;
2341 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2342 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002343 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002344 // If MulOp occurs in OtherMul, we can fold the two multiplies
2345 // together.
2346 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2347 OMulOp != e; ++OMulOp)
2348 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2349 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002350 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002351 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002352 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002353 Mul->op_begin()+MulOp);
2354 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002355 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002356 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002357 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002358 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002359 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002360 OtherMul->op_begin()+OMulOp);
2361 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002362 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002363 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002364 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2365 const SCEV *InnerMulSum =
2366 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanaf752342009-07-07 17:06:11 +00002367 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002368 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002369 Ops.erase(Ops.begin()+Idx);
2370 Ops.erase(Ops.begin()+OtherMulIdx-1);
2371 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002372 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002373 }
2374 }
2375 }
2376 }
2377
2378 // If there are any add recurrences in the operands list, see if any other
2379 // added values are loop invariant. If so, we can fold them into the
2380 // recurrence.
2381 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2382 ++Idx;
2383
2384 // Scan over all recurrences, trying to fold loop invariants into them.
2385 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2386 // Scan all of the other operands to this add and add them to the vector if
2387 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002388 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002389 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002390 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002391 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002392 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002393 LIOps.push_back(Ops[i]);
2394 Ops.erase(Ops.begin()+i);
2395 --i; --e;
2396 }
2397
2398 // If we found some loop invariants, fold them into the recurrence.
2399 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002400 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002401 LIOps.push_back(AddRec->getStart());
2402
Dan Gohmanaf752342009-07-07 17:06:11 +00002403 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002404 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002405 // This follows from the fact that the no-wrap flags on the outer add
2406 // expression are applicable on the 0th iteration, when the add recurrence
2407 // will be equal to its start value.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002408 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002409
Dan Gohman16206132010-06-30 07:16:37 +00002410 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002411 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002412 // Always propagate NW.
2413 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002414 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002415
Chris Lattnerd934c702004-04-02 20:23:17 +00002416 // If all of the other operands were loop invariant, we are done.
2417 if (Ops.size() == 1) return NewRec;
2418
Nick Lewyckydb66b822011-09-06 05:08:09 +00002419 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002420 for (unsigned i = 0;; ++i)
2421 if (Ops[i] == AddRec) {
2422 Ops[i] = NewRec;
2423 break;
2424 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002425 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002426 }
2427
2428 // Okay, if there weren't any loop invariants to be folded, check to see if
2429 // there are multiple AddRec's with the same loop induction variable being
2430 // added together. If so, we can fold them.
2431 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002432 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2433 ++OtherIdx)
2434 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2435 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2436 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2437 AddRec->op_end());
2438 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2439 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002440 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002441 if (OtherAddRec->getLoop() == AddRecLoop) {
2442 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2443 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002444 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002445 AddRecOps.append(OtherAddRec->op_begin()+i,
2446 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002447 break;
2448 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002449 SmallVector<const SCEV *, 2> TwoOps = {
2450 AddRecOps[i], OtherAddRec->getOperand(i)};
2451 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002452 }
2453 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002454 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002455 // Step size has changed, so we cannot guarantee no self-wraparound.
2456 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002457 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002458 }
2459
2460 // Otherwise couldn't fold anything into this recurrence. Move onto the
2461 // next one.
2462 }
2463
2464 // Okay, it looks like we really DO need an add expr. Check to see if we
2465 // already have one, otherwise create a new one.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002466 return getOrCreateAddExpr(Ops, Flags);
2467}
2468
2469const SCEV *
2470ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2471 SCEV::NoWrapFlags Flags) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002472 FoldingSetNodeID ID;
2473 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002474 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2475 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002476 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002477 SCEVAddExpr *S =
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002478 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
Dan Gohman51ad99d2010-01-21 02:09:26 +00002479 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002480 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2481 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002482 S = new (SCEVAllocator)
2483 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002484 UniqueSCEVs.InsertNode(S, IP);
2485 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002486 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002487 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002488}
2489
Nick Lewycky287682e2011-10-04 06:51:26 +00002490static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2491 uint64_t k = i*j;
2492 if (j > 1 && k / j != i) Overflow = true;
2493 return k;
2494}
2495
2496/// Compute the result of "n choose k", the binomial coefficient. If an
2497/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002498/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002499static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2500 // We use the multiplicative formula:
2501 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2502 // At each iteration, we take the n-th term of the numeral and divide by the
2503 // (k-n)th term of the denominator. This division will always produce an
2504 // integral result, and helps reduce the chance of overflow in the
2505 // intermediate computations. However, we can still overflow even when the
2506 // final result would fit.
2507
2508 if (n == 0 || n == k) return 1;
2509 if (k > n) return 0;
2510
2511 if (k > n/2)
2512 k = n-k;
2513
2514 uint64_t r = 1;
2515 for (uint64_t i = 1; i <= k; ++i) {
2516 r = umul_ov(r, n-(i-1), Overflow);
2517 r /= i;
2518 }
2519 return r;
2520}
2521
Nick Lewycky05044c22014-12-06 00:45:50 +00002522/// Determine if any of the operands in this SCEV are a constant or if
2523/// any of the add or multiply expressions in this SCEV contain a constant.
2524static bool containsConstantSomewhere(const SCEV *StartExpr) {
2525 SmallVector<const SCEV *, 4> Ops;
2526 Ops.push_back(StartExpr);
2527 while (!Ops.empty()) {
2528 const SCEV *CurrentExpr = Ops.pop_back_val();
2529 if (isa<SCEVConstant>(*CurrentExpr))
2530 return true;
2531
2532 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2533 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002534 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002535 }
2536 }
2537 return false;
2538}
2539
Sanjoy Dasf8570812016-05-29 00:38:22 +00002540/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002541const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002542 SCEV::NoWrapFlags Flags) {
2543 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2544 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002545 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002546 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002547#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002548 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002549 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002550 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002551 "SCEVMulExpr operand types don't match!");
2552#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002553
2554 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002555 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002556
Sanjoy Das64895612015-10-09 02:44:45 +00002557 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2558
Chris Lattnerd934c702004-04-02 20:23:17 +00002559 // If there are any constants, fold them together.
2560 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002561 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002562
2563 // C1*(C2+V) -> C1*C2 + C1*V
2564 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002565 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2566 // If any of Add's ops are Adds or Muls with a constant,
2567 // apply this transformation as well.
2568 if (Add->getNumOperands() == 2)
2569 if (containsConstantSomewhere(Add))
2570 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2571 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002572
Chris Lattnerd934c702004-04-02 20:23:17 +00002573 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002574 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002575 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002576 ConstantInt *Fold =
2577 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002578 Ops[0] = getConstant(Fold);
2579 Ops.erase(Ops.begin()+1); // Erase the folded element
2580 if (Ops.size() == 1) return Ops[0];
2581 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002582 }
2583
2584 // If we are left with a constant one being multiplied, strip it off.
2585 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2586 Ops.erase(Ops.begin());
2587 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002588 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002589 // If we have a multiply of zero, it will always be zero.
2590 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002591 } else if (Ops[0]->isAllOnesValue()) {
2592 // If we have a mul by -1 of an add, try distributing the -1 among the
2593 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002594 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002595 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2596 SmallVector<const SCEV *, 4> NewOps;
2597 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002598 for (const SCEV *AddOp : Add->operands()) {
2599 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002600 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2601 NewOps.push_back(Mul);
2602 }
2603 if (AnyFolded)
2604 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002605 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002606 // Negation preserves a recurrence's no self-wrap property.
2607 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002608 for (const SCEV *AddRecOp : AddRec->operands())
2609 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2610
Andrew Tricke92dcce2011-03-14 17:38:54 +00002611 return getAddRecExpr(Operands, AddRec->getLoop(),
2612 AddRec->getNoWrapFlags(SCEV::FlagNW));
2613 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002614 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002615 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002616
2617 if (Ops.size() == 1)
2618 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002619 }
2620
2621 // Skip over the add expression until we get to a multiply.
2622 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2623 ++Idx;
2624
Chris Lattnerd934c702004-04-02 20:23:17 +00002625 // If there are mul operands inline them all into this expression.
2626 if (Idx < Ops.size()) {
2627 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002628 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002629 if (Ops.size() > MulOpsInlineThreshold)
2630 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002631 // If we have an mul, expand the mul operands onto the end of the operands
2632 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002633 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002634 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002635 DeletedMul = true;
2636 }
2637
2638 // If we deleted at least one mul, we added operands to the end of the list,
2639 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002640 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002641 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002642 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002643 }
2644
2645 // If there are any add recurrences in the operands list, see if any other
2646 // added values are loop invariant. If so, we can fold them into the
2647 // recurrence.
2648 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2649 ++Idx;
2650
2651 // Scan over all recurrences, trying to fold loop invariants into them.
2652 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2653 // Scan all of the other operands to this mul and add them to the vector if
2654 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002655 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002656 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002657 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002658 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002659 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002660 LIOps.push_back(Ops[i]);
2661 Ops.erase(Ops.begin()+i);
2662 --i; --e;
2663 }
2664
2665 // If we found some loop invariants, fold them into the recurrence.
2666 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002667 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002668 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002669 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002670 const SCEV *Scale = getMulExpr(LIOps);
2671 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2672 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002673
Dan Gohman16206132010-06-30 07:16:37 +00002674 // Build the new addrec. Propagate the NUW and NSW flags if both the
2675 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002676 //
2677 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002678 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002679 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2680 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002681
2682 // If all of the other operands were loop invariant, we are done.
2683 if (Ops.size() == 1) return NewRec;
2684
Nick Lewyckydb66b822011-09-06 05:08:09 +00002685 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002686 for (unsigned i = 0;; ++i)
2687 if (Ops[i] == AddRec) {
2688 Ops[i] = NewRec;
2689 break;
2690 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002691 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002692 }
2693
2694 // Okay, if there weren't any loop invariants to be folded, check to see if
2695 // there are multiple AddRec's with the same loop induction variable being
2696 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002697
2698 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2699 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2700 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2701 // ]]],+,...up to x=2n}.
2702 // Note that the arguments to choose() are always integers with values
2703 // known at compile time, never SCEV objects.
2704 //
2705 // The implementation avoids pointless extra computations when the two
2706 // addrec's are of different length (mathematically, it's equivalent to
2707 // an infinite stream of zeros on the right).
2708 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002709 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002710 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002711 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002712 const SCEVAddRecExpr *OtherAddRec =
2713 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2714 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002715 continue;
2716
Nick Lewycky97756402014-09-01 05:17:15 +00002717 bool Overflow = false;
2718 Type *Ty = AddRec->getType();
2719 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2720 SmallVector<const SCEV*, 7> AddRecOps;
2721 for (int x = 0, xe = AddRec->getNumOperands() +
2722 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002723 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002724 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2725 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2726 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2727 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2728 z < ze && !Overflow; ++z) {
2729 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2730 uint64_t Coeff;
2731 if (LargerThan64Bits)
2732 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2733 else
2734 Coeff = Coeff1*Coeff2;
2735 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2736 const SCEV *Term1 = AddRec->getOperand(y-z);
2737 const SCEV *Term2 = OtherAddRec->getOperand(z);
2738 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002739 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002740 }
Nick Lewycky97756402014-09-01 05:17:15 +00002741 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002742 }
Nick Lewycky97756402014-09-01 05:17:15 +00002743 if (!Overflow) {
2744 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2745 SCEV::FlagAnyWrap);
2746 if (Ops.size() == 2) return NewAddRec;
2747 Ops[Idx] = NewAddRec;
2748 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2749 OpsModified = true;
2750 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2751 if (!AddRec)
2752 break;
2753 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002754 }
Nick Lewycky97756402014-09-01 05:17:15 +00002755 if (OpsModified)
2756 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002757
2758 // Otherwise couldn't fold anything into this recurrence. Move onto the
2759 // next one.
2760 }
2761
2762 // Okay, it looks like we really DO need an mul expr. Check to see if we
2763 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002764 FoldingSetNodeID ID;
2765 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002766 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2767 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002768 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002769 SCEVMulExpr *S =
2770 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2771 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002772 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2773 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002774 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2775 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002776 UniqueSCEVs.InsertNode(S, IP);
2777 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002778 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002779 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002780}
2781
Sanjoy Dasf8570812016-05-29 00:38:22 +00002782/// Get a canonical unsigned division expression, or something simpler if
2783/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002784const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2785 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002786 assert(getEffectiveSCEVType(LHS->getType()) ==
2787 getEffectiveSCEVType(RHS->getType()) &&
2788 "SCEVUDivExpr operand types don't match!");
2789
Dan Gohmana30370b2009-05-04 22:02:23 +00002790 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002791 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002792 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002793 // If the denominator is zero, the result of the udiv is undefined. Don't
2794 // try to analyze it, because the resolution chosen here may differ from
2795 // the resolution chosen in other parts of the compiler.
2796 if (!RHSC->getValue()->isZero()) {
2797 // Determine if the division can be folded into the operands of
2798 // its operands.
2799 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002800 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002801 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002802 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002803 // For non-power-of-two values, effectively round the value up to the
2804 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002805 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002806 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002807 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002808 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002809 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2810 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002811 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2812 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002813 const APInt &StepInt = Step->getAPInt();
2814 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002815 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002816 getZeroExtendExpr(AR, ExtTy) ==
2817 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2818 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002819 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002820 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002821 for (const SCEV *Op : AR->operands())
2822 Operands.push_back(getUDivExpr(Op, RHS));
2823 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002824 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002825 /// Get a canonical UDivExpr for a recurrence.
2826 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2827 // We can currently only fold X%N if X is constant.
2828 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2829 if (StartC && !DivInt.urem(StepInt) &&
2830 getZeroExtendExpr(AR, ExtTy) ==
2831 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2832 getZeroExtendExpr(Step, ExtTy),
2833 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002834 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002835 const APInt &StartRem = StartInt.urem(StepInt);
2836 if (StartRem != 0)
2837 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2838 AR->getLoop(), SCEV::FlagNW);
2839 }
2840 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002841 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2842 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2843 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002844 for (const SCEV *Op : M->operands())
2845 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002846 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2847 // Find an operand that's safely divisible.
2848 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2849 const SCEV *Op = M->getOperand(i);
2850 const SCEV *Div = getUDivExpr(Op, RHSC);
2851 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2852 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2853 M->op_end());
2854 Operands[i] = Div;
2855 return getMulExpr(Operands);
2856 }
2857 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002858 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002859 // (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 +00002860 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002861 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002862 for (const SCEV *Op : A->operands())
2863 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002864 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2865 Operands.clear();
2866 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2867 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2868 if (isa<SCEVUDivExpr>(Op) ||
2869 getMulExpr(Op, RHS) != A->getOperand(i))
2870 break;
2871 Operands.push_back(Op);
2872 }
2873 if (Operands.size() == A->getNumOperands())
2874 return getAddExpr(Operands);
2875 }
2876 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002877
Dan Gohmanacd700a2010-04-22 01:35:11 +00002878 // Fold if both operands are constant.
2879 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2880 Constant *LHSCV = LHSC->getValue();
2881 Constant *RHSCV = RHSC->getValue();
2882 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2883 RHSCV)));
2884 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002885 }
2886 }
2887
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002888 FoldingSetNodeID ID;
2889 ID.AddInteger(scUDivExpr);
2890 ID.AddPointer(LHS);
2891 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002892 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002893 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002894 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2895 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002896 UniqueSCEVs.InsertNode(S, IP);
2897 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002898}
2899
Nick Lewycky31eaca52014-01-27 10:04:03 +00002900static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002901 APInt A = C1->getAPInt().abs();
2902 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002903 uint32_t ABW = A.getBitWidth();
2904 uint32_t BBW = B.getBitWidth();
2905
2906 if (ABW > BBW)
2907 B = B.zext(ABW);
2908 else if (ABW < BBW)
2909 A = A.zext(BBW);
2910
2911 return APIntOps::GreatestCommonDivisor(A, B);
2912}
2913
Sanjoy Dasf8570812016-05-29 00:38:22 +00002914/// Get a canonical unsigned division expression, or something simpler if
2915/// possible. There is no representation for an exact udiv in SCEV IR, but we
2916/// can attempt to remove factors from the LHS and RHS. We can't do this when
2917/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002918const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2919 const SCEV *RHS) {
2920 // TODO: we could try to find factors in all sorts of things, but for now we
2921 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2922 // end of this file for inspiration.
2923
2924 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
Eli Friedmanf1f49c82017-01-18 23:56:42 +00002925 if (!Mul || !Mul->hasNoUnsignedWrap())
Nick Lewycky31eaca52014-01-27 10:04:03 +00002926 return getUDivExpr(LHS, RHS);
2927
2928 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2929 // If the mulexpr multiplies by a constant, then that constant must be the
2930 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002931 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002932 if (LHSCst == RHSCst) {
2933 SmallVector<const SCEV *, 2> Operands;
2934 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2935 return getMulExpr(Operands);
2936 }
2937
2938 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2939 // that there's a factor provided by one of the other terms. We need to
2940 // check.
2941 APInt Factor = gcd(LHSCst, RHSCst);
2942 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002943 LHSCst =
2944 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2945 RHSCst =
2946 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002947 SmallVector<const SCEV *, 2> Operands;
2948 Operands.push_back(LHSCst);
2949 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2950 LHS = getMulExpr(Operands);
2951 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002952 Mul = dyn_cast<SCEVMulExpr>(LHS);
2953 if (!Mul)
2954 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002955 }
2956 }
2957 }
2958
2959 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2960 if (Mul->getOperand(i) == RHS) {
2961 SmallVector<const SCEV *, 2> Operands;
2962 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2963 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2964 return getMulExpr(Operands);
2965 }
2966 }
2967
2968 return getUDivExpr(LHS, RHS);
2969}
Chris Lattnerd934c702004-04-02 20:23:17 +00002970
Sanjoy Dasf8570812016-05-29 00:38:22 +00002971/// Get an add recurrence expression for the specified loop. Simplify the
2972/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002973const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2974 const Loop *L,
2975 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002976 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002977 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002978 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002979 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002980 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002981 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002982 }
2983
2984 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002985 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002986}
2987
Sanjoy Dasf8570812016-05-29 00:38:22 +00002988/// Get an add recurrence expression for the specified loop. Simplify the
2989/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002990const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002991ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002992 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002993 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002994#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002995 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002996 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002997 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002998 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002999 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00003000 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003001 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00003002#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00003003
Dan Gohmanbe928e32008-06-18 16:23:07 +00003004 if (Operands.back()->isZero()) {
3005 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00003006 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00003007 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003008
Dan Gohmancf9c64e2010-02-19 18:49:22 +00003009 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3010 // use that information to infer NUW and NSW flags. However, computing a
3011 // BE count requires calling getAddRecExpr, so we may not yet have a
3012 // meaningful BE count at this point (and if we don't, we'd be stuck
3013 // with a SCEVCouldNotCompute as the cached BE count).
3014
Sanjoy Das81401d42015-01-10 23:41:24 +00003015 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003016
Dan Gohman223a5d22008-08-08 18:33:12 +00003017 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00003018 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00003019 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003020 if (L->contains(NestedLoop)
3021 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3022 : (!NestedLoop->contains(L) &&
3023 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003024 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00003025 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00003026 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00003027 // AddRecs require their operands be loop-invariant with respect to their
3028 // loops. Don't perform this transformation if it would break this
3029 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00003030 bool AllInvariant = all_of(
3031 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003032
Dan Gohmancc030b72009-06-26 22:36:20 +00003033 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003034 // Create a recurrence for the outer loop with the same step size.
3035 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003036 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3037 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003038 SCEV::NoWrapFlags OuterFlags =
3039 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003040
3041 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003042 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3043 return isLoopInvariant(Op, NestedLoop);
3044 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003045
Andrew Trick8b55b732011-03-14 16:50:06 +00003046 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003047 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003048 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003049 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3050 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003051 SCEV::NoWrapFlags InnerFlags =
3052 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003053 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3054 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003055 }
3056 // Reset Operands to its original state.
3057 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003058 }
3059 }
3060
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003061 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3062 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003063 FoldingSetNodeID ID;
3064 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003065 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3066 ID.AddPointer(Operands[i]);
3067 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003068 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003069 SCEVAddRecExpr *S =
3070 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3071 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003072 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3073 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003074 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3075 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003076 UniqueSCEVs.InsertNode(S, IP);
3077 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003078 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003079 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003080}
3081
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003082const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003083ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3084 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3085 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003086 // getSCEV(Base)->getType() has the same address space as Base->getType()
3087 // because SCEV::getType() preserves the address space.
3088 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3089 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3090 // instruction to its SCEV, because the Instruction may be guarded by control
3091 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003092 // context. This can be fixed similarly to how these flags are handled for
3093 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003094 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3095 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003096
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003097 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003098 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003099 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003100 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003101 for (const SCEV *IndexExpr : IndexExprs) {
3102 // Compute the (potentially symbolic) offset in bytes for this index.
3103 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3104 // For a struct, add the member offset.
3105 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3106 unsigned FieldNo = Index->getZExtValue();
3107 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3108
3109 // Add the field offset to the running total offset.
3110 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3111
3112 // Update CurTy to the type of the field at Index.
3113 CurTy = STy->getTypeAtIndex(Index);
3114 } else {
3115 // Update CurTy to its element type.
3116 CurTy = cast<SequentialType>(CurTy)->getElementType();
3117 // For an array, add the element offset, explicitly scaled.
3118 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3119 // Getelementptr indices are signed.
3120 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3121
3122 // Multiply the index by the element size to compute the element offset.
3123 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3124
3125 // Add the element offset to the running total offset.
3126 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3127 }
3128 }
3129
3130 // Add the total offset from all the GEP indices to the base.
3131 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3132}
3133
Dan Gohmanabd17092009-06-24 14:49:00 +00003134const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3135 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003136 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003137 return getSMaxExpr(Ops);
3138}
3139
Dan Gohmanaf752342009-07-07 17:06:11 +00003140const SCEV *
3141ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003142 assert(!Ops.empty() && "Cannot get empty smax!");
3143 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003144#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003145 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003146 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003147 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003148 "SCEVSMaxExpr operand types don't match!");
3149#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003150
3151 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003152 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003153
3154 // If there are any constants, fold them together.
3155 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003156 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003157 ++Idx;
3158 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003159 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003160 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003161 ConstantInt *Fold = ConstantInt::get(
3162 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003163 Ops[0] = getConstant(Fold);
3164 Ops.erase(Ops.begin()+1); // Erase the folded element
3165 if (Ops.size() == 1) return Ops[0];
3166 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003167 }
3168
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003169 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003170 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3171 Ops.erase(Ops.begin());
3172 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003173 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3174 // If we have an smax with a constant maximum-int, it will always be
3175 // maximum-int.
3176 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003177 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003178
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003179 if (Ops.size() == 1) return Ops[0];
3180 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003181
3182 // Find the first SMax
3183 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3184 ++Idx;
3185
3186 // Check to see if one of the operands is an SMax. If so, expand its operands
3187 // onto our operand list, and recurse to simplify.
3188 if (Idx < Ops.size()) {
3189 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003190 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003191 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003192 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003193 DeletedSMax = true;
3194 }
3195
3196 if (DeletedSMax)
3197 return getSMaxExpr(Ops);
3198 }
3199
3200 // Okay, check to see if the same value occurs in the operand list twice. If
3201 // so, delete one. Since we sorted the list, these values are required to
3202 // be adjacent.
3203 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003204 // X smax Y smax Y --> X smax Y
3205 // X smax Y --> X, if X is always greater than Y
3206 if (Ops[i] == Ops[i+1] ||
3207 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3208 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3209 --i; --e;
3210 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003211 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3212 --i; --e;
3213 }
3214
3215 if (Ops.size() == 1) return Ops[0];
3216
3217 assert(!Ops.empty() && "Reduced smax down to nothing!");
3218
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003219 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003220 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003221 FoldingSetNodeID ID;
3222 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003223 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3224 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003225 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003226 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003227 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3228 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003229 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3230 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003231 UniqueSCEVs.InsertNode(S, IP);
3232 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003233}
3234
Dan Gohmanabd17092009-06-24 14:49:00 +00003235const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3236 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003237 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003238 return getUMaxExpr(Ops);
3239}
3240
Dan Gohmanaf752342009-07-07 17:06:11 +00003241const SCEV *
3242ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003243 assert(!Ops.empty() && "Cannot get empty umax!");
3244 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003245#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003246 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003247 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003248 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003249 "SCEVUMaxExpr operand types don't match!");
3250#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003251
3252 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003253 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003254
3255 // If there are any constants, fold them together.
3256 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003257 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003258 ++Idx;
3259 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003260 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003261 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003262 ConstantInt *Fold = ConstantInt::get(
3263 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003264 Ops[0] = getConstant(Fold);
3265 Ops.erase(Ops.begin()+1); // Erase the folded element
3266 if (Ops.size() == 1) return Ops[0];
3267 LHSC = cast<SCEVConstant>(Ops[0]);
3268 }
3269
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003270 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003271 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3272 Ops.erase(Ops.begin());
3273 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003274 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3275 // If we have an umax with a constant maximum-int, it will always be
3276 // maximum-int.
3277 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003278 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003279
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003280 if (Ops.size() == 1) return Ops[0];
3281 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003282
3283 // Find the first UMax
3284 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3285 ++Idx;
3286
3287 // Check to see if one of the operands is a UMax. If so, expand its operands
3288 // onto our operand list, and recurse to simplify.
3289 if (Idx < Ops.size()) {
3290 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003291 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003292 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003293 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003294 DeletedUMax = true;
3295 }
3296
3297 if (DeletedUMax)
3298 return getUMaxExpr(Ops);
3299 }
3300
3301 // Okay, check to see if the same value occurs in the operand list twice. If
3302 // so, delete one. Since we sorted the list, these values are required to
3303 // be adjacent.
3304 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003305 // X umax Y umax Y --> X umax Y
3306 // X umax Y --> X, if X is always greater than Y
3307 if (Ops[i] == Ops[i+1] ||
3308 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3309 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3310 --i; --e;
3311 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003312 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3313 --i; --e;
3314 }
3315
3316 if (Ops.size() == 1) return Ops[0];
3317
3318 assert(!Ops.empty() && "Reduced umax down to nothing!");
3319
3320 // Okay, it looks like we really DO need a umax expr. Check to see if we
3321 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003322 FoldingSetNodeID ID;
3323 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003324 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3325 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003326 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003327 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003328 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3329 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003330 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3331 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003332 UniqueSCEVs.InsertNode(S, IP);
3333 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003334}
3335
Dan Gohmanabd17092009-06-24 14:49:00 +00003336const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3337 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003338 // ~smax(~x, ~y) == smin(x, y).
3339 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3340}
3341
Dan Gohmanabd17092009-06-24 14:49:00 +00003342const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3343 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003344 // ~umax(~x, ~y) == umin(x, y)
3345 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3346}
3347
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003348const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003349 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003350 // constant expression and then folding it back into a ConstantInt.
3351 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003352 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003353}
3354
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003355const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3356 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003357 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003358 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003359 // constant expression and then folding it back into a ConstantInt.
3360 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003361 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003362 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003363}
3364
Dan Gohmanaf752342009-07-07 17:06:11 +00003365const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003366 // Don't attempt to do anything other than create a SCEVUnknown object
3367 // here. createSCEV only calls getUnknown after checking for all other
3368 // interesting possibilities, and any other code that calls getUnknown
3369 // is doing so in order to hide a value from SCEV canonicalization.
3370
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003371 FoldingSetNodeID ID;
3372 ID.AddInteger(scUnknown);
3373 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003374 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003375 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3376 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3377 "Stale SCEVUnknown in uniquing map!");
3378 return S;
3379 }
3380 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3381 FirstUnknown);
3382 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003383 UniqueSCEVs.InsertNode(S, IP);
3384 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003385}
3386
Chris Lattnerd934c702004-04-02 20:23:17 +00003387//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003388// Basic SCEV Analysis and PHI Idiom Recognition Code
3389//
3390
Sanjoy Dasf8570812016-05-29 00:38:22 +00003391/// Test if values of the given type are analyzable within the SCEV
3392/// framework. This primarily includes integer types, and it can optionally
3393/// include pointer types if the ScalarEvolution class has access to
3394/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003395bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003396 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003397 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003398}
3399
Sanjoy Dasf8570812016-05-29 00:38:22 +00003400/// Return the size in bits of the specified type, for which isSCEVable must
3401/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003402uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003403 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003404 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003405}
3406
Sanjoy Dasf8570812016-05-29 00:38:22 +00003407/// Return a type with the same bitwidth as the given type and which represents
3408/// how SCEV will treat the given type, for which isSCEVable must return
3409/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003410Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003411 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3412
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003413 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003414 return Ty;
3415
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003416 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003417 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003418 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003419}
Chris Lattnerd934c702004-04-02 20:23:17 +00003420
Dan Gohmanaf752342009-07-07 17:06:11 +00003421const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003422 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003423}
3424
Sanjoy Das7d752672015-12-08 04:32:54 +00003425bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003426 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3427 auto *SU = dyn_cast<SCEVUnknown>(S);
3428 return SU && SU->getValue() == nullptr;
3429 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003430
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003431 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003432}
3433
Wei Mia49559b2016-02-04 01:27:38 +00003434bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003435 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003436 if (I != HasRecMap.end())
3437 return I->second;
3438
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003439 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003440 HasRecMap.insert({S, FoundAddRec});
3441 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003442}
3443
Wei Mi785858c2016-08-09 20:37:50 +00003444/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3445/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3446/// offset I, then return {S', I}, else return {\p S, nullptr}.
3447static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3448 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3449 if (!Add)
3450 return {S, nullptr};
3451
3452 if (Add->getNumOperands() != 2)
3453 return {S, nullptr};
3454
3455 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3456 if (!ConstOp)
3457 return {S, nullptr};
3458
3459 return {Add->getOperand(1), ConstOp->getValue()};
3460}
3461
3462/// Return the ValueOffsetPair set for \p S. \p S can be represented
3463/// by the value and offset from any ValueOffsetPair in the set.
3464SetVector<ScalarEvolution::ValueOffsetPair> *
3465ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003466 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3467 if (SI == ExprValueMap.end())
3468 return nullptr;
3469#ifndef NDEBUG
3470 if (VerifySCEVMap) {
3471 // Check there is no dangling Value in the set returned.
3472 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003473 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003474 }
3475#endif
3476 return &SI->second;
3477}
3478
Wei Mi785858c2016-08-09 20:37:50 +00003479/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3480/// cannot be used separately. eraseValueFromMap should be used to remove
3481/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003482void ScalarEvolution::eraseValueFromMap(Value *V) {
3483 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3484 if (I != ValueExprMap.end()) {
3485 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003486 // Remove {V, 0} from the set of ExprValueMap[S]
3487 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3488 SV->remove({V, nullptr});
3489
3490 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3491 const SCEV *Stripped;
3492 ConstantInt *Offset;
3493 std::tie(Stripped, Offset) = splitAddExpr(S);
3494 if (Offset != nullptr) {
3495 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3496 SV->remove({V, Offset});
3497 }
Wei Mia49559b2016-02-04 01:27:38 +00003498 ValueExprMap.erase(V);
3499 }
3500}
3501
Sanjoy Dasf8570812016-05-29 00:38:22 +00003502/// Return an existing SCEV if it exists, otherwise analyze the expression and
3503/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003504const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003505 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003506
Jingyue Wu42f1d672015-07-28 18:22:40 +00003507 const SCEV *S = getExistingSCEV(V);
3508 if (S == nullptr) {
3509 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003510 // During PHI resolution, it is possible to create two SCEVs for the same
3511 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003512 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003513 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003514 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003515 if (Pair.second) {
3516 ExprValueMap[S].insert({V, nullptr});
3517
3518 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3519 // ExprValueMap.
3520 const SCEV *Stripped = S;
3521 ConstantInt *Offset = nullptr;
3522 std::tie(Stripped, Offset) = splitAddExpr(S);
3523 // If stripped is SCEVUnknown, don't bother to save
3524 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3525 // increase the complexity of the expansion code.
3526 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3527 // because it may generate add/sub instead of GEP in SCEV expansion.
3528 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3529 !isa<GetElementPtrInst>(V))
3530 ExprValueMap[Stripped].insert({V, Offset});
3531 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003532 }
3533 return S;
3534}
3535
3536const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3537 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3538
Shuxin Yangefc4c012013-07-08 17:33:13 +00003539 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3540 if (I != ValueExprMap.end()) {
3541 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003542 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003543 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003544 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003545 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003546 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003547 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003548}
3549
Sanjoy Dasf8570812016-05-29 00:38:22 +00003550/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003551///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003552const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3553 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003554 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003555 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003556 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003557
Chris Lattner229907c2011-07-18 04:54:35 +00003558 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003559 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003560 return getMulExpr(
3561 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003562}
3563
Sanjoy Dasf8570812016-05-29 00:38:22 +00003564/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003565const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003566 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003567 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003568 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003569
Chris Lattner229907c2011-07-18 04:54:35 +00003570 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003571 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003572 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003573 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003574 return getMinusSCEV(AllOnes, V);
3575}
3576
Chris Lattnerfc877522011-01-09 22:26:35 +00003577const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003578 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003579 // Fast path: X - X --> 0.
3580 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003581 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003582
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003583 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3584 // makes it so that we cannot make much use of NUW.
3585 auto AddFlags = SCEV::FlagAnyWrap;
3586 const bool RHSIsNotMinSigned =
3587 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3588 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3589 // Let M be the minimum representable signed value. Then (-1)*RHS
3590 // signed-wraps if and only if RHS is M. That can happen even for
3591 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3592 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3593 // (-1)*RHS, we need to prove that RHS != M.
3594 //
3595 // If LHS is non-negative and we know that LHS - RHS does not
3596 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3597 // either by proving that RHS > M or that LHS >= 0.
3598 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3599 AddFlags = SCEV::FlagNSW;
3600 }
3601 }
3602
3603 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3604 // RHS is NSW and LHS >= 0.
3605 //
3606 // The difficulty here is that the NSW flag may have been proven
3607 // relative to a loop that is to be found in a recurrence in LHS and
3608 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3609 // larger scope than intended.
3610 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3611
3612 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003613}
3614
Dan Gohmanaf752342009-07-07 17:06:11 +00003615const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003616ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3617 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003618 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3619 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003620 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003621 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003622 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003623 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003624 return getTruncateExpr(V, Ty);
3625 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003626}
3627
Dan Gohmanaf752342009-07-07 17:06:11 +00003628const SCEV *
3629ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003630 Type *Ty) {
3631 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003632 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3633 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003634 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003635 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003636 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003637 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003638 return getTruncateExpr(V, Ty);
3639 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003640}
3641
Dan Gohmanaf752342009-07-07 17:06:11 +00003642const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003643ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3644 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003645 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3646 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003647 "Cannot noop or zero extend with non-integer arguments!");
3648 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3649 "getNoopOrZeroExtend cannot truncate!");
3650 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3651 return V; // No conversion
3652 return getZeroExtendExpr(V, Ty);
3653}
3654
Dan Gohmanaf752342009-07-07 17:06:11 +00003655const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003656ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3657 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003658 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3659 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003660 "Cannot noop or sign extend with non-integer arguments!");
3661 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3662 "getNoopOrSignExtend cannot truncate!");
3663 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3664 return V; // No conversion
3665 return getSignExtendExpr(V, Ty);
3666}
3667
Dan Gohmanaf752342009-07-07 17:06:11 +00003668const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003669ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3670 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003671 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3672 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003673 "Cannot noop or any extend with non-integer arguments!");
3674 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3675 "getNoopOrAnyExtend cannot truncate!");
3676 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3677 return V; // No conversion
3678 return getAnyExtendExpr(V, Ty);
3679}
3680
Dan Gohmanaf752342009-07-07 17:06:11 +00003681const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003682ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3683 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003684 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3685 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003686 "Cannot truncate or noop with non-integer arguments!");
3687 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3688 "getTruncateOrNoop cannot extend!");
3689 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3690 return V; // No conversion
3691 return getTruncateExpr(V, Ty);
3692}
3693
Dan Gohmanabd17092009-06-24 14:49:00 +00003694const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3695 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003696 const SCEV *PromotedLHS = LHS;
3697 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003698
3699 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3700 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3701 else
3702 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3703
3704 return getUMaxExpr(PromotedLHS, PromotedRHS);
3705}
3706
Dan Gohmanabd17092009-06-24 14:49:00 +00003707const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3708 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003709 const SCEV *PromotedLHS = LHS;
3710 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003711
3712 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3713 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3714 else
3715 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3716
3717 return getUMinExpr(PromotedLHS, PromotedRHS);
3718}
3719
Andrew Trick87716c92011-03-17 23:51:11 +00003720const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3721 // A pointer operand may evaluate to a nonpointer expression, such as null.
3722 if (!V->getType()->isPointerTy())
3723 return V;
3724
3725 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3726 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003727 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003728 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003729 for (const SCEV *NAryOp : NAry->operands()) {
3730 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003731 // Cannot find the base of an expression with multiple pointer operands.
3732 if (PtrOp)
3733 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003734 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003735 }
3736 }
3737 if (!PtrOp)
3738 return V;
3739 return getPointerBase(PtrOp);
3740 }
3741 return V;
3742}
3743
Sanjoy Dasf8570812016-05-29 00:38:22 +00003744/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003745static void
3746PushDefUseChildren(Instruction *I,
3747 SmallVectorImpl<Instruction *> &Worklist) {
3748 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003749 for (User *U : I->users())
3750 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003751}
3752
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003753void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003754 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003755 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003756
Dan Gohman0b89dff2009-07-25 01:13:03 +00003757 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003758 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003759 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003760 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003761 if (!Visited.insert(I).second)
3762 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003763
Sanjoy Das63914592015-10-18 00:29:20 +00003764 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003765 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003766 const SCEV *Old = It->second;
3767
Dan Gohman0b89dff2009-07-25 01:13:03 +00003768 // Short-circuit the def-use traversal if the symbolic name
3769 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003770 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003771 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003772
Dan Gohman0b89dff2009-07-25 01:13:03 +00003773 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003774 // structure, it's a PHI that's in the progress of being computed
3775 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3776 // additional loop trip count information isn't going to change anything.
3777 // In the second case, createNodeForPHI will perform the necessary
3778 // updates on its own when it gets to that point. In the third, we do
3779 // want to forget the SCEVUnknown.
3780 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003781 !isa<SCEVUnknown>(Old) ||
3782 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003783 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003784 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003785 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003786 }
3787
3788 PushDefUseChildren(I, Worklist);
3789 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003790}
Chris Lattnerd934c702004-04-02 20:23:17 +00003791
Benjamin Kramer83709b12015-11-16 09:01:28 +00003792namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003793class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3794public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003795 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003796 ScalarEvolution &SE) {
3797 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003798 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003799 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3800 }
3801
3802 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3803 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3804
3805 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3806 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3807 Valid = false;
3808 return Expr;
3809 }
3810
3811 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3812 // Only allow AddRecExprs for this loop.
3813 if (Expr->getLoop() == L)
3814 return Expr->getStart();
3815 Valid = false;
3816 return Expr;
3817 }
3818
3819 bool isValid() { return Valid; }
3820
3821private:
3822 const Loop *L;
3823 bool Valid;
3824};
3825
3826class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3827public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003828 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003829 ScalarEvolution &SE) {
3830 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003831 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003832 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3833 }
3834
3835 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3836 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3837
3838 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3839 // Only allow AddRecExprs for this loop.
3840 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3841 Valid = false;
3842 return Expr;
3843 }
3844
3845 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3846 if (Expr->getLoop() == L && Expr->isAffine())
3847 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3848 Valid = false;
3849 return Expr;
3850 }
3851 bool isValid() { return Valid; }
3852
3853private:
3854 const Loop *L;
3855 bool Valid;
3856};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003857} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003858
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003859SCEV::NoWrapFlags
3860ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3861 if (!AR->isAffine())
3862 return SCEV::FlagAnyWrap;
3863
3864 typedef OverflowingBinaryOperator OBO;
3865 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3866
3867 if (!AR->hasNoSignedWrap()) {
3868 ConstantRange AddRecRange = getSignedRange(AR);
3869 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3870
3871 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3872 Instruction::Add, IncRange, OBO::NoSignedWrap);
3873 if (NSWRegion.contains(AddRecRange))
3874 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3875 }
3876
3877 if (!AR->hasNoUnsignedWrap()) {
3878 ConstantRange AddRecRange = getUnsignedRange(AR);
3879 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3880
3881 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3882 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3883 if (NUWRegion.contains(AddRecRange))
3884 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3885 }
3886
3887 return Result;
3888}
3889
Sanjoy Das118d9192016-03-31 05:14:22 +00003890namespace {
3891/// Represents an abstract binary operation. This may exist as a
3892/// normal instruction or constant expression, or may have been
3893/// derived from an expression tree.
3894struct BinaryOp {
3895 unsigned Opcode;
3896 Value *LHS;
3897 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003898 bool IsNSW;
3899 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003900
3901 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3902 /// constant expression.
3903 Operator *Op;
3904
3905 explicit BinaryOp(Operator *Op)
3906 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003907 IsNSW(false), IsNUW(false), Op(Op) {
3908 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3909 IsNSW = OBO->hasNoSignedWrap();
3910 IsNUW = OBO->hasNoUnsignedWrap();
3911 }
3912 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003913
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003914 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3915 bool IsNUW = false)
3916 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3917 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003918};
3919}
3920
3921
3922/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003923static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003924 auto *Op = dyn_cast<Operator>(V);
3925 if (!Op)
3926 return None;
3927
3928 // Implementation detail: all the cleverness here should happen without
3929 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3930 // SCEV expressions when possible, and we should not break that.
3931
3932 switch (Op->getOpcode()) {
3933 case Instruction::Add:
3934 case Instruction::Sub:
3935 case Instruction::Mul:
3936 case Instruction::UDiv:
3937 case Instruction::And:
3938 case Instruction::Or:
3939 case Instruction::AShr:
3940 case Instruction::Shl:
3941 return BinaryOp(Op);
3942
3943 case Instruction::Xor:
3944 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3945 // If the RHS of the xor is a signbit, then this is just an add.
3946 // Instcombine turns add of signbit into xor as a strength reduction step.
3947 if (RHSC->getValue().isSignBit())
3948 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3949 return BinaryOp(Op);
3950
3951 case Instruction::LShr:
3952 // Turn logical shift right of a constant into a unsigned divide.
3953 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3954 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3955
3956 // If the shift count is not less than the bitwidth, the result of
3957 // the shift is undefined. Don't try to analyze it, because the
3958 // resolution chosen here may differ from the resolution chosen in
3959 // other parts of the compiler.
3960 if (SA->getValue().ult(BitWidth)) {
3961 Constant *X =
3962 ConstantInt::get(SA->getContext(),
3963 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3964 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3965 }
3966 }
3967 return BinaryOp(Op);
3968
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003969 case Instruction::ExtractValue: {
3970 auto *EVI = cast<ExtractValueInst>(Op);
3971 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3972 break;
3973
3974 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3975 if (!CI)
3976 break;
3977
3978 if (auto *F = CI->getCalledFunction())
3979 switch (F->getIntrinsicID()) {
3980 case Intrinsic::sadd_with_overflow:
3981 case Intrinsic::uadd_with_overflow: {
3982 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3983 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3984 CI->getArgOperand(1));
3985
3986 // Now that we know that all uses of the arithmetic-result component of
3987 // CI are guarded by the overflow check, we can go ahead and pretend
3988 // that the arithmetic is non-overflowing.
3989 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3990 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3991 CI->getArgOperand(1), /* IsNSW = */ true,
3992 /* IsNUW = */ false);
3993 else
3994 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3995 CI->getArgOperand(1), /* IsNSW = */ false,
3996 /* IsNUW*/ true);
3997 }
3998
3999 case Intrinsic::ssub_with_overflow:
4000 case Intrinsic::usub_with_overflow:
4001 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4002 CI->getArgOperand(1));
4003
4004 case Intrinsic::smul_with_overflow:
4005 case Intrinsic::umul_with_overflow:
4006 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4007 CI->getArgOperand(1));
4008 default:
4009 break;
4010 }
4011 }
4012
Sanjoy Das118d9192016-03-31 05:14:22 +00004013 default:
4014 break;
4015 }
4016
4017 return None;
4018}
4019
Sanjoy Das55015d22015-10-02 23:09:44 +00004020const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4021 const Loop *L = LI.getLoopFor(PN->getParent());
4022 if (!L || L->getHeader() != PN->getParent())
4023 return nullptr;
4024
4025 // The loop may have multiple entrances or multiple exits; we can analyze
4026 // this phi as an addrec if it has a unique entry value and a unique
4027 // backedge value.
4028 Value *BEValueV = nullptr, *StartValueV = nullptr;
4029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4030 Value *V = PN->getIncomingValue(i);
4031 if (L->contains(PN->getIncomingBlock(i))) {
4032 if (!BEValueV) {
4033 BEValueV = V;
4034 } else if (BEValueV != V) {
4035 BEValueV = nullptr;
4036 break;
4037 }
4038 } else if (!StartValueV) {
4039 StartValueV = V;
4040 } else if (StartValueV != V) {
4041 StartValueV = nullptr;
4042 break;
4043 }
4044 }
4045 if (BEValueV && StartValueV) {
4046 // While we are analyzing this PHI node, handle its value symbolically.
4047 const SCEV *SymbolicName = getUnknown(PN);
4048 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4049 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00004050 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004051
4052 // Using this symbolic name for the PHI, analyze the value coming around
4053 // the back-edge.
4054 const SCEV *BEValue = getSCEV(BEValueV);
4055
4056 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4057 // has a special value for the first iteration of the loop.
4058
4059 // If the value coming around the backedge is an add with the symbolic
4060 // value we just inserted, then we found a simple induction variable!
4061 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4062 // If there is a single occurrence of the symbolic value, replace it
4063 // with a recurrence.
4064 unsigned FoundIndex = Add->getNumOperands();
4065 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4066 if (Add->getOperand(i) == SymbolicName)
4067 if (FoundIndex == e) {
4068 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004069 break;
4070 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004071
4072 if (FoundIndex != Add->getNumOperands()) {
4073 // Create an add with everything but the specified operand.
4074 SmallVector<const SCEV *, 8> Ops;
4075 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4076 if (i != FoundIndex)
4077 Ops.push_back(Add->getOperand(i));
4078 const SCEV *Accum = getAddExpr(Ops);
4079
4080 // This is not a valid addrec if the step amount is varying each
4081 // loop iteration, but is not itself an addrec in this loop.
4082 if (isLoopInvariant(Accum, L) ||
4083 (isa<SCEVAddRecExpr>(Accum) &&
4084 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4085 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4086
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004087 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004088 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4089 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004090 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004091 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004092 Flags = setFlags(Flags, SCEV::FlagNSW);
4093 }
4094 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4095 // If the increment is an inbounds GEP, then we know the address
4096 // space cannot be wrapped around. We cannot make any guarantee
4097 // about signed or unsigned overflow because pointers are
4098 // unsigned but we may have a negative index from the base
4099 // pointer. We can guarantee that no unsigned wrap occurs if the
4100 // indices form a positive value.
4101 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4102 Flags = setFlags(Flags, SCEV::FlagNW);
4103
4104 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4105 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4106 Flags = setFlags(Flags, SCEV::FlagNUW);
4107 }
4108
4109 // We cannot transfer nuw and nsw flags from subtraction
4110 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4111 // for instance.
4112 }
4113
4114 const SCEV *StartVal = getSCEV(StartValueV);
4115 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4116
Sanjoy Das55015d22015-10-02 23:09:44 +00004117 // Okay, for the entire analysis of this edge we assumed the PHI
4118 // to be symbolic. We now need to go back and purge all of the
4119 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004120 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004121 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004122
4123 // We can add Flags to the post-inc expression only if we
4124 // know that it us *undefined behavior* for BEValueV to
4125 // overflow.
4126 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4127 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4128 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4129
Sanjoy Das55015d22015-10-02 23:09:44 +00004130 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004131 }
4132 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004133 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004134 // Otherwise, this could be a loop like this:
4135 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4136 // In this case, j = {1,+,1} and BEValue is j.
4137 // Because the other in-value of i (0) fits the evolution of BEValue
4138 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004139 //
4140 // We can generalize this saying that i is the shifted value of BEValue
4141 // by one iteration:
4142 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4143 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4144 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4145 if (Shifted != getCouldNotCompute() &&
4146 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004147 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004148 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004149 // Okay, for the entire analysis of this edge we assumed the PHI
4150 // to be symbolic. We now need to go back and purge all of the
4151 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004152 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004153 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4154 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004155 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004156 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004157 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004158
4159 // Remove the temporary PHI node SCEV that has been inserted while intending
4160 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4161 // as it will prevent later (possibly simpler) SCEV expressions to be added
4162 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004163 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004164 }
4165
4166 return nullptr;
4167}
4168
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004169// Checks if the SCEV S is available at BB. S is considered available at BB
4170// if S can be materialized at BB without introducing a fault.
4171static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4172 BasicBlock *BB) {
4173 struct CheckAvailable {
4174 bool TraversalDone = false;
4175 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004176
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004177 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4178 BasicBlock *BB = nullptr;
4179 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004180
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004181 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4182 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004183
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004184 bool setUnavailable() {
4185 TraversalDone = true;
4186 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004187 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004188 }
4189
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004190 bool follow(const SCEV *S) {
4191 switch (S->getSCEVType()) {
4192 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4193 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004194 // These expressions are available if their operand(s) is/are.
4195 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004196
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004197 case scAddRecExpr: {
4198 // We allow add recurrences that are on the loop BB is in, or some
4199 // outer loop. This guarantees availability because the value of the
4200 // add recurrence at BB is simply the "current" value of the induction
4201 // variable. We can relax this in the future; for instance an add
4202 // recurrence on a sibling dominating loop is also available at BB.
4203 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4204 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004205 return true;
4206
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004207 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004208 }
4209
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004210 case scUnknown: {
4211 // For SCEVUnknown, we check for simple dominance.
4212 const auto *SU = cast<SCEVUnknown>(S);
4213 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004214
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004215 if (isa<Argument>(V))
4216 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004217
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004218 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4219 return false;
4220
4221 return setUnavailable();
4222 }
4223
4224 case scUDivExpr:
4225 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004226 // We do not try to smart about these at all.
4227 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004228 }
4229 llvm_unreachable("switch should be fully covered!");
4230 }
4231
4232 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004233 };
4234
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004235 CheckAvailable CA(L, BB, DT);
4236 SCEVTraversal<CheckAvailable> ST(CA);
4237
4238 ST.visitAll(S);
4239 return CA.Available;
4240}
4241
4242// Try to match a control flow sequence that branches out at BI and merges back
4243// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4244// match.
4245static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4246 Value *&C, Value *&LHS, Value *&RHS) {
4247 C = BI->getCondition();
4248
4249 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4250 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4251
4252 if (!LeftEdge.isSingleEdge())
4253 return false;
4254
4255 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4256
4257 Use &LeftUse = Merge->getOperandUse(0);
4258 Use &RightUse = Merge->getOperandUse(1);
4259
4260 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4261 LHS = LeftUse;
4262 RHS = RightUse;
4263 return true;
4264 }
4265
4266 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4267 LHS = RightUse;
4268 RHS = LeftUse;
4269 return true;
4270 }
4271
4272 return false;
4273}
4274
4275const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004276 auto IsReachable =
4277 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4278 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004279 const Loop *L = LI.getLoopFor(PN->getParent());
4280
Sanjoy Das337d4782015-10-31 23:21:40 +00004281 // We don't want to break LCSSA, even in a SCEV expression tree.
4282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4283 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4284 return nullptr;
4285
Sanjoy Das55015d22015-10-02 23:09:44 +00004286 // Try to match
4287 //
4288 // br %cond, label %left, label %right
4289 // left:
4290 // br label %merge
4291 // right:
4292 // br label %merge
4293 // merge:
4294 // V = phi [ %x, %left ], [ %y, %right ]
4295 //
4296 // as "select %cond, %x, %y"
4297
4298 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4299 assert(IDom && "At least the entry block should dominate PN");
4300
4301 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4302 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4303
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004304 if (BI && BI->isConditional() &&
4305 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4306 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4307 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004308 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4309 }
4310
4311 return nullptr;
4312}
4313
4314const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4315 if (const SCEV *S = createAddRecFromPHI(PN))
4316 return S;
4317
4318 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4319 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004320
Dan Gohmana9c205c2010-02-25 06:57:05 +00004321 // If the PHI has a single incoming value, follow that value, unless the
4322 // PHI's incoming blocks are in a different loop, in which case doing so
4323 // risks breaking LCSSA form. Instcombine would normally zap these, but
4324 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004325 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004326 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004327 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004328
Chris Lattnerd934c702004-04-02 20:23:17 +00004329 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004330 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004331}
4332
Sanjoy Das55015d22015-10-02 23:09:44 +00004333const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4334 Value *Cond,
4335 Value *TrueVal,
4336 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004337 // Handle "constant" branch or select. This can occur for instance when a
4338 // loop pass transforms an inner loop and moves on to process the outer loop.
4339 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4340 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4341
Sanjoy Dasd0671342015-10-02 19:39:59 +00004342 // Try to match some simple smax or umax patterns.
4343 auto *ICI = dyn_cast<ICmpInst>(Cond);
4344 if (!ICI)
4345 return getUnknown(I);
4346
4347 Value *LHS = ICI->getOperand(0);
4348 Value *RHS = ICI->getOperand(1);
4349
4350 switch (ICI->getPredicate()) {
4351 case ICmpInst::ICMP_SLT:
4352 case ICmpInst::ICMP_SLE:
4353 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004354 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004355 case ICmpInst::ICMP_SGT:
4356 case ICmpInst::ICMP_SGE:
4357 // a >s b ? a+x : b+x -> smax(a, b)+x
4358 // a >s b ? b+x : a+x -> smin(a, b)+x
4359 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4360 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4361 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4362 const SCEV *LA = getSCEV(TrueVal);
4363 const SCEV *RA = getSCEV(FalseVal);
4364 const SCEV *LDiff = getMinusSCEV(LA, LS);
4365 const SCEV *RDiff = getMinusSCEV(RA, RS);
4366 if (LDiff == RDiff)
4367 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4368 LDiff = getMinusSCEV(LA, RS);
4369 RDiff = getMinusSCEV(RA, LS);
4370 if (LDiff == RDiff)
4371 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4372 }
4373 break;
4374 case ICmpInst::ICMP_ULT:
4375 case ICmpInst::ICMP_ULE:
4376 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004377 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004378 case ICmpInst::ICMP_UGT:
4379 case ICmpInst::ICMP_UGE:
4380 // a >u b ? a+x : b+x -> umax(a, b)+x
4381 // a >u b ? b+x : a+x -> umin(a, b)+x
4382 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4383 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4384 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4385 const SCEV *LA = getSCEV(TrueVal);
4386 const SCEV *RA = getSCEV(FalseVal);
4387 const SCEV *LDiff = getMinusSCEV(LA, LS);
4388 const SCEV *RDiff = getMinusSCEV(RA, RS);
4389 if (LDiff == RDiff)
4390 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4391 LDiff = getMinusSCEV(LA, RS);
4392 RDiff = getMinusSCEV(RA, LS);
4393 if (LDiff == RDiff)
4394 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4395 }
4396 break;
4397 case ICmpInst::ICMP_NE:
4398 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4399 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4400 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4401 const SCEV *One = getOne(I->getType());
4402 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4403 const SCEV *LA = getSCEV(TrueVal);
4404 const SCEV *RA = getSCEV(FalseVal);
4405 const SCEV *LDiff = getMinusSCEV(LA, LS);
4406 const SCEV *RDiff = getMinusSCEV(RA, One);
4407 if (LDiff == RDiff)
4408 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4409 }
4410 break;
4411 case ICmpInst::ICMP_EQ:
4412 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4413 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4414 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4415 const SCEV *One = getOne(I->getType());
4416 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4417 const SCEV *LA = getSCEV(TrueVal);
4418 const SCEV *RA = getSCEV(FalseVal);
4419 const SCEV *LDiff = getMinusSCEV(LA, One);
4420 const SCEV *RDiff = getMinusSCEV(RA, LS);
4421 if (LDiff == RDiff)
4422 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4423 }
4424 break;
4425 default:
4426 break;
4427 }
4428
4429 return getUnknown(I);
4430}
4431
Sanjoy Dasf8570812016-05-29 00:38:22 +00004432/// Expand GEP instructions into add and multiply operations. This allows them
4433/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004434const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004435 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004436 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004437 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004438
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004439 SmallVector<const SCEV *, 4> IndexExprs;
4440 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4441 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004442 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004443}
4444
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004445uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004446 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004447 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004448
Dan Gohmana30370b2009-05-04 22:02:23 +00004449 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004450 return std::min(GetMinTrailingZeros(T->getOperand()),
4451 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004452
Dan Gohmana30370b2009-05-04 22:02:23 +00004453 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004455 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4456 ? getTypeSizeInBits(E->getType())
4457 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004458 }
4459
Dan Gohmana30370b2009-05-04 22:02:23 +00004460 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004461 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004462 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4463 ? getTypeSizeInBits(E->getType())
4464 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004465 }
4466
Dan Gohmana30370b2009-05-04 22:02:23 +00004467 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004468 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004469 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004470 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004472 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004473 }
4474
Dan Gohmana30370b2009-05-04 22:02:23 +00004475 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004476 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004477 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4478 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004479 for (unsigned i = 1, e = M->getNumOperands();
4480 SumOpRes != BitWidth && i != e; ++i)
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004481 SumOpRes =
4482 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
Nick Lewycky3783b462007-11-22 07:59:40 +00004483 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004484 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004485
Dan Gohmana30370b2009-05-04 22:02:23 +00004486 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004487 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004488 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004489 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004491 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004492 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004493
Dan Gohmana30370b2009-05-04 22:02:23 +00004494 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004495 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004496 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004497 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004499 return MinOpRes;
4500 }
4501
Dan Gohmana30370b2009-05-04 22:02:23 +00004502 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004503 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004504 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004505 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004506 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004507 return MinOpRes;
4508 }
4509
Dan Gohmanc702fc02009-06-19 23:29:04 +00004510 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4511 // For a SCEVUnknown, ask ValueTracking.
4512 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004513 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004514 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004515 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004516 return Zeros.countTrailingOnes();
4517 }
4518
4519 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004520 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004521}
Chris Lattnerd934c702004-04-02 20:23:17 +00004522
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004523uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4524 auto I = MinTrailingZerosCache.find(S);
4525 if (I != MinTrailingZerosCache.end())
4526 return I->second;
4527
4528 uint32_t Result = GetMinTrailingZerosImpl(S);
4529 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4530 assert(InsertPair.second && "Should insert a new key");
4531 return InsertPair.first->second;
4532}
4533
Sanjoy Dasf8570812016-05-29 00:38:22 +00004534/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004535static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004536 if (Instruction *I = dyn_cast<Instruction>(V))
4537 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4538 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004539
4540 return None;
4541}
4542
Sanjoy Dasf8570812016-05-29 00:38:22 +00004543/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004544/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4545/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004546ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004547ScalarEvolution::getRange(const SCEV *S,
4548 ScalarEvolution::RangeSignHint SignHint) {
4549 DenseMap<const SCEV *, ConstantRange> &Cache =
4550 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4551 : SignedRanges;
4552
Dan Gohman761065e2010-11-17 02:44:44 +00004553 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004554 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4555 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004556 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004557
4558 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004559 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004560
Dan Gohman85be4332010-01-26 19:19:05 +00004561 unsigned BitWidth = getTypeSizeInBits(S->getType());
4562 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4563
Sanjoy Das91b54772015-03-09 21:43:43 +00004564 // If the value has known zeros, the maximum value will have those known zeros
4565 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004566 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004567 if (TZ != 0) {
4568 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4569 ConservativeResult =
4570 ConstantRange(APInt::getMinValue(BitWidth),
4571 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4572 else
4573 ConservativeResult = ConstantRange(
4574 APInt::getSignedMinValue(BitWidth),
4575 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4576 }
Dan Gohman85be4332010-01-26 19:19:05 +00004577
Dan Gohmane65c9172009-07-13 21:35:55 +00004578 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004579 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004580 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004581 X = X.add(getRange(Add->getOperand(i), SignHint));
4582 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004583 }
4584
4585 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004586 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004587 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004588 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4589 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004590 }
4591
4592 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004593 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004594 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004595 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4596 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004597 }
4598
4599 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004600 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004601 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004602 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4603 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004604 }
4605
4606 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004607 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4608 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4609 return setRange(UDiv, SignHint,
4610 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004611 }
4612
4613 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004614 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4615 return setRange(ZExt, SignHint,
4616 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004617 }
4618
4619 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004620 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4621 return setRange(SExt, SignHint,
4622 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004623 }
4624
4625 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004626 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4627 return setRange(Trunc, SignHint,
4628 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004629 }
4630
Dan Gohmane65c9172009-07-13 21:35:55 +00004631 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004632 // If there's no unsigned wrap, the value will never be less than its
4633 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004634 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004635 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004636 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004637 ConservativeResult = ConservativeResult.intersectWith(
4638 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004639
Dan Gohman51ad99d2010-01-21 02:09:26 +00004640 // If there's no signed wrap, and all the operands have the same sign or
4641 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004642 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004643 bool AllNonNeg = true;
4644 bool AllNonPos = true;
4645 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4646 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4647 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4648 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004649 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004650 ConservativeResult = ConservativeResult.intersectWith(
4651 ConstantRange(APInt(BitWidth, 0),
4652 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004653 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004654 ConservativeResult = ConservativeResult.intersectWith(
4655 ConstantRange(APInt::getSignedMinValue(BitWidth),
4656 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004657 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004658
4659 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004660 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004661 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004662 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4663 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004664 auto RangeFromAffine = getRangeForAffineAR(
4665 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4666 BitWidth);
4667 if (!RangeFromAffine.isFullSet())
4668 ConservativeResult =
4669 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004670
4671 auto RangeFromFactoring = getRangeViaFactoring(
4672 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4673 BitWidth);
4674 if (!RangeFromFactoring.isFullSet())
4675 ConservativeResult =
4676 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004677 }
Dan Gohmand261d272009-06-24 01:05:09 +00004678 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004679
Sanjoy Das91b54772015-03-09 21:43:43 +00004680 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004681 }
4682
Dan Gohmanc702fc02009-06-19 23:29:04 +00004683 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004684 // Check if the IR explicitly contains !range metadata.
4685 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4686 if (MDRange.hasValue())
4687 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4688
Sanjoy Das91b54772015-03-09 21:43:43 +00004689 // Split here to avoid paying the compile-time cost of calling both
4690 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4691 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004692 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004693 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4694 // For a SCEVUnknown, ask ValueTracking.
4695 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004696 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004697 if (Ones != ~Zeros + 1)
4698 ConservativeResult =
4699 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4700 } else {
4701 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4702 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004703 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004704 if (NS > 1)
4705 ConservativeResult = ConservativeResult.intersectWith(
4706 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4707 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004708 }
4709
4710 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004711 }
4712
Sanjoy Das91b54772015-03-09 21:43:43 +00004713 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004714}
4715
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004716// Given a StartRange, Step and MaxBECount for an expression compute a range of
4717// values that the expression can take. Initially, the expression has a value
4718// from StartRange and then is changed by Step up to MaxBECount times. Signed
4719// argument defines if we treat Step as signed or unsigned.
4720static ConstantRange getRangeForAffineARHelper(APInt Step,
4721 ConstantRange StartRange,
4722 APInt MaxBECount,
4723 unsigned BitWidth, bool Signed) {
4724 // If either Step or MaxBECount is 0, then the expression won't change, and we
4725 // just need to return the initial range.
4726 if (Step == 0 || MaxBECount == 0)
4727 return StartRange;
4728
4729 // If we don't know anything about the inital value (i.e. StartRange is
4730 // FullRange), then we don't know anything about the final range either.
4731 // Return FullRange.
4732 if (StartRange.isFullSet())
4733 return ConstantRange(BitWidth, /* isFullSet = */ true);
4734
4735 // If Step is signed and negative, then we use its absolute value, but we also
4736 // note that we're moving in the opposite direction.
4737 bool Descending = Signed && Step.isNegative();
4738
4739 if (Signed)
4740 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4741 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4742 // This equations hold true due to the well-defined wrap-around behavior of
4743 // APInt.
4744 Step = Step.abs();
4745
4746 // Check if Offset is more than full span of BitWidth. If it is, the
4747 // expression is guaranteed to overflow.
4748 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4749 return ConstantRange(BitWidth, /* isFullSet = */ true);
4750
4751 // Offset is by how much the expression can change. Checks above guarantee no
4752 // overflow here.
4753 APInt Offset = Step * MaxBECount;
4754
4755 // Minimum value of the final range will match the minimal value of StartRange
4756 // if the expression is increasing and will be decreased by Offset otherwise.
4757 // Maximum value of the final range will match the maximal value of StartRange
4758 // if the expression is decreasing and will be increased by Offset otherwise.
4759 APInt StartLower = StartRange.getLower();
4760 APInt StartUpper = StartRange.getUpper() - 1;
4761 APInt MovedBoundary =
4762 Descending ? (StartLower - Offset) : (StartUpper + Offset);
4763
4764 // It's possible that the new minimum/maximum value will fall into the initial
4765 // range (due to wrap around). This means that the expression can take any
4766 // value in this bitwidth, and we have to return full range.
4767 if (StartRange.contains(MovedBoundary))
4768 return ConstantRange(BitWidth, /* isFullSet = */ true);
4769
4770 APInt NewLower, NewUpper;
4771 if (Descending) {
4772 NewLower = MovedBoundary;
4773 NewUpper = StartUpper;
4774 } else {
4775 NewLower = StartLower;
4776 NewUpper = MovedBoundary;
4777 }
4778
4779 // If we end up with full range, return a proper full range.
4780 if (NewLower == NewUpper + 1)
4781 return ConstantRange(BitWidth, /* isFullSet = */ true);
4782
4783 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4784 return ConstantRange(NewLower, NewUpper + 1);
4785}
4786
Sanjoy Dasb765b632016-03-02 00:57:39 +00004787ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4788 const SCEV *Step,
4789 const SCEV *MaxBECount,
4790 unsigned BitWidth) {
4791 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4792 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4793 "Precondition!");
4794
Sanjoy Dasb765b632016-03-02 00:57:39 +00004795 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4796 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004797 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
Sanjoy Dasb765b632016-03-02 00:57:39 +00004798
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004799 // First, consider step signed.
Sanjoy Dasb765b632016-03-02 00:57:39 +00004800 ConstantRange StartSRange = getSignedRange(Start);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004801 ConstantRange StepSRange = getSignedRange(Step);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004802
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004803 // If Step can be both positive and negative, we need to find ranges for the
4804 // maximum absolute step values in both directions and union them.
4805 ConstantRange SR =
4806 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4807 MaxBECountValue, BitWidth, /* Signed = */ true);
4808 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4809 StartSRange, MaxBECountValue,
4810 BitWidth, /* Signed = */ true));
Sanjoy Dasb765b632016-03-02 00:57:39 +00004811
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004812 // Next, consider step unsigned.
4813 ConstantRange UR = getRangeForAffineARHelper(
4814 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4815 MaxBECountValue, BitWidth, /* Signed = */ false);
4816
4817 // Finally, intersect signed and unsigned ranges.
4818 return SR.intersectWith(UR);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004819}
4820
Sanjoy Dasbf730982016-03-02 00:57:54 +00004821ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4822 const SCEV *Step,
4823 const SCEV *MaxBECount,
4824 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004825 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4826 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4827
4828 struct SelectPattern {
4829 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004830 APInt TrueValue;
4831 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004832
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004833 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4834 const SCEV *S) {
4835 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004836 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004837
4838 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4839 "Should be!");
4840
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004841 // Peel off a constant offset:
4842 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4843 // In the future we could consider being smarter here and handle
4844 // {Start+Step,+,Step} too.
4845 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4846 return;
4847
4848 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4849 S = SA->getOperand(1);
4850 }
4851
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004852 // Peel off a cast operation
4853 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4854 CastOp = SCast->getSCEVType();
4855 S = SCast->getOperand();
4856 }
4857
Sanjoy Dasbf730982016-03-02 00:57:54 +00004858 using namespace llvm::PatternMatch;
4859
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004860 auto *SU = dyn_cast<SCEVUnknown>(S);
4861 const APInt *TrueVal, *FalseVal;
4862 if (!SU ||
4863 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4864 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004865 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004866 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004867 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004868
4869 TrueValue = *TrueVal;
4870 FalseValue = *FalseVal;
4871
4872 // Re-apply the cast we peeled off earlier
4873 if (CastOp.hasValue())
4874 switch (*CastOp) {
4875 default:
4876 llvm_unreachable("Unknown SCEV cast type!");
4877
4878 case scTruncate:
4879 TrueValue = TrueValue.trunc(BitWidth);
4880 FalseValue = FalseValue.trunc(BitWidth);
4881 break;
4882 case scZeroExtend:
4883 TrueValue = TrueValue.zext(BitWidth);
4884 FalseValue = FalseValue.zext(BitWidth);
4885 break;
4886 case scSignExtend:
4887 TrueValue = TrueValue.sext(BitWidth);
4888 FalseValue = FalseValue.sext(BitWidth);
4889 break;
4890 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004891
4892 // Re-apply the constant offset we peeled off earlier
4893 TrueValue += Offset;
4894 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004895 }
4896
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004897 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004898 };
4899
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004900 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004901 if (!StartPattern.isRecognized())
4902 return ConstantRange(BitWidth, /* isFullSet = */ true);
4903
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004904 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004905 if (!StepPattern.isRecognized())
4906 return ConstantRange(BitWidth, /* isFullSet = */ true);
4907
4908 if (StartPattern.Condition != StepPattern.Condition) {
4909 // We don't handle this case today; but we could, by considering four
4910 // possibilities below instead of two. I'm not sure if there are cases where
4911 // that will help over what getRange already does, though.
4912 return ConstantRange(BitWidth, /* isFullSet = */ true);
4913 }
4914
4915 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4916 // construct arbitrary general SCEV expressions here. This function is called
4917 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4918 // say) can end up caching a suboptimal value.
4919
Sanjoy Das6b017a12016-03-02 02:56:29 +00004920 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4921 // C2352 and C2512 (otherwise it isn't needed).
4922
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004923 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004924 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004925 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004926 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004927
Sanjoy Das1168f932016-03-02 02:34:20 +00004928 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004929 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004930 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004931 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004932
4933 return TrueRange.unionWith(FalseRange);
4934}
4935
Jingyue Wu42f1d672015-07-28 18:22:40 +00004936SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004937 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004938 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4939
4940 // Return early if there are no flags to propagate to the SCEV.
4941 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4942 if (BinOp->hasNoUnsignedWrap())
4943 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4944 if (BinOp->hasNoSignedWrap())
4945 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004946 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004947 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004948
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004949 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4950}
4951
4952bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4953 // Here we check that I is in the header of the innermost loop containing I,
4954 // since we only deal with instructions in the loop header. The actual loop we
4955 // need to check later will come from an add recurrence, but getting that
4956 // requires computing the SCEV of the operands, which can be expensive. This
4957 // check we can do cheaply to rule out some cases early.
4958 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004959 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004960 InnermostContainingLoop->getHeader() != I->getParent())
4961 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004962
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004963 // Only proceed if we can prove that I does not yield poison.
4964 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004965
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004966 // At this point we know that if I is executed, then it does not wrap
4967 // according to at least one of NSW or NUW. If I is not executed, then we do
4968 // not know if the calculation that I represents would wrap. Multiple
4969 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004970 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4971 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004972 // that guarantee for cases where I is not executed. So we need to find the
4973 // loop that I is considered in relation to and prove that I is executed for
4974 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004975 // calculates does not wrap anywhere in the loop, so then we can apply the
4976 // flags to the SCEV.
4977 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004978 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4979 // from different loops, so that we know which loop to prove that I is
4980 // executed in.
4981 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004982 // I could be an extractvalue from a call to an overflow intrinsic.
4983 // TODO: We can do better here in some cases.
4984 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4985 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004986 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004987 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004988 bool AllOtherOpsLoopInvariant = true;
4989 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4990 ++OtherOpIndex) {
4991 if (OtherOpIndex != OpIndex) {
4992 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4993 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4994 AllOtherOpsLoopInvariant = false;
4995 break;
4996 }
4997 }
4998 }
4999 if (AllOtherOpsLoopInvariant &&
5000 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5001 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005002 }
5003 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005004 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005005}
5006
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005007bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5008 // If we know that \c I can never be poison period, then that's enough.
5009 if (isSCEVExprNeverPoison(I))
5010 return true;
5011
5012 // For an add recurrence specifically, we assume that infinite loops without
5013 // side effects are undefined behavior, and then reason as follows:
5014 //
5015 // If the add recurrence is poison in any iteration, it is poison on all
5016 // future iterations (since incrementing poison yields poison). If the result
5017 // of the add recurrence is fed into the loop latch condition and the loop
5018 // does not contain any throws or exiting blocks other than the latch, we now
5019 // have the ability to "choose" whether the backedge is taken or not (by
5020 // choosing a sufficiently evil value for the poison feeding into the branch)
5021 // for every iteration including and after the one in which \p I first became
5022 // poison. There are two possibilities (let's call the iteration in which \p
5023 // I first became poison as K):
5024 //
5025 // 1. In the set of iterations including and after K, the loop body executes
5026 // no side effects. In this case executing the backege an infinte number
5027 // of times will yield undefined behavior.
5028 //
5029 // 2. In the set of iterations including and after K, the loop body executes
5030 // at least one side effect. In this case, that specific instance of side
5031 // effect is control dependent on poison, which also yields undefined
5032 // behavior.
5033
5034 auto *ExitingBB = L->getExitingBlock();
5035 auto *LatchBB = L->getLoopLatch();
5036 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5037 return false;
5038
5039 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005040 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005041
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005042 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5043 // things that are known to be fully poison under that assumption go on the
5044 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005045 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005046 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005047
5048 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00005049 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005050 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005051
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005052 for (auto *PoisonUser : Poison->users()) {
5053 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5054 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5055 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5056 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005057 assert(BI->isConditional() && "Only possibility!");
5058 if (BI->getParent() == LatchBB) {
5059 LatchControlDependentOnPoison = true;
5060 break;
5061 }
5062 }
5063 }
5064 }
5065
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005066 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5067}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005068
Sanjoy Das5603fc02016-09-26 02:44:07 +00005069ScalarEvolution::LoopProperties
5070ScalarEvolution::getLoopProperties(const Loop *L) {
5071 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005072
Sanjoy Das5603fc02016-09-26 02:44:07 +00005073 auto Itr = LoopPropertiesCache.find(L);
5074 if (Itr == LoopPropertiesCache.end()) {
5075 auto HasSideEffects = [](Instruction *I) {
5076 if (auto *SI = dyn_cast<StoreInst>(I))
5077 return !SI->isSimple();
5078
5079 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005080 };
5081
Sanjoy Das5603fc02016-09-26 02:44:07 +00005082 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5083 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005084
Sanjoy Das5603fc02016-09-26 02:44:07 +00005085 for (auto *BB : L->getBlocks())
5086 for (auto &I : *BB) {
5087 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5088 LP.HasNoAbnormalExits = false;
5089 if (HasSideEffects(&I))
5090 LP.HasNoSideEffects = false;
5091 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5092 break; // We're already as pessimistic as we can get.
5093 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005094
Sanjoy Das5603fc02016-09-26 02:44:07 +00005095 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005096 assert(InsertPair.second && "We just checked!");
5097 Itr = InsertPair.first;
5098 }
5099
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005100 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005101}
5102
Dan Gohmanaf752342009-07-07 17:06:11 +00005103const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005104 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005105 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005106
Dan Gohman69451a02010-03-09 23:46:50 +00005107 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005108 // Don't attempt to analyze instructions in blocks that aren't
5109 // reachable. Such instructions don't matter, and they aren't required
5110 // to obey basic rules for definitions dominating uses which this
5111 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005112 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005113 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005114 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005115 return getConstant(CI);
5116 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005117 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005118 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005119 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005120 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005121 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005122
Dan Gohman80ca01c2009-07-17 20:47:02 +00005123 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005124 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005125 switch (BO->Opcode) {
5126 case Instruction::Add: {
5127 // The simple thing to do would be to just call getSCEV on both operands
5128 // and call getAddExpr with the result. However if we're looking at a
5129 // bunch of things all added together, this can be quite inefficient,
5130 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5131 // Instead, gather up all the operands and make a single getAddExpr call.
5132 // LLVM IR canonical form means we need only traverse the left operands.
5133 SmallVector<const SCEV *, 4> AddOps;
5134 do {
5135 if (BO->Op) {
5136 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5137 AddOps.push_back(OpSCEV);
5138 break;
5139 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005140
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005141 // If a NUW or NSW flag can be applied to the SCEV for this
5142 // addition, then compute the SCEV for this addition by itself
5143 // with a separate call to getAddExpr. We need to do that
5144 // instead of pushing the operands of the addition onto AddOps,
5145 // since the flags are only known to apply to this particular
5146 // addition - they may not apply to other additions that can be
5147 // formed with operands from AddOps.
5148 const SCEV *RHS = getSCEV(BO->RHS);
5149 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5150 if (Flags != SCEV::FlagAnyWrap) {
5151 const SCEV *LHS = getSCEV(BO->LHS);
5152 if (BO->Opcode == Instruction::Sub)
5153 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5154 else
5155 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5156 break;
5157 }
Dan Gohman36bad002009-09-17 18:05:20 +00005158 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005159
5160 if (BO->Opcode == Instruction::Sub)
5161 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5162 else
5163 AddOps.push_back(getSCEV(BO->RHS));
5164
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005165 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005166 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5167 NewBO->Opcode != Instruction::Sub)) {
5168 AddOps.push_back(getSCEV(BO->LHS));
5169 break;
5170 }
5171 BO = NewBO;
5172 } while (true);
5173
5174 return getAddExpr(AddOps);
5175 }
5176
5177 case Instruction::Mul: {
5178 SmallVector<const SCEV *, 4> MulOps;
5179 do {
5180 if (BO->Op) {
5181 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5182 MulOps.push_back(OpSCEV);
5183 break;
5184 }
5185
5186 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5187 if (Flags != SCEV::FlagAnyWrap) {
5188 MulOps.push_back(
5189 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5190 break;
5191 }
5192 }
5193
5194 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005195 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005196 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5197 MulOps.push_back(getSCEV(BO->LHS));
5198 break;
5199 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005200 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005201 } while (true);
5202
5203 return getMulExpr(MulOps);
5204 }
5205 case Instruction::UDiv:
5206 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5207 case Instruction::Sub: {
5208 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5209 if (BO->Op)
5210 Flags = getNoWrapFlagsFromUB(BO->Op);
5211 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5212 }
5213 case Instruction::And:
5214 // For an expression like x&255 that merely masks off the high bits,
5215 // use zext(trunc(x)) as the SCEV expression.
5216 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5217 if (CI->isNullValue())
5218 return getSCEV(BO->RHS);
5219 if (CI->isAllOnesValue())
5220 return getSCEV(BO->LHS);
5221 const APInt &A = CI->getValue();
5222
5223 // Instcombine's ShrinkDemandedConstant may strip bits out of
5224 // constants, obscuring what would otherwise be a low-bits mask.
5225 // Use computeKnownBits to compute what ShrinkDemandedConstant
5226 // knew about to reconstruct a low-bits mask value.
5227 unsigned LZ = A.countLeadingZeros();
5228 unsigned TZ = A.countTrailingZeros();
5229 unsigned BitWidth = A.getBitWidth();
5230 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5231 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005232 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005233
5234 APInt EffectiveMask =
5235 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5236 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005237 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5238 const SCEV *LHS = getSCEV(BO->LHS);
5239 const SCEV *ShiftedLHS = nullptr;
5240 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5241 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5242 // For an expression like (x * 8) & 8, simplify the multiply.
5243 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5244 unsigned GCD = std::min(MulZeros, TZ);
5245 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5246 SmallVector<const SCEV*, 4> MulOps;
5247 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5248 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5249 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5250 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5251 }
5252 }
5253 if (!ShiftedLHS)
5254 ShiftedLHS = getUDivExpr(LHS, MulCount);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005255 return getMulExpr(
5256 getZeroExtendExpr(
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005257 getTruncateExpr(ShiftedLHS,
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005258 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5259 BO->LHS->getType()),
5260 MulCount);
5261 }
Dan Gohman36bad002009-09-17 18:05:20 +00005262 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005263 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005264
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005265 case Instruction::Or:
5266 // If the RHS of the Or is a constant, we may have something like:
5267 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5268 // optimizations will transparently handle this case.
5269 //
5270 // In order for this transformation to be safe, the LHS must be of the
5271 // form X*(2^n) and the Or constant must be less than 2^n.
5272 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5273 const SCEV *LHS = getSCEV(BO->LHS);
5274 const APInt &CIVal = CI->getValue();
5275 if (GetMinTrailingZeros(LHS) >=
5276 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5277 // Build a plain add SCEV.
5278 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5279 // If the LHS of the add was an addrec and it has no-wrap flags,
5280 // transfer the no-wrap flags, since an or won't introduce a wrap.
5281 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5282 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5283 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5284 OldAR->getNoWrapFlags());
5285 }
5286 return S;
5287 }
5288 }
5289 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005290
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005291 case Instruction::Xor:
5292 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5293 // If the RHS of xor is -1, then this is a not operation.
5294 if (CI->isAllOnesValue())
5295 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005296
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005297 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5298 // This is a variant of the check for xor with -1, and it handles
5299 // the case where instcombine has trimmed non-demanded bits out
5300 // of an xor with -1.
5301 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5302 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5303 if (LBO->getOpcode() == Instruction::And &&
5304 LCI->getValue() == CI->getValue())
5305 if (const SCEVZeroExtendExpr *Z =
5306 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5307 Type *UTy = BO->LHS->getType();
5308 const SCEV *Z0 = Z->getOperand();
5309 Type *Z0Ty = Z0->getType();
5310 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005311
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005312 // If C is a low-bits mask, the zero extend is serving to
5313 // mask off the high bits. Complement the operand and
5314 // re-apply the zext.
5315 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5316 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5317
5318 // If C is a single bit, it may be in the sign-bit position
5319 // before the zero-extend. In this case, represent the xor
5320 // using an add, which is equivalent, and re-apply the zext.
5321 APInt Trunc = CI->getValue().trunc(Z0TySize);
5322 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5323 Trunc.isSignBit())
5324 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5325 UTy);
5326 }
5327 }
5328 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005329
5330 case Instruction::Shl:
5331 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005332 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5333 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005334
5335 // If the shift count is not less than the bitwidth, the result of
5336 // the shift is undefined. Don't try to analyze it, because the
5337 // resolution chosen here may differ from the resolution chosen in
5338 // other parts of the compiler.
5339 if (SA->getValue().uge(BitWidth))
5340 break;
5341
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005342 // It is currently not resolved how to interpret NSW for left
5343 // shift by BitWidth - 1, so we avoid applying flags in that
5344 // case. Remove this check (or this comment) once the situation
5345 // is resolved. See
5346 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5347 // and http://reviews.llvm.org/D8890 .
5348 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005349 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5350 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005351
Owen Andersonedb4a702009-07-24 23:12:02 +00005352 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005353 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005354 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005355 }
5356 break;
5357
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005358 case Instruction::AShr:
5359 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5360 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5361 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5362 if (L->getOpcode() == Instruction::Shl &&
5363 L->getOperand(1) == BO->RHS) {
5364 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005365
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005366 // If the shift count is not less than the bitwidth, the result of
5367 // the shift is undefined. Don't try to analyze it, because the
5368 // resolution chosen here may differ from the resolution chosen in
5369 // other parts of the compiler.
5370 if (CI->getValue().uge(BitWidth))
5371 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005372
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005373 uint64_t Amt = BitWidth - CI->getZExtValue();
5374 if (Amt == BitWidth)
5375 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5376 return getSignExtendExpr(
5377 getTruncateExpr(getSCEV(L->getOperand(0)),
5378 IntegerType::get(getContext(), Amt)),
5379 BO->LHS->getType());
5380 }
5381 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005382 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005383 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005384
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005385 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005386 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005387 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005388
5389 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005390 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005391
5392 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005393 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005394
5395 case Instruction::BitCast:
5396 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005397 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005398 return getSCEV(U->getOperand(0));
5399 break;
5400
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005401 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5402 // lead to pointer expressions which cannot safely be expanded to GEPs,
5403 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5404 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005405
Dan Gohmanee750d12009-05-08 20:26:55 +00005406 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005407 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005408
Dan Gohman05e89732008-06-22 19:56:46 +00005409 case Instruction::PHI:
5410 return createNodeForPHI(cast<PHINode>(U));
5411
5412 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005413 // U can also be a select constant expr, which let fall through. Since
5414 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5415 // constant expressions cannot have instructions as operands, we'd have
5416 // returned getUnknown for a select constant expressions anyway.
5417 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005418 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5419 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005420 break;
5421
5422 case Instruction::Call:
5423 case Instruction::Invoke:
5424 if (Value *RV = CallSite(U).getReturnedArgOperand())
5425 return getSCEV(RV);
5426 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005427 }
5428
Dan Gohmanc8e23622009-04-21 23:15:49 +00005429 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005430}
5431
5432
5433
5434//===----------------------------------------------------------------------===//
5435// Iteration Count Computation Code
5436//
5437
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005438static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5439 if (!ExitCount)
5440 return 0;
5441
5442 ConstantInt *ExitConst = ExitCount->getValue();
5443
5444 // Guard against huge trip counts.
5445 if (ExitConst->getValue().getActiveBits() > 32)
5446 return 0;
5447
5448 // In case of integer overflow, this returns 0, which is correct.
5449 return ((unsigned)ExitConst->getZExtValue()) + 1;
5450}
5451
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005452unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005453 if (BasicBlock *ExitingBB = L->getExitingBlock())
5454 return getSmallConstantTripCount(L, ExitingBB);
5455
5456 // No trip count information for multiple exits.
5457 return 0;
5458}
5459
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005460unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005461 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005462 assert(ExitingBlock && "Must pass a non-null exiting block!");
5463 assert(L->isLoopExiting(ExitingBlock) &&
5464 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005465 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005466 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005467 return getConstantTripCount(ExitCount);
5468}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005469
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005470unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005471 const auto *MaxExitCount =
5472 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5473 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005474}
5475
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005476unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005477 if (BasicBlock *ExitingBB = L->getExitingBlock())
5478 return getSmallConstantTripMultiple(L, ExitingBB);
5479
5480 // No trip multiple information for multiple exits.
5481 return 0;
5482}
5483
Sanjoy Dasf8570812016-05-29 00:38:22 +00005484/// Returns the largest constant divisor of the trip count of this loop as a
5485/// normal unsigned value, if possible. This means that the actual trip count is
5486/// always a multiple of the returned value (don't forget the trip count could
5487/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005488///
5489/// Returns 1 if the trip count is unknown or not guaranteed to be the
5490/// multiple of a constant (which is also the case if the trip count is simply
5491/// constant, use getSmallConstantTripCount for that case), Will also return 1
5492/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005493///
5494/// As explained in the comments for getSmallConstantTripCount, this assumes
5495/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005496unsigned
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005497ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005498 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005499 assert(ExitingBlock && "Must pass a non-null exiting block!");
5500 assert(L->isLoopExiting(ExitingBlock) &&
5501 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005502 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005503 if (ExitCount == getCouldNotCompute())
5504 return 1;
5505
5506 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005507 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005508 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5509 // to factor simple cases.
5510 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5511 TCMul = Mul->getOperand(0);
5512
5513 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5514 if (!MulC)
5515 return 1;
5516
5517 ConstantInt *Result = MulC->getValue();
5518
Hal Finkel30bd9342012-10-24 19:46:44 +00005519 // Guard against huge trip counts (this requires checking
5520 // for zero to handle the case where the trip count == -1 and the
5521 // addition wraps).
5522 if (!Result || Result->getValue().getActiveBits() > 32 ||
5523 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005524 return 1;
5525
5526 return (unsigned)Result->getZExtValue();
5527}
5528
Sanjoy Dasf8570812016-05-29 00:38:22 +00005529/// Get the expression for the number of loop iterations for which this loop is
5530/// guaranteed not to exit via ExitingBlock. Otherwise return
5531/// SCEVCouldNotCompute.
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005532const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5533 BasicBlock *ExitingBlock) {
Andrew Trick77c55422011-08-02 04:23:35 +00005534 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005535}
5536
Silviu Baranga6f444df2016-04-08 14:29:09 +00005537const SCEV *
5538ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5539 SCEVUnionPredicate &Preds) {
5540 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5541}
5542
Dan Gohmanaf752342009-07-07 17:06:11 +00005543const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005544 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005545}
5546
Sanjoy Dasf8570812016-05-29 00:38:22 +00005547/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5548/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005549const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005550 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005551}
5552
John Brawn84b21832016-10-21 11:08:48 +00005553bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5554 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5555}
5556
Sanjoy Dasf8570812016-05-29 00:38:22 +00005557/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005558static void
5559PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5560 BasicBlock *Header = L->getHeader();
5561
5562 // Push all Loop-header PHIs onto the Worklist stack.
5563 for (BasicBlock::iterator I = Header->begin();
5564 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5565 Worklist.push_back(PN);
5566}
5567
Dan Gohman2b8da352009-04-30 20:47:05 +00005568const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005569ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5570 auto &BTI = getBackedgeTakenInfo(L);
5571 if (BTI.hasFullInfo())
5572 return BTI;
5573
5574 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5575
5576 if (!Pair.second)
5577 return Pair.first->second;
5578
5579 BackedgeTakenInfo Result =
5580 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5581
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005582 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005583}
5584
5585const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005586ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005587 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005588 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005589 // update the value. The temporary CouldNotCompute value tells SCEV
5590 // code elsewhere that it shouldn't attempt to request a new
5591 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005592 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005593 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005594 if (!Pair.second)
5595 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005596
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005597 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005598 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5599 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005600 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005601
5602 if (Result.getExact(this) != getCouldNotCompute()) {
5603 assert(isLoopInvariant(Result.getExact(this), L) &&
5604 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005605 "Computed backedge-taken count isn't loop invariant for loop!");
5606 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005607 }
5608 else if (Result.getMax(this) == getCouldNotCompute() &&
5609 isa<PHINode>(L->getHeader()->begin())) {
5610 // Only count loops that have phi nodes as not being computable.
5611 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005612 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005613
Chris Lattnera337f5e2011-01-09 02:16:18 +00005614 // Now that we know more about the trip count for this loop, forget any
5615 // existing SCEV values for PHI nodes in this loop since they are only
5616 // conservative estimates made without the benefit of trip count
5617 // information. This is similar to the code in forgetLoop, except that
5618 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005619 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005620 SmallVector<Instruction *, 16> Worklist;
5621 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005622
Chris Lattnera337f5e2011-01-09 02:16:18 +00005623 SmallPtrSet<Instruction *, 8> Visited;
5624 while (!Worklist.empty()) {
5625 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005626 if (!Visited.insert(I).second)
5627 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005628
Chris Lattnera337f5e2011-01-09 02:16:18 +00005629 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005630 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005631 if (It != ValueExprMap.end()) {
5632 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005633
Chris Lattnera337f5e2011-01-09 02:16:18 +00005634 // SCEVUnknown for a PHI either means that it has an unrecognized
5635 // structure, or it's a PHI that's in the progress of being computed
5636 // by createNodeForPHI. In the former case, additional loop trip
5637 // count information isn't going to change anything. In the later
5638 // case, createNodeForPHI will perform the necessary updates on its
5639 // own when it gets to that point.
5640 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005641 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005642 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005643 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005644 if (PHINode *PN = dyn_cast<PHINode>(I))
5645 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005646 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005647
5648 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005649 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005650 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005651
5652 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005653 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005654 // recusive call to getBackedgeTakenInfo (on a different
5655 // loop), which would invalidate the iterator computed
5656 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005657 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005658}
5659
Dan Gohman880c92a2009-10-31 15:04:55 +00005660void ScalarEvolution::forgetLoop(const Loop *L) {
5661 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005662 auto RemoveLoopFromBackedgeMap =
5663 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5664 auto BTCPos = Map.find(L);
5665 if (BTCPos != Map.end()) {
5666 BTCPos->second.clear();
5667 Map.erase(BTCPos);
5668 }
5669 };
5670
5671 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5672 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005673
Dan Gohman880c92a2009-10-31 15:04:55 +00005674 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005675 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005676 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005677
Dan Gohmandc191042009-07-08 19:23:34 +00005678 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005679 while (!Worklist.empty()) {
5680 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005681 if (!Visited.insert(I).second)
5682 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005683
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005684 ValueExprMapType::iterator It =
5685 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005686 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005687 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005688 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005689 if (PHINode *PN = dyn_cast<PHINode>(I))
5690 ConstantEvolutionLoopExitValue.erase(PN);
5691 }
5692
5693 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005694 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005695
5696 // Forget all contained loops too, to avoid dangling entries in the
5697 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005698 for (Loop *I : *L)
5699 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005700
Sanjoy Das5603fc02016-09-26 02:44:07 +00005701 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005702}
5703
Eric Christopheref6d5932010-07-29 01:25:38 +00005704void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005705 Instruction *I = dyn_cast<Instruction>(V);
5706 if (!I) return;
5707
5708 // Drop information about expressions based on loop-header PHIs.
5709 SmallVector<Instruction *, 16> Worklist;
5710 Worklist.push_back(I);
5711
5712 SmallPtrSet<Instruction *, 8> Visited;
5713 while (!Worklist.empty()) {
5714 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005715 if (!Visited.insert(I).second)
5716 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005717
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005718 ValueExprMapType::iterator It =
5719 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005720 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005721 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005722 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005723 if (PHINode *PN = dyn_cast<PHINode>(I))
5724 ConstantEvolutionLoopExitValue.erase(PN);
5725 }
5726
5727 PushDefUseChildren(I, Worklist);
5728 }
5729}
5730
Sanjoy Dasf8570812016-05-29 00:38:22 +00005731/// Get the exact loop backedge taken count considering all loop exits. A
5732/// computable result can only be returned for loops with a single exit.
5733/// Returning the minimum taken count among all exits is incorrect because one
5734/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5735/// the limit of each loop test is never skipped. This is a valid assumption as
5736/// long as the loop exits via that test. For precise results, it is the
5737/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005738/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005739const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005740ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5741 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005742 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005743 if (!isComplete() || ExitNotTaken.empty())
5744 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005745
Craig Topper9f008862014-04-15 04:59:12 +00005746 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005747 for (auto &ENT : ExitNotTaken) {
5748 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005749
5750 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005751 BECount = ENT.ExactNotTaken;
5752 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005753 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005754 if (Preds && !ENT.hasAlwaysTruePredicate())
5755 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005756
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005757 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005758 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005759 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005760
Andrew Trickbbb226a2011-09-02 21:20:46 +00005761 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005762 return BECount;
5763}
5764
Sanjoy Dasf8570812016-05-29 00:38:22 +00005765/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005766const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005767ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005768 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005769 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005770 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005771 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005772
Andrew Trick3ca3f982011-07-26 17:19:55 +00005773 return SE->getCouldNotCompute();
5774}
5775
5776/// getMax - Get the max backedge taken count for the loop.
5777const SCEV *
5778ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005779 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5780 return !ENT.hasAlwaysTruePredicate();
5781 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005782
Sanjoy Das73268612016-09-26 01:10:22 +00005783 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5784 return SE->getCouldNotCompute();
5785
5786 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005787}
5788
John Brawn84b21832016-10-21 11:08:48 +00005789bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5790 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5791 return !ENT.hasAlwaysTruePredicate();
5792 };
5793 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5794}
5795
Andrew Trick9093e152013-03-26 03:14:53 +00005796bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5797 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005798 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5799 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005800 return true;
5801
Silviu Baranga6f444df2016-04-08 14:29:09 +00005802 for (auto &ENT : ExitNotTaken)
5803 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5804 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005805 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005806
Andrew Trick9093e152013-03-26 03:14:53 +00005807 return false;
5808}
5809
Andrew Trick3ca3f982011-07-26 17:19:55 +00005810/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5811/// computable exit into a persistent ExitNotTakenInfo array.
5812ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005813 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5814 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005815 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5816 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005817 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005818 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005819 std::transform(
5820 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005821 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005822 BasicBlock *ExitBB = EEI.first;
5823 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005824 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005825 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005826
5827 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5828 for (auto *Pred : EL.Predicates)
5829 Predicate->add(Pred);
5830
5831 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005832 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005833}
5834
Sanjoy Dasf8570812016-05-29 00:38:22 +00005835/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005836void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005837 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005838}
5839
Sanjoy Dasf8570812016-05-29 00:38:22 +00005840/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005841ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005842ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5843 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005844 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005845 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005846
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005847 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5848
5849 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005850 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005851 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005852 const SCEV *MustExitMaxBECount = nullptr;
5853 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005854 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005855
5856 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5857 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005858 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005859 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005860 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005861 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5862
Sanjoy Dasf0022122016-09-28 17:14:58 +00005863 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005864 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005865
5866 // 1. For each exit that can be computed, add an entry to ExitCounts.
5867 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005868 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005869 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005870 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005871 CouldComputeBECount = false;
5872 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005873 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005874
Andrew Trick839e30b2014-05-23 19:47:13 +00005875 // 2. Derive the loop's MaxBECount from each exit's max number of
5876 // non-exiting iterations. Partition the loop exits into two kinds:
5877 // LoopMustExits and LoopMayExits.
5878 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005879 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5880 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005881 // MaxBECount is the minimum EL.MaxNotTaken of computable
5882 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5883 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5884 // computable EL.MaxNotTaken.
5885 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005886 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005887 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005888 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005889 MustExitMaxOrZero = EL.MaxOrZero;
5890 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005891 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005892 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005893 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005894 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005895 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5896 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005897 else {
5898 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005899 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005900 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005901 }
Dan Gohman96212b62009-06-22 00:31:57 +00005902 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005903 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5904 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00005905 // The loop backedge will be taken the maximum or zero times if there's
5906 // a single exit that must be taken the maximum or zero times.
5907 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005908 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00005909 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00005910}
5911
Andrew Trick3ca3f982011-07-26 17:19:55 +00005912ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005913ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5914 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005915
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005916 // Okay, we've chosen an exiting block. See what condition causes us to exit
5917 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005918 // lead to the loop header.
5919 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005920 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005921 for (auto *SBB : successors(ExitingBlock))
5922 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005923 if (Exit) // Multiple exit successors.
5924 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005925 Exit = SBB;
5926 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005927 MustExecuteLoopHeader = false;
5928 }
Dan Gohmance973df2009-06-24 04:48:43 +00005929
Chris Lattner18954852007-01-07 02:24:26 +00005930 // At this point, we know we have a conditional branch that determines whether
5931 // the loop is exited. However, we don't know if the branch is executed each
5932 // time through the loop. If not, then the execution count of the branch will
5933 // not be equal to the trip count of the loop.
5934 //
5935 // Currently we check for this by checking to see if the Exit branch goes to
5936 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005937 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005938 // loop header. This is common for un-rotated loops.
5939 //
5940 // If both of those tests fail, walk up the unique predecessor chain to the
5941 // header, stopping if there is an edge that doesn't exit the loop. If the
5942 // header is reached, the execution count of the branch will be equal to the
5943 // trip count of the loop.
5944 //
5945 // More extensive analysis could be done to handle more cases here.
5946 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005947 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005948 // The simple checks failed, try climbing the unique predecessor chain
5949 // up to the header.
5950 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005951 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005952 BasicBlock *Pred = BB->getUniquePredecessor();
5953 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005954 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005955 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005956 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005957 if (PredSucc == BB)
5958 continue;
5959 // If the predecessor has a successor that isn't BB and isn't
5960 // outside the loop, assume the worst.
5961 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005962 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005963 }
5964 if (Pred == L->getHeader()) {
5965 Ok = true;
5966 break;
5967 }
5968 BB = Pred;
5969 }
5970 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005971 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005972 }
5973
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005974 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005975 TerminatorInst *Term = ExitingBlock->getTerminator();
5976 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5977 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5978 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005979 return computeExitLimitFromCond(
5980 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5981 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005982 }
5983
5984 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005985 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005986 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005987
5988 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005989}
5990
Andrew Trick3ca3f982011-07-26 17:19:55 +00005991ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005992ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005993 Value *ExitCond,
5994 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005995 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005996 bool ControlsExit,
5997 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005998 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6000 if (BO->getOpcode() == Instruction::And) {
6001 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00006002 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006003 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006004 ControlsExit && !EitherMayExit,
6005 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006006 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006007 ControlsExit && !EitherMayExit,
6008 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006009 const SCEV *BECount = getCouldNotCompute();
6010 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006011 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006012 // Both conditions must be true for the loop to continue executing.
6013 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006014 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6015 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006016 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006017 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006018 BECount =
6019 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6020 if (EL0.MaxNotTaken == getCouldNotCompute())
6021 MaxBECount = EL1.MaxNotTaken;
6022 else if (EL1.MaxNotTaken == getCouldNotCompute())
6023 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006024 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006025 MaxBECount =
6026 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006027 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006028 // Both conditions must be true at the same time for the loop to exit.
6029 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006030 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006031 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6032 MaxBECount = EL0.MaxNotTaken;
6033 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6034 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006035 }
6036
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006037 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6038 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006039 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6040 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6041 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006042 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6043 !isa<SCEVCouldNotCompute>(BECount))
6044 MaxBECount = BECount;
6045
John Brawn84b21832016-10-21 11:08:48 +00006046 return ExitLimit(BECount, MaxBECount, false,
6047 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006048 }
6049 if (BO->getOpcode() == Instruction::Or) {
6050 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00006051 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006052 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006053 ControlsExit && !EitherMayExit,
6054 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006055 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006056 ControlsExit && !EitherMayExit,
6057 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006058 const SCEV *BECount = getCouldNotCompute();
6059 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006060 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006061 // Both conditions must be false for the loop to continue executing.
6062 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006063 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6064 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006065 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006066 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006067 BECount =
6068 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6069 if (EL0.MaxNotTaken == getCouldNotCompute())
6070 MaxBECount = EL1.MaxNotTaken;
6071 else if (EL1.MaxNotTaken == getCouldNotCompute())
6072 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006073 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006074 MaxBECount =
6075 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006076 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006077 // Both conditions must be false at the same time for the loop to exit.
6078 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006079 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006080 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6081 MaxBECount = EL0.MaxNotTaken;
6082 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6083 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006084 }
6085
John Brawn84b21832016-10-21 11:08:48 +00006086 return ExitLimit(BECount, MaxBECount, false,
6087 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006088 }
6089 }
6090
6091 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006092 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006093 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6094 ExitLimit EL =
6095 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6096 if (EL.hasFullInfo() || !AllowPredicates)
6097 return EL;
6098
6099 // Try again, but use SCEV predicates this time.
6100 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6101 /*AllowPredicates=*/true);
6102 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006103
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006104 // Check for a constant condition. These are normally stripped out by
6105 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6106 // preserve the CFG and is temporarily leaving constant conditions
6107 // in place.
6108 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6109 if (L->contains(FBB) == !CI->getZExtValue())
6110 // The backedge is always taken.
6111 return getCouldNotCompute();
6112 else
6113 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006114 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006115 }
6116
Eli Friedmanebf98b02009-05-09 12:32:42 +00006117 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006118 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006119}
6120
Andrew Trick3ca3f982011-07-26 17:19:55 +00006121ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006122ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006123 ICmpInst *ExitCond,
6124 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006125 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006126 bool ControlsExit,
6127 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006128
Reid Spencer266e42b2006-12-23 06:05:41 +00006129 // If the condition was exit on true, convert the condition to exit on false
6130 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006131 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006132 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006133 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006134 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006135
6136 // Handle common loops like: for (X = "string"; *X; ++X)
6137 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6138 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006139 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006140 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006141 if (ItCnt.hasAnyInfo())
6142 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006143 }
6144
Dan Gohmanaf752342009-07-07 17:06:11 +00006145 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6146 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006147
6148 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006149 LHS = getSCEVAtScope(LHS, L);
6150 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006151
Dan Gohmance973df2009-06-24 04:48:43 +00006152 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006153 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006154 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006155 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006156 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006157 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006158 }
6159
Dan Gohman81585c12010-05-03 16:35:17 +00006160 // Simplify the operands before analyzing them.
6161 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6162
Chris Lattnerd934c702004-04-02 20:23:17 +00006163 // If we have a comparison of a chrec against a constant, try to use value
6164 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006165 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6166 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006167 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006168 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006169 ConstantRange CompRange =
6170 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006171
Dan Gohmanaf752342009-07-07 17:06:11 +00006172 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006173 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006174 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006175
Chris Lattnerd934c702004-04-02 20:23:17 +00006176 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006177 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006178 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006179 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006180 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006181 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006182 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006183 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006184 case ICmpInst::ICMP_EQ: { // while (X == Y)
6185 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006186 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006187 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006188 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006189 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006190 case ICmpInst::ICMP_SLT:
6191 case ICmpInst::ICMP_ULT: { // while (X < Y)
6192 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006193 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006194 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006195 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006196 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006197 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006198 case ICmpInst::ICMP_SGT:
6199 case ICmpInst::ICMP_UGT: { // while (X > Y)
6200 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006201 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006202 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006203 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006204 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006205 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006206 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006207 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006208 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006209 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006210
6211 auto *ExhaustiveCount =
6212 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6213
6214 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6215 return ExhaustiveCount;
6216
6217 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6218 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006219}
6220
Benjamin Kramer5a188542014-02-11 15:44:32 +00006221ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006222ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006223 SwitchInst *Switch,
6224 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006225 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006226 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6227
6228 // Give up if the exit is the default dest of a switch.
6229 if (Switch->getDefaultDest() == ExitingBlock)
6230 return getCouldNotCompute();
6231
6232 assert(L->contains(Switch->getDefaultDest()) &&
6233 "Default case must not exit the loop!");
6234 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6235 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6236
6237 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006238 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006239 if (EL.hasAnyInfo())
6240 return EL;
6241
6242 return getCouldNotCompute();
6243}
6244
Chris Lattnerec901cc2004-10-12 01:49:27 +00006245static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006246EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6247 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006248 const SCEV *InVal = SE.getConstant(C);
6249 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006250 assert(isa<SCEVConstant>(Val) &&
6251 "Evaluation of SCEV at constant didn't fold correctly?");
6252 return cast<SCEVConstant>(Val)->getValue();
6253}
6254
Sanjoy Dasf8570812016-05-29 00:38:22 +00006255/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6256/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006257ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006258ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006259 LoadInst *LI,
6260 Constant *RHS,
6261 const Loop *L,
6262 ICmpInst::Predicate predicate) {
6263
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006264 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006265
6266 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006267 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006268 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006269 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006270
6271 // Make sure that it is really a constant global we are gepping, with an
6272 // initializer, and make sure the first IDX is really 0.
6273 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006274 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006275 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6276 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006277 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006278
6279 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006280 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006281 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006282 unsigned VarIdxNum = 0;
6283 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6284 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6285 Indexes.push_back(CI);
6286 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006287 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006288 VarIdx = GEP->getOperand(i);
6289 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006290 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006291 }
6292
Andrew Trick7004e4b2012-03-26 22:33:59 +00006293 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6294 if (!VarIdx)
6295 return getCouldNotCompute();
6296
Chris Lattnerec901cc2004-10-12 01:49:27 +00006297 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6298 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006299 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006300 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006301
6302 // We can only recognize very limited forms of loop index expressions, in
6303 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006304 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006305 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006306 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6307 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006308 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006309
6310 unsigned MaxSteps = MaxBruteForceIterations;
6311 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006312 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006313 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006314 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006315
6316 // Form the GEP offset.
6317 Indexes[VarIdxNum] = Val;
6318
Chris Lattnere166a852012-01-24 05:49:24 +00006319 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6320 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006321 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006322
6323 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006324 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006325 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006326 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006327 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006328 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006329 }
6330 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006331 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006332}
6333
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006334ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6335 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6336 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6337 if (!RHS)
6338 return getCouldNotCompute();
6339
6340 const BasicBlock *Latch = L->getLoopLatch();
6341 if (!Latch)
6342 return getCouldNotCompute();
6343
6344 const BasicBlock *Predecessor = L->getLoopPredecessor();
6345 if (!Predecessor)
6346 return getCouldNotCompute();
6347
6348 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6349 // Return LHS in OutLHS and shift_opt in OutOpCode.
6350 auto MatchPositiveShift =
6351 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6352
6353 using namespace PatternMatch;
6354
6355 ConstantInt *ShiftAmt;
6356 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6357 OutOpCode = Instruction::LShr;
6358 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6359 OutOpCode = Instruction::AShr;
6360 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6361 OutOpCode = Instruction::Shl;
6362 else
6363 return false;
6364
6365 return ShiftAmt->getValue().isStrictlyPositive();
6366 };
6367
6368 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6369 //
6370 // loop:
6371 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6372 // %iv.shifted = lshr i32 %iv, <positive constant>
6373 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006374 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006375 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6376 auto MatchShiftRecurrence =
6377 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6378 Optional<Instruction::BinaryOps> PostShiftOpCode;
6379
6380 {
6381 Instruction::BinaryOps OpC;
6382 Value *V;
6383
6384 // If we encounter a shift instruction, "peel off" the shift operation,
6385 // and remember that we did so. Later when we inspect %iv's backedge
6386 // value, we will make sure that the backedge value uses the same
6387 // operation.
6388 //
6389 // Note: the peeled shift operation does not have to be the same
6390 // instruction as the one feeding into the PHI's backedge value. We only
6391 // really care about it being the same *kind* of shift instruction --
6392 // that's all that is required for our later inferences to hold.
6393 if (MatchPositiveShift(LHS, V, OpC)) {
6394 PostShiftOpCode = OpC;
6395 LHS = V;
6396 }
6397 }
6398
6399 PNOut = dyn_cast<PHINode>(LHS);
6400 if (!PNOut || PNOut->getParent() != L->getHeader())
6401 return false;
6402
6403 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6404 Value *OpLHS;
6405
6406 return
6407 // The backedge value for the PHI node must be a shift by a positive
6408 // amount
6409 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6410
6411 // of the PHI node itself
6412 OpLHS == PNOut &&
6413
6414 // and the kind of shift should be match the kind of shift we peeled
6415 // off, if any.
6416 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6417 };
6418
6419 PHINode *PN;
6420 Instruction::BinaryOps OpCode;
6421 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6422 return getCouldNotCompute();
6423
6424 const DataLayout &DL = getDataLayout();
6425
6426 // The key rationale for this optimization is that for some kinds of shift
6427 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6428 // within a finite number of iterations. If the condition guarding the
6429 // backedge (in the sense that the backedge is taken if the condition is true)
6430 // is false for the value the shift recurrence stabilizes to, then we know
6431 // that the backedge is taken only a finite number of times.
6432
6433 ConstantInt *StableValue = nullptr;
6434 switch (OpCode) {
6435 default:
6436 llvm_unreachable("Impossible case!");
6437
6438 case Instruction::AShr: {
6439 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6440 // bitwidth(K) iterations.
6441 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6442 bool KnownZero, KnownOne;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00006443 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006444 Predecessor->getTerminator(), &DT);
6445 auto *Ty = cast<IntegerType>(RHS->getType());
6446 if (KnownZero)
6447 StableValue = ConstantInt::get(Ty, 0);
6448 else if (KnownOne)
6449 StableValue = ConstantInt::get(Ty, -1, true);
6450 else
6451 return getCouldNotCompute();
6452
6453 break;
6454 }
6455 case Instruction::LShr:
6456 case Instruction::Shl:
6457 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6458 // stabilize to 0 in at most bitwidth(K) iterations.
6459 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6460 break;
6461 }
6462
6463 auto *Result =
6464 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6465 assert(Result->getType()->isIntegerTy(1) &&
6466 "Otherwise cannot be an operand to a branch instruction");
6467
6468 if (Result->isZeroValue()) {
6469 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6470 const SCEV *UpperBound =
6471 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006472 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006473 }
6474
6475 return getCouldNotCompute();
6476}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006477
Sanjoy Dasf8570812016-05-29 00:38:22 +00006478/// Return true if we can constant fold an instruction of the specified type,
6479/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006480static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006481 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006482 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6483 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006484 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006485
Chris Lattnerdd730472004-04-17 22:58:41 +00006486 if (const CallInst *CI = dyn_cast<CallInst>(I))
6487 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006488 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006489 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006490}
6491
Andrew Trick3a86ba72011-10-05 03:25:31 +00006492/// Determine whether this instruction can constant evolve within this loop
6493/// assuming its operands can all constant evolve.
6494static bool canConstantEvolve(Instruction *I, const Loop *L) {
6495 // An instruction outside of the loop can't be derived from a loop PHI.
6496 if (!L->contains(I)) return false;
6497
6498 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006499 // We don't currently keep track of the control flow needed to evaluate
6500 // PHIs, so we cannot handle PHIs inside of loops.
6501 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006502 }
6503
6504 // If we won't be able to constant fold this expression even if the operands
6505 // are constants, bail early.
6506 return CanConstantFold(I);
6507}
6508
6509/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6510/// recursing through each instruction operand until reaching a loop header phi.
6511static PHINode *
6512getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Michael Liao468fb742017-01-13 18:28:30 +00006513 DenseMap<Instruction *, PHINode *> &PHIMap,
6514 unsigned Depth) {
6515 if (Depth > MaxConstantEvolvingDepth)
6516 return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006517
6518 // Otherwise, we can evaluate this instruction if all of its operands are
6519 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006520 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006521 for (Value *Op : UseInst->operands()) {
6522 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006523
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006524 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006525 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006526
6527 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006528 if (!P)
6529 // If this operand is already visited, reuse the prior result.
6530 // We may have P != PHI if this is the deepest point at which the
6531 // inconsistent paths meet.
6532 P = PHIMap.lookup(OpInst);
6533 if (!P) {
6534 // Recurse and memoize the results, whether a phi is found or not.
6535 // This recursive call invalidates pointers into PHIMap.
Michael Liao468fb742017-01-13 18:28:30 +00006536 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006537 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006538 }
Craig Topper9f008862014-04-15 04:59:12 +00006539 if (!P)
6540 return nullptr; // Not evolving from PHI
6541 if (PHI && PHI != P)
6542 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006543 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006544 }
6545 // This is a expression evolving from a constant PHI!
6546 return PHI;
6547}
6548
Chris Lattnerdd730472004-04-17 22:58:41 +00006549/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6550/// in the loop that V is derived from. We allow arbitrary operations along the
6551/// way, but the operands of an operation must either be constants or a value
6552/// derived from a constant PHI. If this expression does not fit with these
6553/// constraints, return null.
6554static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006555 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006556 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006557
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006558 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006559 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006560
Andrew Trick3a86ba72011-10-05 03:25:31 +00006561 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006562 DenseMap<Instruction *, PHINode *> PHIMap;
Michael Liao468fb742017-01-13 18:28:30 +00006563 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
Chris Lattnerdd730472004-04-17 22:58:41 +00006564}
6565
6566/// EvaluateExpression - Given an expression that passes the
6567/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6568/// in the loop has the value PHIVal. If we can't fold this expression for some
6569/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006570static Constant *EvaluateExpression(Value *V, const Loop *L,
6571 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006572 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006573 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006574 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006575 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006576 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006577 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006578
Andrew Trick3a86ba72011-10-05 03:25:31 +00006579 if (Constant *C = Vals.lookup(I)) return C;
6580
Nick Lewyckya6674c72011-10-22 19:58:20 +00006581 // An instruction inside the loop depends on a value outside the loop that we
6582 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006583 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006584
6585 // An unmapped PHI can be due to a branch or another loop inside this loop,
6586 // or due to this not being the initial iteration through a loop where we
6587 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006588 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006589
Dan Gohmanf820bd32010-06-22 13:15:46 +00006590 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006591
6592 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006593 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6594 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006595 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006596 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006597 continue;
6598 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006599 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006600 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006601 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006602 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006603 }
6604
Nick Lewyckya6674c72011-10-22 19:58:20 +00006605 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006606 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006607 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006608 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6609 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006610 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006611 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006612 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006613}
6614
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006615
6616// If every incoming value to PN except the one for BB is a specific Constant,
6617// return that, else return nullptr.
6618static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6619 Constant *IncomingVal = nullptr;
6620
6621 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6622 if (PN->getIncomingBlock(i) == BB)
6623 continue;
6624
6625 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6626 if (!CurrentVal)
6627 return nullptr;
6628
6629 if (IncomingVal != CurrentVal) {
6630 if (IncomingVal)
6631 return nullptr;
6632 IncomingVal = CurrentVal;
6633 }
6634 }
6635
6636 return IncomingVal;
6637}
6638
Chris Lattnerdd730472004-04-17 22:58:41 +00006639/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6640/// in the header of its containing loop, we know the loop executes a
6641/// constant number of times, and the PHI node is just a recurrence
6642/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006643Constant *
6644ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006645 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006646 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006647 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006648 if (I != ConstantEvolutionLoopExitValue.end())
6649 return I->second;
6650
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006651 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006652 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006653
6654 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6655
Andrew Trick3a86ba72011-10-05 03:25:31 +00006656 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006657 BasicBlock *Header = L->getHeader();
6658 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006659
Sanjoy Dasdd709962015-10-08 18:28:36 +00006660 BasicBlock *Latch = L->getLoopLatch();
6661 if (!Latch)
6662 return nullptr;
6663
Sanjoy Das4493b402015-10-07 17:38:25 +00006664 for (auto &I : *Header) {
6665 PHINode *PHI = dyn_cast<PHINode>(&I);
6666 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006667 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006668 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006669 CurrentIterVals[PHI] = StartCST;
6670 }
6671 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006672 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006673
Sanjoy Dasdd709962015-10-08 18:28:36 +00006674 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006675
6676 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006677 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006678 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006679
Dan Gohman0bddac12009-02-24 18:55:53 +00006680 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006681 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006682 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006683 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006684 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006685 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006686
Nick Lewyckya6674c72011-10-22 19:58:20 +00006687 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006688 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006689 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006690 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006691 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006692 if (!NextPHI)
6693 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006694 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006695
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006696 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6697
Nick Lewyckya6674c72011-10-22 19:58:20 +00006698 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6699 // cease to be able to evaluate one of them or if they stop evolving,
6700 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006701 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006702 for (const auto &I : CurrentIterVals) {
6703 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006704 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006705 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006706 }
6707 // We use two distinct loops because EvaluateExpression may invalidate any
6708 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006709 for (const auto &I : PHIsToCompute) {
6710 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006711 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006712 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006713 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006714 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006715 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006716 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006717 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006718 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006719
6720 // If all entries in CurrentIterVals == NextIterVals then we can stop
6721 // iterating, the loop can't continue to change.
6722 if (StoppedEvolving)
6723 return RetVal = CurrentIterVals[PN];
6724
Andrew Trick3a86ba72011-10-05 03:25:31 +00006725 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006726 }
6727}
6728
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006729const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006730 Value *Cond,
6731 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006732 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006733 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006734
Dan Gohman866971e2010-06-19 14:17:24 +00006735 // If the loop is canonicalized, the PHI will have exactly two entries.
6736 // That's the only form we support here.
6737 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6738
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006739 DenseMap<Instruction *, Constant *> CurrentIterVals;
6740 BasicBlock *Header = L->getHeader();
6741 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6742
Sanjoy Dasdd709962015-10-08 18:28:36 +00006743 BasicBlock *Latch = L->getLoopLatch();
6744 assert(Latch && "Should follow from NumIncomingValues == 2!");
6745
Sanjoy Das4493b402015-10-07 17:38:25 +00006746 for (auto &I : *Header) {
6747 PHINode *PHI = dyn_cast<PHINode>(&I);
6748 if (!PHI)
6749 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006750 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006751 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006752 CurrentIterVals[PHI] = StartCST;
6753 }
6754 if (!CurrentIterVals.count(PN))
6755 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006756
6757 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6758 // the loop symbolically to determine when the condition gets a value of
6759 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006760 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006761 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006762 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006763 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006764 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006765
Zhou Sheng75b871f2007-01-11 12:24:14 +00006766 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006767 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006768
Reid Spencer983e3b32007-03-01 07:25:48 +00006769 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006770 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006771 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006772 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006773
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006774 // Update all the PHI nodes for the next iteration.
6775 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006776
6777 // Create a list of which PHIs we need to compute. We want to do this before
6778 // calling EvaluateExpression on them because that may invalidate iterators
6779 // into CurrentIterVals.
6780 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006781 for (const auto &I : CurrentIterVals) {
6782 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006783 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006784 PHIsToCompute.push_back(PHI);
6785 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006786 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006787 Constant *&NextPHI = NextIterVals[PHI];
6788 if (NextPHI) continue; // Already computed!
6789
Sanjoy Dasdd709962015-10-08 18:28:36 +00006790 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006791 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006792 }
6793 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006794 }
6795
6796 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006797 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006798}
6799
Dan Gohmanaf752342009-07-07 17:06:11 +00006800const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006801 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6802 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006803 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006804 for (auto &LS : Values)
6805 if (LS.first == L)
6806 return LS.second ? LS.second : V;
6807
6808 Values.emplace_back(L, nullptr);
6809
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006810 // Otherwise compute it.
6811 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006812 for (auto &LS : reverse(ValuesAtScopes[V]))
6813 if (LS.first == L) {
6814 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006815 break;
6816 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006817 return C;
6818}
6819
Nick Lewyckya6674c72011-10-22 19:58:20 +00006820/// This builds up a Constant using the ConstantExpr interface. That way, we
6821/// will return Constants for objects which aren't represented by a
6822/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6823/// Returns NULL if the SCEV isn't representable as a Constant.
6824static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006825 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006826 case scCouldNotCompute:
6827 case scAddRecExpr:
6828 break;
6829 case scConstant:
6830 return cast<SCEVConstant>(V)->getValue();
6831 case scUnknown:
6832 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6833 case scSignExtend: {
6834 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6835 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6836 return ConstantExpr::getSExt(CastOp, SS->getType());
6837 break;
6838 }
6839 case scZeroExtend: {
6840 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6841 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6842 return ConstantExpr::getZExt(CastOp, SZ->getType());
6843 break;
6844 }
6845 case scTruncate: {
6846 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6847 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6848 return ConstantExpr::getTrunc(CastOp, ST->getType());
6849 break;
6850 }
6851 case scAddExpr: {
6852 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6853 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006854 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6855 unsigned AS = PTy->getAddressSpace();
6856 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6857 C = ConstantExpr::getBitCast(C, DestPtrTy);
6858 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006859 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6860 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006861 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006862
6863 // First pointer!
6864 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006865 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006866 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006867 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006868 // The offsets have been converted to bytes. We can add bytes to an
6869 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006870 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006871 }
6872
6873 // Don't bother trying to sum two pointers. We probably can't
6874 // statically compute a load that results from it anyway.
6875 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006876 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006877
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006878 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6879 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006880 C2 = ConstantExpr::getIntegerCast(
6881 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006882 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006883 } else
6884 C = ConstantExpr::getAdd(C, C2);
6885 }
6886 return C;
6887 }
6888 break;
6889 }
6890 case scMulExpr: {
6891 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6892 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6893 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006894 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006895 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6896 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006897 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006898 C = ConstantExpr::getMul(C, C2);
6899 }
6900 return C;
6901 }
6902 break;
6903 }
6904 case scUDivExpr: {
6905 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6906 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6907 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6908 if (LHS->getType() == RHS->getType())
6909 return ConstantExpr::getUDiv(LHS, RHS);
6910 break;
6911 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006912 case scSMaxExpr:
6913 case scUMaxExpr:
6914 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006915 }
Craig Topper9f008862014-04-15 04:59:12 +00006916 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006917}
6918
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006919const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006920 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006921
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006922 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006923 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006924 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006925 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006926 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006927 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6928 if (PHINode *PN = dyn_cast<PHINode>(I))
6929 if (PN->getParent() == LI->getHeader()) {
6930 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006931 // to see if the loop that contains it has a known backedge-taken
6932 // count. If so, we may be able to force computation of the exit
6933 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006934 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006935 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006936 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006937 // Okay, we know how many times the containing loop executes. If
6938 // this is a constant evolving PHI node, get the final value at
6939 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006940 Constant *RV =
6941 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006942 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006943 }
6944 }
6945
Reid Spencere6328ca2006-12-04 21:33:23 +00006946 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006947 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006948 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006949 // result. This is particularly useful for computing loop exit values.
6950 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006951 SmallVector<Constant *, 4> Operands;
6952 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006953 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006954 if (Constant *C = dyn_cast<Constant>(Op)) {
6955 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006956 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006957 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006958
6959 // If any of the operands is non-constant and if they are
6960 // non-integer and non-pointer, don't even try to analyze them
6961 // with scev techniques.
6962 if (!isSCEVable(Op->getType()))
6963 return V;
6964
6965 const SCEV *OrigV = getSCEV(Op);
6966 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6967 MadeImprovement |= OrigV != OpV;
6968
Nick Lewyckya6674c72011-10-22 19:58:20 +00006969 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006970 if (!C) return V;
6971 if (C->getType() != Op->getType())
6972 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6973 Op->getType(),
6974 false),
6975 C, Op->getType());
6976 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006977 }
Dan Gohmance973df2009-06-24 04:48:43 +00006978
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006979 // Check to see if getSCEVAtScope actually made an improvement.
6980 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006981 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006982 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006983 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006984 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006985 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006986 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6987 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006988 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006989 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006990 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006991 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006992 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006993 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006994 }
6995 }
6996
6997 // This is some other type of SCEVUnknown, just return it.
6998 return V;
6999 }
7000
Dan Gohmana30370b2009-05-04 22:02:23 +00007001 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007002 // Avoid performing the look-up in the common case where the specified
7003 // expression has no loop-variant portions.
7004 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007005 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007006 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007007 // Okay, at least one of these operands is loop variant but might be
7008 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00007009 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7010 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00007011 NewOps.push_back(OpAtScope);
7012
7013 for (++i; i != e; ++i) {
7014 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007015 NewOps.push_back(OpAtScope);
7016 }
7017 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007018 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007019 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007020 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007021 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007022 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007023 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007024 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00007025 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007026 }
7027 }
7028 // If we got here, all operands are loop invariant.
7029 return Comm;
7030 }
7031
Dan Gohmana30370b2009-05-04 22:02:23 +00007032 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007033 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7034 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00007035 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7036 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00007037 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00007038 }
7039
7040 // If this is a loop recurrence for a loop that does not contain L, then we
7041 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00007042 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007043 // First, attempt to evaluate each operand.
7044 // Avoid performing the look-up in the common case where the specified
7045 // expression has no loop-variant portions.
7046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7047 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7048 if (OpAtScope == AddRec->getOperand(i))
7049 continue;
7050
7051 // Okay, at least one of these operands is loop variant but might be
7052 // foldable. Build a new instance of the folded commutative expression.
7053 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7054 AddRec->op_begin()+i);
7055 NewOps.push_back(OpAtScope);
7056 for (++i; i != e; ++i)
7057 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7058
Andrew Trick759ba082011-04-27 01:21:25 +00007059 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00007060 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00007061 AddRec->getNoWrapFlags(SCEV::FlagNW));
7062 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00007063 // The addrec may be folded to a nonrecurrence, for example, if the
7064 // induction variable is multiplied by zero after constant folding. Go
7065 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00007066 if (!AddRec)
7067 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007068 break;
7069 }
7070
7071 // If the scope is outside the addrec's loop, evaluate it by using the
7072 // loop exit value of the addrec.
7073 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007074 // To evaluate this recurrence, we need to know how many times the AddRec
7075 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00007076 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007077 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00007078
Eli Friedman61f67622008-08-04 23:49:06 +00007079 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007080 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007081 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007082
Dan Gohman8ca08852009-05-24 23:25:42 +00007083 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007084 }
7085
Dan Gohmana30370b2009-05-04 22:02:23 +00007086 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007087 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007088 if (Op == Cast->getOperand())
7089 return Cast; // must be loop invariant
7090 return getZeroExtendExpr(Op, Cast->getType());
7091 }
7092
Dan Gohmana30370b2009-05-04 22:02:23 +00007093 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007094 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007095 if (Op == Cast->getOperand())
7096 return Cast; // must be loop invariant
7097 return getSignExtendExpr(Op, Cast->getType());
7098 }
7099
Dan Gohmana30370b2009-05-04 22:02:23 +00007100 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007101 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007102 if (Op == Cast->getOperand())
7103 return Cast; // must be loop invariant
7104 return getTruncateExpr(Op, Cast->getType());
7105 }
7106
Torok Edwinfbcc6632009-07-14 16:55:14 +00007107 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007108}
7109
Dan Gohmanaf752342009-07-07 17:06:11 +00007110const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007111 return getSCEVAtScope(getSCEV(V), L);
7112}
7113
Sanjoy Dasf8570812016-05-29 00:38:22 +00007114/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007115///
7116/// A * X = B (mod N)
7117///
7118/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7119/// A and B isn't important.
7120///
7121/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007122static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007123 ScalarEvolution &SE) {
7124 uint32_t BW = A.getBitWidth();
Eli Friedman10d1ff62017-01-31 00:42:42 +00007125 assert(BW == SE.getTypeSizeInBits(B->getType()));
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007126 assert(A != 0 && "A must be non-zero.");
7127
7128 // 1. D = gcd(A, N)
7129 //
7130 // The gcd of A and N may have only one prime factor: 2. The number of
7131 // trailing zeros in A is its multiplicity
7132 uint32_t Mult2 = A.countTrailingZeros();
7133 // D = 2^Mult2
7134
7135 // 2. Check if B is divisible by D.
7136 //
7137 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7138 // is not less than multiplicity of this prime factor for D.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007139 if (SE.GetMinTrailingZeros(B) < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007140 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007141
7142 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7143 // modulo (N / D).
7144 //
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007145 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7146 // (N / D) in general. The inverse itself always fits into BW bits, though,
7147 // so we immediately truncate it.
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007148 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7149 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007150 Mod.setBit(BW - Mult2); // Mod = N / D
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007151 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007152
7153 // 4. Compute the minimum unsigned root of the equation:
7154 // I * (B / D) mod (N / D)
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007155 // To simplify the computation, we factor out the divide by D:
7156 // (I * B mod N) / D
Eli Friedman10d1ff62017-01-31 00:42:42 +00007157 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7158 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007159}
Chris Lattnerd934c702004-04-02 20:23:17 +00007160
Sanjoy Dasf8570812016-05-29 00:38:22 +00007161/// Find the roots of the quadratic equation for the given quadratic chrec
7162/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7163/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007164///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007165static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007166SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007167 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007168 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7169 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7170 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007171
Chris Lattnerd934c702004-04-02 20:23:17 +00007172 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007173 if (!LC || !MC || !NC)
7174 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007175
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007176 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7177 const APInt &L = LC->getAPInt();
7178 const APInt &M = MC->getAPInt();
7179 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007180 APInt Two(BitWidth, 2);
7181 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007182
Dan Gohmance973df2009-06-24 04:48:43 +00007183 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007184 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007185 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007186 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7187 // The B coefficient is M-N/2
7188 APInt B(M);
7189 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007190
Reid Spencer983e3b32007-03-01 07:25:48 +00007191 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007192 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007193
Reid Spencer983e3b32007-03-01 07:25:48 +00007194 // Compute the B^2-4ac term.
7195 APInt SqrtTerm(B);
7196 SqrtTerm *= B;
7197 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007198
Nick Lewyckyfb780832012-08-01 09:14:36 +00007199 if (SqrtTerm.isNegative()) {
7200 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007201 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007202 }
7203
Reid Spencer983e3b32007-03-01 07:25:48 +00007204 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7205 // integer value or else APInt::sqrt() will assert.
7206 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007207
Dan Gohmance973df2009-06-24 04:48:43 +00007208 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007209 // The divisions must be performed as signed divisions.
7210 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007211 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007212 if (TwoA.isMinValue())
7213 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007214
Owen Anderson47db9412009-07-22 00:24:57 +00007215 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007216
7217 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007218 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007219 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007220 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007221
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007222 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7223 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007224 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007225}
7226
Andrew Trick3ca3f982011-07-26 17:19:55 +00007227ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007228ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007229 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007230
7231 // This is only used for loops with a "x != y" exit test. The exit condition
7232 // is now expressed as a single expression, V = x-y. So the exit test is
7233 // effectively V != 0. We know and take advantage of the fact that this
7234 // expression only being used in a comparison by zero context.
7235
Sanjoy Dasf0022122016-09-28 17:14:58 +00007236 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007237 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007238 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007239 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007240 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007241 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007242 }
7243
Dan Gohman48f82222009-05-04 22:30:44 +00007244 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007245 if (!AddRec && AllowPredicates)
7246 // Try to make this an AddRec using runtime tests, in the first X
7247 // iterations of this loop, where X is the SCEV expression found by the
7248 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007249 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007250
Chris Lattnerd934c702004-04-02 20:23:17 +00007251 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007252 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007253
Chris Lattnerdff679f2011-01-09 22:39:48 +00007254 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7255 // the quadratic equation to solve it.
7256 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007257 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7258 const SCEVConstant *R1 = Roots->first;
7259 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007260 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007261 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7262 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007263 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007264 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007265
Chris Lattnerd934c702004-04-02 20:23:17 +00007266 // We can only use this value if the chrec ends up with an exact zero
7267 // value at this index. When solving for "X*X != 5", for example, we
7268 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007269 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007270 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007271 // We found a quadratic root!
7272 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007273 }
7274 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007275 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007276 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007277
Chris Lattnerdff679f2011-01-09 22:39:48 +00007278 // Otherwise we can only handle this if it is affine.
7279 if (!AddRec->isAffine())
7280 return getCouldNotCompute();
7281
7282 // If this is an affine expression, the execution count of this branch is
7283 // the minimum unsigned root of the following equation:
7284 //
7285 // Start + Step*N = 0 (mod 2^BW)
7286 //
7287 // equivalent to:
7288 //
7289 // Step*N = -Start (mod 2^BW)
7290 //
7291 // where BW is the common bit width of Start and Step.
7292
7293 // Get the initial value for the loop.
7294 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7295 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7296
7297 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007298 //
7299 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7300 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7301 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7302 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007303 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007304 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007305 return getCouldNotCompute();
7306
Andrew Trick8b55b732011-03-14 16:50:06 +00007307 // For positive steps (counting up until unsigned overflow):
7308 // N = -Start/Step (as unsigned)
7309 // For negative steps (counting down to zero):
7310 // N = Start/-Step
7311 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007312 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007313 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007314
7315 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007316 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7317 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007318 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
Eli Friedman83962652017-01-11 20:55:48 +00007319 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
Eli Friedmanbd6deda2017-01-11 21:07:15 +00007320
7321 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7322 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7323 // case, and see if we can improve the bound.
7324 //
7325 // Explicitly handling this here is necessary because getUnsignedRange
7326 // isn't context-sensitive; it doesn't know that we only care about the
7327 // range inside the loop.
7328 const SCEV *Zero = getZero(Distance->getType());
7329 const SCEV *One = getOne(Distance->getType());
7330 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7331 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7332 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7333 // as "unsigned_max(Distance + 1) - 1".
7334 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7335 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7336 }
Eli Friedman83962652017-01-11 20:55:48 +00007337 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007338 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007339
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007340 // If the condition controls loop exit (the loop exits only if the expression
7341 // is true) and the addition is no-wrap we can use unsigned divide to
7342 // compute the backedge count. In this case, the step may not divide the
7343 // distance, but we don't care because if the condition is "missed" the loop
7344 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007345 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7346 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007347 const SCEV *Exact =
7348 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007349 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007350 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007351
Eli Friedman10d1ff62017-01-31 00:42:42 +00007352 // Solve the general equation.
7353 const SCEV *E = SolveLinEquationWithOverflow(
7354 StepC->getAPInt(), getNegativeSCEV(Start), *this);
7355 return ExitLimit(E, E, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007356}
7357
Andrew Trick3ca3f982011-07-26 17:19:55 +00007358ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007359ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007360 // Loops that look like: while (X == 0) are very strange indeed. We don't
7361 // handle them yet except for the trivial case. This could be expanded in the
7362 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007363
Chris Lattnerd934c702004-04-02 20:23:17 +00007364 // If the value is a constant, check to see if it is known to be non-zero
7365 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007366 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007367 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007368 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007369 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007370 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007371
Chris Lattnerd934c702004-04-02 20:23:17 +00007372 // We could implement others, but I really doubt anyone writes loops like
7373 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007374 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007375}
7376
Dan Gohman4e3c1132010-04-15 16:19:08 +00007377std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007378ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007379 // If the block has a unique predecessor, then there is no path from the
7380 // predecessor to the block that does not go through the direct edge
7381 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007382 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007383 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007384
7385 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007386 // If the header has a unique predecessor outside the loop, it must be
7387 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007388 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007389 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007390
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007391 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007392}
7393
Sanjoy Dasf8570812016-05-29 00:38:22 +00007394/// SCEV structural equivalence is usually sufficient for testing whether two
7395/// expressions are equal, however for the purposes of looking for a condition
7396/// guarding a loop, it can be useful to be a little more general, since a
7397/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007398///
Dan Gohmanaf752342009-07-07 17:06:11 +00007399static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007400 // Quick check to see if they are the same SCEV.
7401 if (A == B) return true;
7402
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007403 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7404 // Not all instructions that are "identical" compute the same value. For
7405 // instance, two distinct alloca instructions allocating the same type are
7406 // identical and do not read memory; but compute distinct values.
7407 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7408 };
7409
Dan Gohman450f4e02009-06-20 00:35:32 +00007410 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7411 // two different instructions with the same value. Check for this case.
7412 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7413 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7414 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7415 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007416 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007417 return true;
7418
7419 // Otherwise assume they may have a different value.
7420 return false;
7421}
7422
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007423bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007424 const SCEV *&LHS, const SCEV *&RHS,
7425 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007426 bool Changed = false;
7427
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007428 // If we hit the max recursion limit bail out.
7429 if (Depth >= 3)
7430 return false;
7431
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007432 // Canonicalize a constant to the right side.
7433 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7434 // Check for both operands constant.
7435 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7436 if (ConstantExpr::getICmp(Pred,
7437 LHSC->getValue(),
7438 RHSC->getValue())->isNullValue())
7439 goto trivially_false;
7440 else
7441 goto trivially_true;
7442 }
7443 // Otherwise swap the operands to put the constant on the right.
7444 std::swap(LHS, RHS);
7445 Pred = ICmpInst::getSwappedPredicate(Pred);
7446 Changed = true;
7447 }
7448
7449 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007450 // addrec's loop, put the addrec on the left. Also make a dominance check,
7451 // as both operands could be addrecs loop-invariant in each other's loop.
7452 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7453 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007454 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007455 std::swap(LHS, RHS);
7456 Pred = ICmpInst::getSwappedPredicate(Pred);
7457 Changed = true;
7458 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007459 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007460
7461 // If there's a constant operand, canonicalize comparisons with boundary
7462 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7463 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007464 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007465
7466 bool SimplifiedByConstantRange = false;
7467
7468 if (!ICmpInst::isEquality(Pred)) {
7469 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7470 if (ExactCR.isFullSet())
7471 goto trivially_true;
7472 else if (ExactCR.isEmptySet())
7473 goto trivially_false;
7474
7475 APInt NewRHS;
7476 CmpInst::Predicate NewPred;
7477 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7478 ICmpInst::isEquality(NewPred)) {
7479 // We were able to convert an inequality to an equality.
7480 Pred = NewPred;
7481 RHS = getConstant(NewRHS);
7482 Changed = SimplifiedByConstantRange = true;
7483 }
7484 }
7485
7486 if (!SimplifiedByConstantRange) {
7487 switch (Pred) {
7488 default:
7489 break;
7490 case ICmpInst::ICMP_EQ:
7491 case ICmpInst::ICMP_NE:
7492 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7493 if (!RA)
7494 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7495 if (const SCEVMulExpr *ME =
7496 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7497 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7498 ME->getOperand(0)->isAllOnesValue()) {
7499 RHS = AE->getOperand(1);
7500 LHS = ME->getOperand(1);
7501 Changed = true;
7502 }
7503 break;
7504
7505
7506 // The "Should have been caught earlier!" messages refer to the fact
7507 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7508 // should have fired on the corresponding cases, and canonicalized the
7509 // check to trivially_true or trivially_false.
7510
7511 case ICmpInst::ICMP_UGE:
7512 assert(!RA.isMinValue() && "Should have been caught earlier!");
7513 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007514 RHS = getConstant(RA - 1);
7515 Changed = true;
7516 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007517 case ICmpInst::ICMP_ULE:
7518 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7519 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007520 RHS = getConstant(RA + 1);
7521 Changed = true;
7522 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007523 case ICmpInst::ICMP_SGE:
7524 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7525 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007526 RHS = getConstant(RA - 1);
7527 Changed = true;
7528 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007529 case ICmpInst::ICMP_SLE:
7530 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7531 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007532 RHS = getConstant(RA + 1);
7533 Changed = true;
7534 break;
7535 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007536 }
7537 }
7538
7539 // Check for obvious equality.
7540 if (HasSameValue(LHS, RHS)) {
7541 if (ICmpInst::isTrueWhenEqual(Pred))
7542 goto trivially_true;
7543 if (ICmpInst::isFalseWhenEqual(Pred))
7544 goto trivially_false;
7545 }
7546
Dan Gohman81585c12010-05-03 16:35:17 +00007547 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7548 // adding or subtracting 1 from one of the operands.
7549 switch (Pred) {
7550 case ICmpInst::ICMP_SLE:
7551 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7552 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007553 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007554 Pred = ICmpInst::ICMP_SLT;
7555 Changed = true;
7556 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007557 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007558 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007559 Pred = ICmpInst::ICMP_SLT;
7560 Changed = true;
7561 }
7562 break;
7563 case ICmpInst::ICMP_SGE:
7564 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007565 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007566 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007567 Pred = ICmpInst::ICMP_SGT;
7568 Changed = true;
7569 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7570 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007571 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007572 Pred = ICmpInst::ICMP_SGT;
7573 Changed = true;
7574 }
7575 break;
7576 case ICmpInst::ICMP_ULE:
7577 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007578 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007579 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007580 Pred = ICmpInst::ICMP_ULT;
7581 Changed = true;
7582 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007583 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007584 Pred = ICmpInst::ICMP_ULT;
7585 Changed = true;
7586 }
7587 break;
7588 case ICmpInst::ICMP_UGE:
7589 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007590 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007591 Pred = ICmpInst::ICMP_UGT;
7592 Changed = true;
7593 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007594 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007595 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007596 Pred = ICmpInst::ICMP_UGT;
7597 Changed = true;
7598 }
7599 break;
7600 default:
7601 break;
7602 }
7603
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007604 // TODO: More simplifications are possible here.
7605
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007606 // Recursively simplify until we either hit a recursion limit or nothing
7607 // changes.
7608 if (Changed)
7609 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7610
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007611 return Changed;
7612
7613trivially_true:
7614 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007615 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007616 Pred = ICmpInst::ICMP_EQ;
7617 return true;
7618
7619trivially_false:
7620 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007621 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007622 Pred = ICmpInst::ICMP_NE;
7623 return true;
7624}
7625
Dan Gohmane65c9172009-07-13 21:35:55 +00007626bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7627 return getSignedRange(S).getSignedMax().isNegative();
7628}
7629
7630bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7631 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7632}
7633
7634bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7635 return !getSignedRange(S).getSignedMin().isNegative();
7636}
7637
7638bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7639 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7640}
7641
7642bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7643 return isKnownNegative(S) || isKnownPositive(S);
7644}
7645
7646bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7647 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007648 // Canonicalize the inputs first.
7649 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7650
Dan Gohman07591692010-04-11 22:16:48 +00007651 // If LHS or RHS is an addrec, check to see if the condition is true in
7652 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007653 // If LHS and RHS are both addrec, both conditions must be true in
7654 // every iteration of the loop.
7655 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7656 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7657 bool LeftGuarded = false;
7658 bool RightGuarded = false;
7659 if (LAR) {
7660 const Loop *L = LAR->getLoop();
7661 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7662 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7663 if (!RAR) return true;
7664 LeftGuarded = true;
7665 }
7666 }
7667 if (RAR) {
7668 const Loop *L = RAR->getLoop();
7669 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7670 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7671 if (!LAR) return true;
7672 RightGuarded = true;
7673 }
7674 }
7675 if (LeftGuarded && RightGuarded)
7676 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007677
Sanjoy Das7d910f22015-10-02 18:50:30 +00007678 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7679 return true;
7680
Dan Gohman07591692010-04-11 22:16:48 +00007681 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007682 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007683}
7684
Sanjoy Das5dab2052015-07-27 21:42:49 +00007685bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7686 ICmpInst::Predicate Pred,
7687 bool &Increasing) {
7688 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7689
7690#ifndef NDEBUG
7691 // Verify an invariant: inverting the predicate should turn a monotonically
7692 // increasing change to a monotonically decreasing one, and vice versa.
7693 bool IncreasingSwapped;
7694 bool ResultSwapped = isMonotonicPredicateImpl(
7695 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7696
7697 assert(Result == ResultSwapped && "should be able to analyze both!");
7698 if (ResultSwapped)
7699 assert(Increasing == !IncreasingSwapped &&
7700 "monotonicity should flip as we flip the predicate");
7701#endif
7702
7703 return Result;
7704}
7705
7706bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7707 ICmpInst::Predicate Pred,
7708 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007709
7710 // A zero step value for LHS means the induction variable is essentially a
7711 // loop invariant value. We don't really depend on the predicate actually
7712 // flipping from false to true (for increasing predicates, and the other way
7713 // around for decreasing predicates), all we care about is that *if* the
7714 // predicate changes then it only changes from false to true.
7715 //
7716 // A zero step value in itself is not very useful, but there may be places
7717 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7718 // as general as possible.
7719
Sanjoy Das366acc12015-08-06 20:43:41 +00007720 switch (Pred) {
7721 default:
7722 return false; // Conservative answer
7723
7724 case ICmpInst::ICMP_UGT:
7725 case ICmpInst::ICMP_UGE:
7726 case ICmpInst::ICMP_ULT:
7727 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007728 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007729 return false;
7730
7731 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007732 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007733
7734 case ICmpInst::ICMP_SGT:
7735 case ICmpInst::ICMP_SGE:
7736 case ICmpInst::ICMP_SLT:
7737 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007738 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007739 return false;
7740
7741 const SCEV *Step = LHS->getStepRecurrence(*this);
7742
7743 if (isKnownNonNegative(Step)) {
7744 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7745 return true;
7746 }
7747
7748 if (isKnownNonPositive(Step)) {
7749 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7750 return true;
7751 }
7752
7753 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007754 }
7755
Sanjoy Das5dab2052015-07-27 21:42:49 +00007756 }
7757
Sanjoy Das366acc12015-08-06 20:43:41 +00007758 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007759}
7760
7761bool ScalarEvolution::isLoopInvariantPredicate(
7762 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7763 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7764 const SCEV *&InvariantRHS) {
7765
7766 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7767 if (!isLoopInvariant(RHS, L)) {
7768 if (!isLoopInvariant(LHS, L))
7769 return false;
7770
7771 std::swap(LHS, RHS);
7772 Pred = ICmpInst::getSwappedPredicate(Pred);
7773 }
7774
7775 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7776 if (!ArLHS || ArLHS->getLoop() != L)
7777 return false;
7778
7779 bool Increasing;
7780 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7781 return false;
7782
7783 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7784 // true as the loop iterates, and the backedge is control dependent on
7785 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7786 //
7787 // * if the predicate was false in the first iteration then the predicate
7788 // is never evaluated again, since the loop exits without taking the
7789 // backedge.
7790 // * if the predicate was true in the first iteration then it will
7791 // continue to be true for all future iterations since it is
7792 // monotonically increasing.
7793 //
7794 // For both the above possibilities, we can replace the loop varying
7795 // predicate with its value on the first iteration of the loop (which is
7796 // loop invariant).
7797 //
7798 // A similar reasoning applies for a monotonically decreasing predicate, by
7799 // replacing true with false and false with true in the above two bullets.
7800
7801 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7802
7803 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7804 return false;
7805
7806 InvariantPred = Pred;
7807 InvariantLHS = ArLHS->getStart();
7808 InvariantRHS = RHS;
7809 return true;
7810}
7811
Sanjoy Das401e6312016-02-01 20:48:10 +00007812bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7813 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007814 if (HasSameValue(LHS, RHS))
7815 return ICmpInst::isTrueWhenEqual(Pred);
7816
Dan Gohman07591692010-04-11 22:16:48 +00007817 // This code is split out from isKnownPredicate because it is called from
7818 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007819
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007820 auto CheckRanges =
7821 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7822 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7823 .contains(RangeLHS);
7824 };
7825
7826 // The check at the top of the function catches the case where the values are
7827 // known to be equal.
7828 if (Pred == CmpInst::ICMP_EQ)
7829 return false;
7830
7831 if (Pred == CmpInst::ICMP_NE)
7832 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7833 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7834 isKnownNonZero(getMinusSCEV(LHS, RHS));
7835
7836 if (CmpInst::isSigned(Pred))
7837 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7838
7839 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007840}
7841
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007842bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7843 const SCEV *LHS,
7844 const SCEV *RHS) {
7845
7846 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7847 // Return Y via OutY.
7848 auto MatchBinaryAddToConst =
7849 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7850 SCEV::NoWrapFlags ExpectedFlags) {
7851 const SCEV *NonConstOp, *ConstOp;
7852 SCEV::NoWrapFlags FlagsPresent;
7853
7854 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7855 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7856 return false;
7857
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007858 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007859 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7860 };
7861
7862 APInt C;
7863
7864 switch (Pred) {
7865 default:
7866 break;
7867
7868 case ICmpInst::ICMP_SGE:
7869 std::swap(LHS, RHS);
7870 case ICmpInst::ICMP_SLE:
7871 // X s<= (X + C)<nsw> if C >= 0
7872 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7873 return true;
7874
7875 // (X + C)<nsw> s<= X if C <= 0
7876 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7877 !C.isStrictlyPositive())
7878 return true;
7879 break;
7880
7881 case ICmpInst::ICMP_SGT:
7882 std::swap(LHS, RHS);
7883 case ICmpInst::ICMP_SLT:
7884 // X s< (X + C)<nsw> if C > 0
7885 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7886 C.isStrictlyPositive())
7887 return true;
7888
7889 // (X + C)<nsw> s< X if C < 0
7890 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7891 return true;
7892 break;
7893 }
7894
7895 return false;
7896}
7897
Sanjoy Das7d910f22015-10-02 18:50:30 +00007898bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7899 const SCEV *LHS,
7900 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007901 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007902 return false;
7903
7904 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7905 // the stack can result in exponential time complexity.
7906 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7907
7908 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7909 //
7910 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7911 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7912 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7913 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7914 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007915 return isKnownNonNegative(RHS) &&
7916 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7917 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007918}
7919
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007920bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7921 ICmpInst::Predicate Pred,
7922 const SCEV *LHS, const SCEV *RHS) {
7923 // No need to even try if we know the module has no guards.
7924 if (!HasGuards)
7925 return false;
7926
7927 return any_of(*BB, [&](Instruction &I) {
7928 using namespace llvm::PatternMatch;
7929
7930 Value *Condition;
7931 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7932 m_Value(Condition))) &&
7933 isImpliedCond(Pred, LHS, RHS, Condition, false);
7934 });
7935}
7936
Dan Gohmane65c9172009-07-13 21:35:55 +00007937/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7938/// protected by a conditional between LHS and RHS. This is used to
7939/// to eliminate casts.
7940bool
7941ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7942 ICmpInst::Predicate Pred,
7943 const SCEV *LHS, const SCEV *RHS) {
7944 // Interpret a null as meaning no loop, where there is obviously no guard
7945 // (interprocedural conditions notwithstanding).
7946 if (!L) return true;
7947
Sanjoy Das401e6312016-02-01 20:48:10 +00007948 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7949 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007950
Dan Gohmane65c9172009-07-13 21:35:55 +00007951 BasicBlock *Latch = L->getLoopLatch();
7952 if (!Latch)
7953 return false;
7954
7955 BranchInst *LoopContinuePredicate =
7956 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007957 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7958 isImpliedCond(Pred, LHS, RHS,
7959 LoopContinuePredicate->getCondition(),
7960 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7961 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007962
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007963 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007964 // -- that can lead to O(n!) time complexity.
7965 if (WalkingBEDominatingConds)
7966 return false;
7967
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007968 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007969
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007970 // See if we can exploit a trip count to prove the predicate.
7971 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7972 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7973 if (LatchBECount != getCouldNotCompute()) {
7974 // We know that Latch branches back to the loop header exactly
7975 // LatchBECount times. This means the backdege condition at Latch is
7976 // equivalent to "{0,+,1} u< LatchBECount".
7977 Type *Ty = LatchBECount->getType();
7978 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7979 const SCEV *LoopCounter =
7980 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7981 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7982 LatchBECount))
7983 return true;
7984 }
7985
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007986 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007987 for (auto &AssumeVH : AC.assumptions()) {
7988 if (!AssumeVH)
7989 continue;
7990 auto *CI = cast<CallInst>(AssumeVH);
7991 if (!DT.dominates(CI, Latch->getTerminator()))
7992 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007993
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007994 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7995 return true;
7996 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007997
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007998 // If the loop is not reachable from the entry block, we risk running into an
7999 // infinite loop as we walk up into the dom tree. These loops do not matter
8000 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008001 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008002 return false;
8003
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008004 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8005 return true;
8006
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008007 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8008 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008009
8010 assert(DTN && "should reach the loop header before reaching the root!");
8011
8012 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008013 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8014 return true;
8015
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008016 BasicBlock *PBB = BB->getSinglePredecessor();
8017 if (!PBB)
8018 continue;
8019
8020 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8021 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8022 continue;
8023
8024 Value *Condition = ContinuePredicate->getCondition();
8025
8026 // If we have an edge `E` within the loop body that dominates the only
8027 // latch, the condition guarding `E` also guards the backedge. This
8028 // reasoning works only for loops with a single latch.
8029
8030 BasicBlockEdge DominatingEdge(PBB, BB);
8031 if (DominatingEdge.isSingleEdge()) {
8032 // We're constructively (and conservatively) enumerating edges within the
8033 // loop body that dominate the latch. The dominator tree better agree
8034 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008035 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008036
8037 if (isImpliedCond(Pred, LHS, RHS, Condition,
8038 BB != ContinuePredicate->getSuccessor(0)))
8039 return true;
8040 }
8041 }
8042
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008043 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008044}
8045
Dan Gohmane65c9172009-07-13 21:35:55 +00008046bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008047ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8048 ICmpInst::Predicate Pred,
8049 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008050 // Interpret a null as meaning no loop, where there is obviously no guard
8051 // (interprocedural conditions notwithstanding).
8052 if (!L) return false;
8053
Sanjoy Das401e6312016-02-01 20:48:10 +00008054 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8055 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008056
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008057 // Starting at the loop predecessor, climb up the predecessor chain, as long
8058 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008059 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008060 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008061 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008062 Pair.first;
8063 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008064
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008065 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8066 return true;
8067
Dan Gohman2a62fd92008-08-12 20:17:31 +00008068 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008069 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008070 if (!LoopEntryPredicate ||
8071 LoopEntryPredicate->isUnconditional())
8072 continue;
8073
Dan Gohmane18c2d62010-08-10 23:46:30 +00008074 if (isImpliedCond(Pred, LHS, RHS,
8075 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008076 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008077 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008078 }
8079
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008080 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008081 for (auto &AssumeVH : AC.assumptions()) {
8082 if (!AssumeVH)
8083 continue;
8084 auto *CI = cast<CallInst>(AssumeVH);
8085 if (!DT.dominates(CI, L->getHeader()))
8086 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008087
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008088 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8089 return true;
8090 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008091
Dan Gohman2a62fd92008-08-12 20:17:31 +00008092 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008093}
8094
Dan Gohmane18c2d62010-08-10 23:46:30 +00008095bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008096 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008097 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008098 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008099 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008100 return false;
8101
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008102 auto ClearOnExit =
8103 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8104
Dan Gohman8b0a4192010-03-01 17:49:51 +00008105 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008106 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008107 if (BO->getOpcode() == Instruction::And) {
8108 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008109 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8110 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008111 } else if (BO->getOpcode() == Instruction::Or) {
8112 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008113 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8114 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008115 }
8116 }
8117
Dan Gohmane18c2d62010-08-10 23:46:30 +00008118 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008119 if (!ICI) return false;
8120
Andrew Trickfa594032012-11-29 18:35:13 +00008121 // Now that we found a conditional branch that dominates the loop or controls
8122 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008123 ICmpInst::Predicate FoundPred;
8124 if (Inverse)
8125 FoundPred = ICI->getInversePredicate();
8126 else
8127 FoundPred = ICI->getPredicate();
8128
8129 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8130 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008131
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008132 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8133}
8134
8135bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8136 const SCEV *RHS,
8137 ICmpInst::Predicate FoundPred,
8138 const SCEV *FoundLHS,
8139 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008140 // Balance the types.
8141 if (getTypeSizeInBits(LHS->getType()) <
8142 getTypeSizeInBits(FoundLHS->getType())) {
8143 if (CmpInst::isSigned(Pred)) {
8144 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8145 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8146 } else {
8147 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8148 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8149 }
8150 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008151 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008152 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008153 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8154 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8155 } else {
8156 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8157 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8158 }
8159 }
8160
Dan Gohman430f0cc2009-07-21 23:03:19 +00008161 // Canonicalize the query to match the way instcombine will have
8162 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008163 if (SimplifyICmpOperands(Pred, LHS, RHS))
8164 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008165 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008166 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8167 if (FoundLHS == FoundRHS)
8168 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008169
8170 // Check to see if we can make the LHS or RHS match.
8171 if (LHS == FoundRHS || RHS == FoundLHS) {
8172 if (isa<SCEVConstant>(RHS)) {
8173 std::swap(FoundLHS, FoundRHS);
8174 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8175 } else {
8176 std::swap(LHS, RHS);
8177 Pred = ICmpInst::getSwappedPredicate(Pred);
8178 }
8179 }
8180
8181 // Check whether the found predicate is the same as the desired predicate.
8182 if (FoundPred == Pred)
8183 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8184
8185 // Check whether swapping the found predicate makes it the same as the
8186 // desired predicate.
8187 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8188 if (isa<SCEVConstant>(RHS))
8189 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8190 else
8191 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8192 RHS, LHS, FoundLHS, FoundRHS);
8193 }
8194
Sanjoy Das6e78b172015-10-22 19:57:34 +00008195 // Unsigned comparison is the same as signed comparison when both the operands
8196 // are non-negative.
8197 if (CmpInst::isUnsigned(FoundPred) &&
8198 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8199 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8200 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8201
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008202 // Check if we can make progress by sharpening ranges.
8203 if (FoundPred == ICmpInst::ICMP_NE &&
8204 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8205
8206 const SCEVConstant *C = nullptr;
8207 const SCEV *V = nullptr;
8208
8209 if (isa<SCEVConstant>(FoundLHS)) {
8210 C = cast<SCEVConstant>(FoundLHS);
8211 V = FoundRHS;
8212 } else {
8213 C = cast<SCEVConstant>(FoundRHS);
8214 V = FoundLHS;
8215 }
8216
8217 // The guarding predicate tells us that C != V. If the known range
8218 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8219 // range we consider has to correspond to same signedness as the
8220 // predicate we're interested in folding.
8221
8222 APInt Min = ICmpInst::isSigned(Pred) ?
8223 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8224
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008225 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008226 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8227 // This is true even if (Min + 1) wraps around -- in case of
8228 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8229
8230 APInt SharperMin = Min + 1;
8231
8232 switch (Pred) {
8233 case ICmpInst::ICMP_SGE:
8234 case ICmpInst::ICMP_UGE:
8235 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8236 // RHS, we're done.
8237 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8238 getConstant(SharperMin)))
8239 return true;
8240
8241 case ICmpInst::ICMP_SGT:
8242 case ICmpInst::ICMP_UGT:
8243 // We know from the range information that (V `Pred` Min ||
8244 // V == Min). We know from the guarding condition that !(V
8245 // == Min). This gives us
8246 //
8247 // V `Pred` Min || V == Min && !(V == Min)
8248 // => V `Pred` Min
8249 //
8250 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8251
8252 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8253 return true;
8254
8255 default:
8256 // No change
8257 break;
8258 }
8259 }
8260 }
8261
Dan Gohman430f0cc2009-07-21 23:03:19 +00008262 // Check whether the actual condition is beyond sufficient.
8263 if (FoundPred == ICmpInst::ICMP_EQ)
8264 if (ICmpInst::isTrueWhenEqual(Pred))
8265 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8266 return true;
8267 if (Pred == ICmpInst::ICMP_NE)
8268 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8269 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8270 return true;
8271
8272 // Otherwise assume the worst.
8273 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008274}
8275
Sanjoy Das1ed69102015-10-13 02:53:27 +00008276bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8277 const SCEV *&L, const SCEV *&R,
8278 SCEV::NoWrapFlags &Flags) {
8279 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8280 if (!AE || AE->getNumOperands() != 2)
8281 return false;
8282
8283 L = AE->getOperand(0);
8284 R = AE->getOperand(1);
8285 Flags = AE->getNoWrapFlags();
8286 return true;
8287}
8288
Sanjoy Das0b1af852016-07-23 00:28:56 +00008289Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8290 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008291 // We avoid subtracting expressions here because this function is usually
8292 // fairly deep in the call stack (i.e. is called many times).
8293
Sanjoy Das96709c42015-09-25 23:53:45 +00008294 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8295 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8296 const auto *MAR = cast<SCEVAddRecExpr>(More);
8297
8298 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008299 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008300
8301 // We look at affine expressions only; not for correctness but to keep
8302 // getStepRecurrence cheap.
8303 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008304 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008305
Sanjoy Das1ed69102015-10-13 02:53:27 +00008306 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008307 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008308
8309 Less = LAR->getStart();
8310 More = MAR->getStart();
8311
8312 // fall through
8313 }
8314
8315 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008316 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8317 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008318 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008319 }
8320
8321 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008322 SCEV::NoWrapFlags Flags;
8323 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008324 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008325 if (R == More)
8326 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008327
Sanjoy Das1ed69102015-10-13 02:53:27 +00008328 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008329 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008330 if (R == Less)
8331 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008332
Sanjoy Das0b1af852016-07-23 00:28:56 +00008333 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008334}
8335
8336bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8337 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8338 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8339 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8340 return false;
8341
8342 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8343 if (!AddRecLHS)
8344 return false;
8345
8346 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8347 if (!AddRecFoundLHS)
8348 return false;
8349
8350 // We'd like to let SCEV reason about control dependencies, so we constrain
8351 // both the inequalities to be about add recurrences on the same loop. This
8352 // way we can use isLoopEntryGuardedByCond later.
8353
8354 const Loop *L = AddRecFoundLHS->getLoop();
8355 if (L != AddRecLHS->getLoop())
8356 return false;
8357
8358 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8359 //
8360 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8361 // ... (2)
8362 //
8363 // Informal proof for (2), assuming (1) [*]:
8364 //
8365 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8366 //
8367 // Then
8368 //
8369 // FoundLHS s< FoundRHS s< INT_MIN - C
8370 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8371 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8372 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8373 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8374 // <=> FoundLHS + C s< FoundRHS + C
8375 //
8376 // [*]: (1) can be proved by ruling out overflow.
8377 //
8378 // [**]: This can be proved by analyzing all the four possibilities:
8379 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8380 // (A s>= 0, B s>= 0).
8381 //
8382 // Note:
8383 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8384 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8385 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8386 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8387 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8388 // C)".
8389
Sanjoy Das0b1af852016-07-23 00:28:56 +00008390 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8391 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8392 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008393 return false;
8394
Sanjoy Das0b1af852016-07-23 00:28:56 +00008395 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008396 return true;
8397
Sanjoy Das96709c42015-09-25 23:53:45 +00008398 APInt FoundRHSLimit;
8399
8400 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008401 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008402 } else {
8403 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008404 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008405 }
8406
8407 // Try to prove (1) or (2), as needed.
8408 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8409 getConstant(FoundRHSLimit));
8410}
8411
Dan Gohman430f0cc2009-07-21 23:03:19 +00008412bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8413 const SCEV *LHS, const SCEV *RHS,
8414 const SCEV *FoundLHS,
8415 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008416 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8417 return true;
8418
Sanjoy Das96709c42015-09-25 23:53:45 +00008419 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8420 return true;
8421
Dan Gohman430f0cc2009-07-21 23:03:19 +00008422 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8423 FoundLHS, FoundRHS) ||
8424 // ~x < ~y --> x > y
8425 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8426 getNotSCEV(FoundRHS),
8427 getNotSCEV(FoundLHS));
8428}
8429
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008430
8431/// If Expr computes ~A, return A else return nullptr
8432static const SCEV *MatchNotExpr(const SCEV *Expr) {
8433 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008434 if (!Add || Add->getNumOperands() != 2 ||
8435 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008436 return nullptr;
8437
8438 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008439 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8440 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008441 return nullptr;
8442
8443 return AddRHS->getOperand(1);
8444}
8445
8446
8447/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8448template<typename MaxExprType>
8449static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8450 const SCEV *Candidate) {
8451 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8452 if (!MaxExpr) return false;
8453
Sanjoy Das347d2722015-12-01 07:49:27 +00008454 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008455}
8456
8457
8458/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8459template<typename MaxExprType>
8460static bool IsMinConsistingOf(ScalarEvolution &SE,
8461 const SCEV *MaybeMinExpr,
8462 const SCEV *Candidate) {
8463 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8464 if (!MaybeMaxExpr)
8465 return false;
8466
8467 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8468}
8469
Hal Finkela8d205f2015-08-19 01:51:51 +00008470static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8471 ICmpInst::Predicate Pred,
8472 const SCEV *LHS, const SCEV *RHS) {
8473
8474 // If both sides are affine addrecs for the same loop, with equal
8475 // steps, and we know the recurrences don't wrap, then we only
8476 // need to check the predicate on the starting values.
8477
8478 if (!ICmpInst::isRelational(Pred))
8479 return false;
8480
8481 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8482 if (!LAR)
8483 return false;
8484 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8485 if (!RAR)
8486 return false;
8487 if (LAR->getLoop() != RAR->getLoop())
8488 return false;
8489 if (!LAR->isAffine() || !RAR->isAffine())
8490 return false;
8491
8492 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8493 return false;
8494
Hal Finkelff08a2e2015-08-19 17:26:07 +00008495 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8496 SCEV::FlagNSW : SCEV::FlagNUW;
8497 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008498 return false;
8499
8500 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8501}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008502
8503/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8504/// expression?
8505static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8506 ICmpInst::Predicate Pred,
8507 const SCEV *LHS, const SCEV *RHS) {
8508 switch (Pred) {
8509 default:
8510 return false;
8511
8512 case ICmpInst::ICMP_SGE:
8513 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008514 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008515 case ICmpInst::ICMP_SLE:
8516 return
8517 // min(A, ...) <= A
8518 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8519 // A <= max(A, ...)
8520 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8521
8522 case ICmpInst::ICMP_UGE:
8523 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008524 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008525 case ICmpInst::ICMP_ULE:
8526 return
8527 // min(A, ...) <= A
8528 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8529 // A <= max(A, ...)
8530 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8531 }
8532
8533 llvm_unreachable("covered switch fell through?!");
8534}
8535
Dan Gohmane65c9172009-07-13 21:35:55 +00008536bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008537ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8538 const SCEV *LHS, const SCEV *RHS,
8539 const SCEV *FoundLHS,
8540 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008541 auto IsKnownPredicateFull =
8542 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008543 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008544 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008545 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8546 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008547 };
8548
Dan Gohmane65c9172009-07-13 21:35:55 +00008549 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008550 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8551 case ICmpInst::ICMP_EQ:
8552 case ICmpInst::ICMP_NE:
8553 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8554 return true;
8555 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008556 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008557 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008558 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8559 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008560 return true;
8561 break;
8562 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008563 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008564 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8565 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008566 return true;
8567 break;
8568 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008569 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008570 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8571 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008572 return true;
8573 break;
8574 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008575 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008576 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8577 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008578 return true;
8579 break;
8580 }
8581
8582 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008583}
8584
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008585bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8586 const SCEV *LHS,
8587 const SCEV *RHS,
8588 const SCEV *FoundLHS,
8589 const SCEV *FoundRHS) {
8590 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8591 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8592 // reduce the compile time impact of this optimization.
8593 return false;
8594
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008595 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008596 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008597 return false;
8598
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008599 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008600
8601 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8602 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8603 ConstantRange FoundLHSRange =
8604 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8605
Sanjoy Das095f5b22016-07-22 20:47:55 +00008606 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8607 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008608
8609 // We can also compute the range of values for `LHS` that satisfy the
8610 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008611 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008612 ConstantRange SatisfyingLHSRange =
8613 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8614
8615 // The antecedent implies the consequent if every value of `LHS` that
8616 // satisfies the antecedent also satisfies the consequent.
8617 return SatisfyingLHSRange.contains(LHSRange);
8618}
8619
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008620bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8621 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008622 assert(isKnownPositive(Stride) && "Positive stride expected!");
8623
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008624 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008625
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008626 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008627 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008628
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008629 if (IsSigned) {
8630 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8631 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8632 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8633 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008634
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008635 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8636 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008637 }
Dan Gohman01048422009-06-21 23:46:38 +00008638
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008639 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8640 APInt MaxValue = APInt::getMaxValue(BitWidth);
8641 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8642 .getUnsignedMax();
8643
8644 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8645 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8646}
8647
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008648bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8649 bool IsSigned, bool NoWrap) {
8650 if (NoWrap) return false;
8651
8652 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008653 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008654
8655 if (IsSigned) {
8656 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8657 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8658 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8659 .getSignedMax();
8660
8661 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8662 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8663 }
8664
8665 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8666 APInt MinValue = APInt::getMinValue(BitWidth);
8667 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8668 .getUnsignedMax();
8669
8670 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8671 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8672}
8673
Johannes Doerfert2683e562015-02-09 12:34:23 +00008674const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008675 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008676 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008677 Delta = Equality ? getAddExpr(Delta, Step)
8678 : getAddExpr(Delta, getMinusSCEV(Step, One));
8679 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008680}
8681
Andrew Trick3ca3f982011-07-26 17:19:55 +00008682ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008683ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008684 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008685 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008686 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008687 // We handle only IV < Invariant
8688 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008689 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008690
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008691 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008692 bool PredicatedIV = false;
8693
8694 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008695 // Try to make this an AddRec using runtime tests, in the first X
8696 // iterations of this loop, where X is the SCEV expression found by the
8697 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008698 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008699 PredicatedIV = true;
8700 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008701
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008702 // Avoid weird loops
8703 if (!IV || IV->getLoop() != L || !IV->isAffine())
8704 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008705
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008706 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008707 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008708
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008709 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008710
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008711 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008712
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008713 // Avoid negative or zero stride values.
8714 if (!PositiveStride) {
8715 // We can compute the correct backedge taken count for loops with unknown
8716 // strides if we can prove that the loop is not an infinite loop with side
8717 // effects. Here's the loop structure we are trying to handle -
8718 //
8719 // i = start
8720 // do {
8721 // A[i] = i;
8722 // i += s;
8723 // } while (i < end);
8724 //
8725 // The backedge taken count for such loops is evaluated as -
8726 // (max(end, start + stride) - start - 1) /u stride
8727 //
8728 // The additional preconditions that we need to check to prove correctness
8729 // of the above formula is as follows -
8730 //
8731 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8732 // NoWrap flag).
8733 // b) loop is single exit with no side effects.
8734 //
8735 //
8736 // Precondition a) implies that if the stride is negative, this is a single
8737 // trip loop. The backedge taken count formula reduces to zero in this case.
8738 //
8739 // Precondition b) implies that the unknown stride cannot be zero otherwise
8740 // we have UB.
8741 //
8742 // The positive stride case is the same as isKnownPositive(Stride) returning
8743 // true (original behavior of the function).
8744 //
8745 // We want to make sure that the stride is truly unknown as there are edge
8746 // cases where ScalarEvolution propagates no wrap flags to the
8747 // post-increment/decrement IV even though the increment/decrement operation
8748 // itself is wrapping. The computed backedge taken count may be wrong in
8749 // such cases. This is prevented by checking that the stride is not known to
8750 // be either positive or non-positive. For example, no wrap flags are
8751 // propagated to the post-increment IV of this loop with a trip count of 2 -
8752 //
8753 // unsigned char i;
8754 // for(i=127; i<128; i+=129)
8755 // A[i] = i;
8756 //
8757 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8758 !loopHasNoSideEffects(L))
8759 return getCouldNotCompute();
8760
8761 } else if (!Stride->isOne() &&
8762 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8763 // Avoid proven overflow cases: this will ensure that the backedge taken
8764 // count will not generate any unsigned overflow. Relaxed no-overflow
8765 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8766 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008767 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008768
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008769 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8770 : ICmpInst::ICMP_ULT;
8771 const SCEV *Start = IV->getStart();
8772 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00008773 // If the backedge is taken at least once, then it will be taken
8774 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8775 // is the LHS value of the less-than comparison the first time it is evaluated
8776 // and End is the RHS.
8777 const SCEV *BECountIfBackedgeTaken =
8778 computeBECount(getMinusSCEV(End, Start), Stride, false);
8779 // If the loop entry is guarded by the result of the backedge test of the
8780 // first loop iteration, then we know the backedge will be taken at least
8781 // once and so the backedge taken count is as above. If not then we use the
8782 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8783 // as if the backedge is taken at least once max(End,Start) is End and so the
8784 // result is as above, and if not max(End,Start) is Start so we get a backedge
8785 // count of zero.
8786 const SCEV *BECount;
8787 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8788 BECount = BECountIfBackedgeTaken;
8789 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008790 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00008791 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8792 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008793
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008794 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00008795 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008796 if (isa<SCEVConstant>(BECount))
8797 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00008798 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00008799 // If we know exactly how many times the backedge will be taken if it's
8800 // taken at least once, then the backedge count will either be that or
8801 // zero.
8802 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00008803 MaxOrZero = true;
8804 } else {
John Brawnecf79302016-10-18 10:10:53 +00008805 // Calculate the maximum backedge count based on the range of values
8806 // permitted by Start, End, and Stride.
8807 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8808 : getUnsignedRange(Start).getUnsignedMin();
8809
8810 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8811
8812 APInt StrideForMaxBECount;
8813
8814 if (PositiveStride)
8815 StrideForMaxBECount =
8816 IsSigned ? getSignedRange(Stride).getSignedMin()
8817 : getUnsignedRange(Stride).getUnsignedMin();
8818 else
8819 // Using a stride of 1 is safe when computing max backedge taken count for
8820 // a loop with unknown stride.
8821 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8822
8823 APInt Limit =
8824 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8825 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8826
8827 // Although End can be a MAX expression we estimate MaxEnd considering only
8828 // the case End = RHS. This is safe because in the other case (End - Start)
8829 // is zero, leading to a zero maximum backedge taken count.
8830 APInt MaxEnd =
8831 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8832 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8833
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008834 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008835 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00008836 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008837
8838 if (isa<SCEVCouldNotCompute>(MaxBECount))
8839 MaxBECount = BECount;
8840
John Brawn84b21832016-10-21 11:08:48 +00008841 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008842}
8843
8844ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008845ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008846 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008847 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008848 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008849 // We handle only IV > Invariant
8850 if (!isLoopInvariant(RHS, L))
8851 return getCouldNotCompute();
8852
8853 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008854 if (!IV && AllowPredicates)
8855 // Try to make this an AddRec using runtime tests, in the first X
8856 // iterations of this loop, where X is the SCEV expression found by the
8857 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008858 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008859
8860 // Avoid weird loops
8861 if (!IV || IV->getLoop() != L || !IV->isAffine())
8862 return getCouldNotCompute();
8863
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008864 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008865 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8866
8867 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8868
8869 // Avoid negative or zero stride values
8870 if (!isKnownPositive(Stride))
8871 return getCouldNotCompute();
8872
8873 // Avoid proven overflow cases: this will ensure that the backedge taken count
8874 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008875 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008876 // behaviors like the case of C language.
8877 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8878 return getCouldNotCompute();
8879
8880 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8881 : ICmpInst::ICMP_UGT;
8882
8883 const SCEV *Start = IV->getStart();
8884 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008885 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8886 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008887
8888 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8889
8890 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8891 : getUnsignedRange(Start).getUnsignedMax();
8892
8893 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8894 : getUnsignedRange(Stride).getUnsignedMin();
8895
8896 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8897 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8898 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8899
8900 // Although End can be a MIN expression we estimate MinEnd considering only
8901 // the case End = RHS. This is safe because in the other case (Start - End)
8902 // is zero, leading to a zero maximum backedge taken count.
8903 APInt MinEnd =
8904 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8905 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8906
8907
8908 const SCEV *MaxBECount = getCouldNotCompute();
8909 if (isa<SCEVConstant>(BECount))
8910 MaxBECount = BECount;
8911 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008912 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008913 getConstant(MinStride), false);
8914
8915 if (isa<SCEVCouldNotCompute>(MaxBECount))
8916 MaxBECount = BECount;
8917
John Brawn84b21832016-10-21 11:08:48 +00008918 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00008919}
8920
Benjamin Kramerc321e532016-06-08 19:09:22 +00008921const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008922 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008923 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008924 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008925
8926 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008927 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008928 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008929 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008930 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008931 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008932 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008933 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008934 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008935 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008936 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008937 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008938 }
8939
8940 // The only time we can solve this is when we have all constant indices.
8941 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008942 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008943 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008944
8945 // Okay at this point we know that all elements of the chrec are constants and
8946 // that the start element is zero.
8947
8948 // First check to see if the range contains zero. If not, the first
8949 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008950 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008951 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008952 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008953
Chris Lattnerd934c702004-04-02 20:23:17 +00008954 if (isAffine()) {
8955 // If this is an affine expression then we have this situation:
8956 // Solve {0,+,A} in Range === Ax in Range
8957
Nick Lewycky52460262007-07-16 02:08:00 +00008958 // We know that zero is in the range. If A is positive then we know that
8959 // the upper value of the range must be the first possible exit value.
8960 // If A is negative then the lower of the range is the last possible loop
8961 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008962 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008963 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008964 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008965
Nick Lewycky52460262007-07-16 02:08:00 +00008966 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008967 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008968 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008969
8970 // Evaluate at the exit value. If we really did fall out of the valid
8971 // range, then we computed our trip count, otherwise wrap around or other
8972 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008973 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008974 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008975 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008976
8977 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008978 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008979 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008980 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008981 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008982 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008983 } else if (isQuadratic()) {
8984 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8985 // quadratic equation to solve it. To do this, we must frame our problem in
8986 // terms of figuring out when zero is crossed, instead of when
8987 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008988 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008989 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00008990 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008991
8992 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008993 if (auto Roots =
8994 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008995 const SCEVConstant *R1 = Roots->first;
8996 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008997 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008998 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8999 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00009000 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00009001 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00009002
Chris Lattnerd934c702004-04-02 20:23:17 +00009003 // Make sure the root is not off by one. The returned iteration should
9004 // not be in the range, but the previous one should be. When solving
9005 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00009006 ConstantInt *R1Val =
9007 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009008 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009009 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009010 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009011 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009012
Dan Gohmana37eaf22007-10-22 18:31:58 +00009013 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009014 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009015 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00009016 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009017 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009018
Chris Lattnerd934c702004-04-02 20:23:17 +00009019 // If R1 was not in the range, then it is a good return value. Make
9020 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009021 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009022 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009023 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009024 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009025 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00009026 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009027 }
9028 }
9029 }
9030
Dan Gohman31efa302009-04-18 17:58:19 +00009031 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009032}
9033
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009034// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009035static inline bool containsUndefs(const SCEV *S) {
9036 return SCEVExprContains(S, [](const SCEV *S) {
9037 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9038 return isa<UndefValue>(SU->getValue());
9039 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9040 return isa<UndefValue>(SC->getValue());
9041 return false;
9042 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009043}
9044
9045namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009046// Collect all steps of SCEV expressions.
9047struct SCEVCollectStrides {
9048 ScalarEvolution &SE;
9049 SmallVectorImpl<const SCEV *> &Strides;
9050
9051 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9052 : SE(SE), Strides(S) {}
9053
9054 bool follow(const SCEV *S) {
9055 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9056 Strides.push_back(AR->getStepRecurrence(SE));
9057 return true;
9058 }
9059 bool isDone() const { return false; }
9060};
9061
9062// Collect all SCEVUnknown and SCEVMulExpr expressions.
9063struct SCEVCollectTerms {
9064 SmallVectorImpl<const SCEV *> &Terms;
9065
9066 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9067 : Terms(T) {}
9068
9069 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009070 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9071 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009072 if (!containsUndefs(S))
9073 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009074
9075 // Stop recursion: once we collected a term, do not walk its operands.
9076 return false;
9077 }
9078
9079 // Keep looking.
9080 return true;
9081 }
9082 bool isDone() const { return false; }
9083};
Tobias Grosser374bce02015-10-12 08:02:00 +00009084
9085// Check if a SCEV contains an AddRecExpr.
9086struct SCEVHasAddRec {
9087 bool &ContainsAddRec;
9088
9089 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9090 ContainsAddRec = false;
9091 }
9092
9093 bool follow(const SCEV *S) {
9094 if (isa<SCEVAddRecExpr>(S)) {
9095 ContainsAddRec = true;
9096
9097 // Stop recursion: once we collected a term, do not walk its operands.
9098 return false;
9099 }
9100
9101 // Keep looking.
9102 return true;
9103 }
9104 bool isDone() const { return false; }
9105};
9106
9107// Find factors that are multiplied with an expression that (possibly as a
9108// subexpression) contains an AddRecExpr. In the expression:
9109//
9110// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9111//
9112// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9113// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9114// parameters as they form a product with an induction variable.
9115//
9116// This collector expects all array size parameters to be in the same MulExpr.
9117// It might be necessary to later add support for collecting parameters that are
9118// spread over different nested MulExpr.
9119struct SCEVCollectAddRecMultiplies {
9120 SmallVectorImpl<const SCEV *> &Terms;
9121 ScalarEvolution &SE;
9122
9123 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9124 : Terms(T), SE(SE) {}
9125
9126 bool follow(const SCEV *S) {
9127 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9128 bool HasAddRec = false;
9129 SmallVector<const SCEV *, 0> Operands;
9130 for (auto Op : Mul->operands()) {
9131 if (isa<SCEVUnknown>(Op)) {
9132 Operands.push_back(Op);
9133 } else {
9134 bool ContainsAddRec;
9135 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9136 visitAll(Op, ContiansAddRec);
9137 HasAddRec |= ContainsAddRec;
9138 }
9139 }
9140 if (Operands.size() == 0)
9141 return true;
9142
9143 if (!HasAddRec)
9144 return false;
9145
9146 Terms.push_back(SE.getMulExpr(Operands));
9147 // Stop recursion: once we collected a term, do not walk its operands.
9148 return false;
9149 }
9150
9151 // Keep looking.
9152 return true;
9153 }
9154 bool isDone() const { return false; }
9155};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009156}
Sebastian Pop448712b2014-05-07 18:01:20 +00009157
Tobias Grosser374bce02015-10-12 08:02:00 +00009158/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9159/// two places:
9160/// 1) The strides of AddRec expressions.
9161/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009162void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9163 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009164 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009165 SCEVCollectStrides StrideCollector(*this, Strides);
9166 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009167
9168 DEBUG({
9169 dbgs() << "Strides:\n";
9170 for (const SCEV *S : Strides)
9171 dbgs() << *S << "\n";
9172 });
9173
9174 for (const SCEV *S : Strides) {
9175 SCEVCollectTerms TermCollector(Terms);
9176 visitAll(S, TermCollector);
9177 }
9178
9179 DEBUG({
9180 dbgs() << "Terms:\n";
9181 for (const SCEV *T : Terms)
9182 dbgs() << *T << "\n";
9183 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009184
9185 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9186 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009187}
9188
Sebastian Popb1a548f2014-05-12 19:01:53 +00009189static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009190 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009191 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009192 int Last = Terms.size() - 1;
9193 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009194
Sebastian Pop448712b2014-05-07 18:01:20 +00009195 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009196 if (Last == 0) {
9197 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009198 SmallVector<const SCEV *, 2> Qs;
9199 for (const SCEV *Op : M->operands())
9200 if (!isa<SCEVConstant>(Op))
9201 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009202
Sebastian Pope30bd352014-05-27 22:41:56 +00009203 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009204 }
9205
Sebastian Pope30bd352014-05-27 22:41:56 +00009206 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009207 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009208 }
9209
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009210 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009211 // Normalize the terms before the next call to findArrayDimensionsRec.
9212 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009213 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009214
9215 // Bail out when GCD does not evenly divide one of the terms.
9216 if (!R->isZero())
9217 return false;
9218
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009219 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009220 }
9221
Tobias Grosser3080cf12014-05-08 07:55:34 +00009222 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009223 Terms.erase(
9224 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9225 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009226
Sebastian Pop448712b2014-05-07 18:01:20 +00009227 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009228 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9229 return false;
9230
Sebastian Pope30bd352014-05-27 22:41:56 +00009231 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009232 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009233}
Sebastian Popc62c6792013-11-12 22:47:20 +00009234
Sebastian Pop448712b2014-05-07 18:01:20 +00009235
9236// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009237static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009238 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009239 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009240 return true;
9241 return false;
9242}
9243
9244// Return the number of product terms in S.
9245static inline int numberOfTerms(const SCEV *S) {
9246 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9247 return Expr->getNumOperands();
9248 return 1;
9249}
9250
Sebastian Popa6e58602014-05-27 22:41:45 +00009251static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9252 if (isa<SCEVConstant>(T))
9253 return nullptr;
9254
9255 if (isa<SCEVUnknown>(T))
9256 return T;
9257
9258 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9259 SmallVector<const SCEV *, 2> Factors;
9260 for (const SCEV *Op : M->operands())
9261 if (!isa<SCEVConstant>(Op))
9262 Factors.push_back(Op);
9263
9264 return SE.getMulExpr(Factors);
9265 }
9266
9267 return T;
9268}
9269
9270/// Return the size of an element read or written by Inst.
9271const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9272 Type *Ty;
9273 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9274 Ty = Store->getValueOperand()->getType();
9275 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009276 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009277 else
9278 return nullptr;
9279
9280 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9281 return getSizeOfExpr(ETy, Ty);
9282}
9283
Sebastian Popa6e58602014-05-27 22:41:45 +00009284void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9285 SmallVectorImpl<const SCEV *> &Sizes,
9286 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009287 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009288 return;
9289
9290 // Early return when Terms do not contain parameters: we do not delinearize
9291 // non parametric SCEVs.
9292 if (!containsParameters(Terms))
9293 return;
9294
9295 DEBUG({
9296 dbgs() << "Terms:\n";
9297 for (const SCEV *T : Terms)
9298 dbgs() << *T << "\n";
9299 });
9300
9301 // Remove duplicates.
9302 std::sort(Terms.begin(), Terms.end());
9303 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9304
9305 // Put larger terms first.
9306 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9307 return numberOfTerms(LHS) > numberOfTerms(RHS);
9308 });
9309
Sebastian Popa6e58602014-05-27 22:41:45 +00009310 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9311
Tobias Grosser374bce02015-10-12 08:02:00 +00009312 // Try to divide all terms by the element size. If term is not divisible by
9313 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009314 for (const SCEV *&Term : Terms) {
9315 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009316 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009317 if (!Q->isZero())
9318 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009319 }
9320
9321 SmallVector<const SCEV *, 4> NewTerms;
9322
9323 // Remove constant factors.
9324 for (const SCEV *T : Terms)
9325 if (const SCEV *NewT = removeConstantFactors(SE, T))
9326 NewTerms.push_back(NewT);
9327
Sebastian Pop448712b2014-05-07 18:01:20 +00009328 DEBUG({
9329 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009330 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009331 dbgs() << *T << "\n";
9332 });
9333
Sebastian Popa6e58602014-05-27 22:41:45 +00009334 if (NewTerms.empty() ||
9335 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009336 Sizes.clear();
9337 return;
9338 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009339
Sebastian Popa6e58602014-05-27 22:41:45 +00009340 // The last element to be pushed into Sizes is the size of an element.
9341 Sizes.push_back(ElementSize);
9342
Sebastian Pop448712b2014-05-07 18:01:20 +00009343 DEBUG({
9344 dbgs() << "Sizes:\n";
9345 for (const SCEV *S : Sizes)
9346 dbgs() << *S << "\n";
9347 });
9348}
9349
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009350void ScalarEvolution::computeAccessFunctions(
9351 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9352 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009353
Sebastian Popb1a548f2014-05-12 19:01:53 +00009354 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009355 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009356 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009357
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009358 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009359 if (!AR->isAffine())
9360 return;
9361
9362 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009363 int Last = Sizes.size() - 1;
9364 for (int i = Last; i >= 0; i--) {
9365 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009366 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009367
9368 DEBUG({
9369 dbgs() << "Res: " << *Res << "\n";
9370 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9371 dbgs() << "Res divided by Sizes[i]:\n";
9372 dbgs() << "Quotient: " << *Q << "\n";
9373 dbgs() << "Remainder: " << *R << "\n";
9374 });
9375
9376 Res = Q;
9377
Sebastian Popa6e58602014-05-27 22:41:45 +00009378 // Do not record the last subscript corresponding to the size of elements in
9379 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009380 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009381
9382 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009383 if (isa<SCEVAddRecExpr>(R)) {
9384 Subscripts.clear();
9385 Sizes.clear();
9386 return;
9387 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009388
Sebastian Pop448712b2014-05-07 18:01:20 +00009389 continue;
9390 }
9391
9392 // Record the access function for the current subscript.
9393 Subscripts.push_back(R);
9394 }
9395
9396 // Also push in last position the remainder of the last division: it will be
9397 // the access function of the innermost dimension.
9398 Subscripts.push_back(Res);
9399
9400 std::reverse(Subscripts.begin(), Subscripts.end());
9401
9402 DEBUG({
9403 dbgs() << "Subscripts:\n";
9404 for (const SCEV *S : Subscripts)
9405 dbgs() << *S << "\n";
9406 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009407}
9408
Sebastian Popc62c6792013-11-12 22:47:20 +00009409/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9410/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009411/// is the offset start of the array. The SCEV->delinearize algorithm computes
9412/// the multiples of SCEV coefficients: that is a pattern matching of sub
9413/// expressions in the stride and base of a SCEV corresponding to the
9414/// computation of a GCD (greatest common divisor) of base and stride. When
9415/// SCEV->delinearize fails, it returns the SCEV unchanged.
9416///
9417/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9418///
9419/// void foo(long n, long m, long o, double A[n][m][o]) {
9420///
9421/// for (long i = 0; i < n; i++)
9422/// for (long j = 0; j < m; j++)
9423/// for (long k = 0; k < o; k++)
9424/// A[i][j][k] = 1.0;
9425/// }
9426///
9427/// the delinearization input is the following AddRec SCEV:
9428///
9429/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9430///
9431/// From this SCEV, we are able to say that the base offset of the access is %A
9432/// because it appears as an offset that does not divide any of the strides in
9433/// the loops:
9434///
9435/// CHECK: Base offset: %A
9436///
9437/// and then SCEV->delinearize determines the size of some of the dimensions of
9438/// the array as these are the multiples by which the strides are happening:
9439///
9440/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9441///
9442/// Note that the outermost dimension remains of UnknownSize because there are
9443/// no strides that would help identifying the size of the last dimension: when
9444/// the array has been statically allocated, one could compute the size of that
9445/// dimension by dividing the overall size of the array by the size of the known
9446/// dimensions: %m * %o * 8.
9447///
9448/// Finally delinearize provides the access functions for the array reference
9449/// that does correspond to A[i][j][k] of the above C testcase:
9450///
9451/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9452///
9453/// The testcases are checking the output of a function pass:
9454/// DelinearizationPass that walks through all loads and stores of a function
9455/// asking for the SCEV of the memory access with respect to all enclosing
9456/// loops, calling SCEV->delinearize on that and printing the results.
9457
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009458void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009459 SmallVectorImpl<const SCEV *> &Subscripts,
9460 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009461 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009462 // First step: collect parametric terms.
9463 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009464 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009465
Sebastian Popb1a548f2014-05-12 19:01:53 +00009466 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009467 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009468
Sebastian Pop448712b2014-05-07 18:01:20 +00009469 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009470 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009471
Sebastian Popb1a548f2014-05-12 19:01:53 +00009472 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009473 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009474
Sebastian Pop448712b2014-05-07 18:01:20 +00009475 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009476 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009477
Sebastian Pop28e6b972014-05-27 22:41:51 +00009478 if (Subscripts.empty())
9479 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009480
Sebastian Pop448712b2014-05-07 18:01:20 +00009481 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009482 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009483 dbgs() << "ArrayDecl[UnknownSize]";
9484 for (const SCEV *S : Sizes)
9485 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009486
Sebastian Pop444621a2014-05-09 22:45:02 +00009487 dbgs() << "\nArrayRef";
9488 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009489 dbgs() << "[" << *S << "]";
9490 dbgs() << "\n";
9491 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009492}
Chris Lattnerd934c702004-04-02 20:23:17 +00009493
9494//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009495// SCEVCallbackVH Class Implementation
9496//===----------------------------------------------------------------------===//
9497
Dan Gohmand33a0902009-05-19 19:22:47 +00009498void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009499 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009500 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9501 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009502 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009503 // this now dangles!
9504}
9505
Dan Gohman7a066722010-07-28 01:09:07 +00009506void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009507 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009508
Dan Gohman48f82222009-05-04 22:30:44 +00009509 // Forget all the expressions associated with users of the old value,
9510 // so that future queries will recompute the expressions using the new
9511 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009512 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009513 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009514 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009515 while (!Worklist.empty()) {
9516 User *U = Worklist.pop_back_val();
9517 // Deleting the Old value will cause this to dangle. Postpone
9518 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009519 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009520 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009521 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009522 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009523 if (PHINode *PN = dyn_cast<PHINode>(U))
9524 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009525 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009526 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009527 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009528 // Delete the Old value.
9529 if (PHINode *PN = dyn_cast<PHINode>(Old))
9530 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009531 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009532 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009533}
9534
Dan Gohmand33a0902009-05-19 19:22:47 +00009535ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009536 : CallbackVH(V), SE(se) {}
9537
9538//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009539// ScalarEvolution Class Implementation
9540//===----------------------------------------------------------------------===//
9541
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009542ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009543 AssumptionCache &AC, DominatorTree &DT,
9544 LoopInfo &LI)
9545 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009546 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009547 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9548 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009549 FirstUnknown(nullptr) {
9550
9551 // To use guards for proving predicates, we need to scan every instruction in
9552 // relevant basic blocks, and not just terminators. Doing this is a waste of
9553 // time if the IR does not actually contain any calls to
9554 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9555 //
9556 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9557 // to _add_ guards to the module when there weren't any before, and wants
9558 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9559 // efficient in lieu of being smart in that rather obscure case.
9560
9561 auto *GuardDecl = F.getParent()->getFunction(
9562 Intrinsic::getName(Intrinsic::experimental_guard));
9563 HasGuards = GuardDecl && !GuardDecl->use_empty();
9564}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009565
9566ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009567 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009568 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009569 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009570 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009571 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00009572 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009573 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009574 PredicatedBackedgeTakenCounts(
9575 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009576 ConstantEvolutionLoopExitValue(
9577 std::move(Arg.ConstantEvolutionLoopExitValue)),
9578 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9579 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009580 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009581 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009582 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9583 SignedRanges(std::move(Arg.SignedRanges)),
9584 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009585 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009586 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9587 FirstUnknown(Arg.FirstUnknown) {
9588 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009589}
9590
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009591ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009592 // Iterate through all the SCEVUnknown instances and call their
9593 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009594 for (SCEVUnknown *U = FirstUnknown; U;) {
9595 SCEVUnknown *Tmp = U;
9596 U = U->Next;
9597 Tmp->~SCEVUnknown();
9598 }
Craig Topper9f008862014-04-15 04:59:12 +00009599 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009600
Wei Mia49559b2016-02-04 01:27:38 +00009601 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009602 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009603 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009604
9605 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9606 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009607 for (auto &BTCI : BackedgeTakenCounts)
9608 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009609 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9610 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009611
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009612 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009613 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009614 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009615}
9616
Dan Gohmanc8e23622009-04-21 23:15:49 +00009617bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009618 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009619}
9620
Dan Gohmanc8e23622009-04-21 23:15:49 +00009621static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009622 const Loop *L) {
9623 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009624 for (Loop *I : *L)
9625 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009626
Dan Gohmanbc694912010-01-09 18:17:45 +00009627 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009628 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009629 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009630
Dan Gohmancb0efec2009-12-18 01:14:11 +00009631 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009632 L->getExitBlocks(ExitBlocks);
9633 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009634 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009635
Dan Gohman0bddac12009-02-24 18:55:53 +00009636 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9637 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009638 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009639 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009640 }
9641
Dan Gohmanbc694912010-01-09 18:17:45 +00009642 OS << "\n"
9643 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009644 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009645 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009646
9647 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9648 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009649 if (SE->isBackedgeTakenCountMaxOrZero(L))
9650 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009651 } else {
9652 OS << "Unpredictable max backedge-taken count. ";
9653 }
9654
Silviu Baranga6f444df2016-04-08 14:29:09 +00009655 OS << "\n"
9656 "Loop ";
9657 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9658 OS << ": ";
9659
9660 SCEVUnionPredicate Pred;
9661 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9662 if (!isa<SCEVCouldNotCompute>(PBT)) {
9663 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9664 OS << " Predicates:\n";
9665 Pred.print(OS, 4);
9666 } else {
9667 OS << "Unpredictable predicated backedge-taken count. ";
9668 }
Dan Gohman69942932009-06-24 00:33:16 +00009669 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009670}
9671
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009672static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9673 switch (LD) {
9674 case ScalarEvolution::LoopVariant:
9675 return "Variant";
9676 case ScalarEvolution::LoopInvariant:
9677 return "Invariant";
9678 case ScalarEvolution::LoopComputable:
9679 return "Computable";
9680 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009681 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009682}
9683
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009684void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009685 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009686 // out SCEV values of all instructions that are interesting. Doing
9687 // this potentially causes it to create new SCEV objects though,
9688 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009689 // observable from outside the class though, so casting away the
9690 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009691 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009692
Dan Gohmanbc694912010-01-09 18:17:45 +00009693 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009694 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009695 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009696 for (Instruction &I : instructions(F))
9697 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9698 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009699 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009700 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009701 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009702 if (!isa<SCEVCouldNotCompute>(SV)) {
9703 OS << " U: ";
9704 SE.getUnsignedRange(SV).print(OS);
9705 OS << " S: ";
9706 SE.getSignedRange(SV).print(OS);
9707 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009708
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009709 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009710
Dan Gohmanaf752342009-07-07 17:06:11 +00009711 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009712 if (AtUse != SV) {
9713 OS << " --> ";
9714 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009715 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9716 OS << " U: ";
9717 SE.getUnsignedRange(AtUse).print(OS);
9718 OS << " S: ";
9719 SE.getSignedRange(AtUse).print(OS);
9720 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009721 }
9722
9723 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009724 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009725 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009726 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009727 OS << "<<Unknown>>";
9728 } else {
9729 OS << *ExitValue;
9730 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009731
9732 bool First = true;
9733 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9734 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009735 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009736 First = false;
9737 } else {
9738 OS << ", ";
9739 }
9740
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009741 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9742 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009743 }
9744
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009745 for (auto *InnerL : depth_first(L)) {
9746 if (InnerL == L)
9747 continue;
9748 if (First) {
9749 OS << "\t\t" "LoopDispositions: { ";
9750 First = false;
9751 } else {
9752 OS << ", ";
9753 }
9754
9755 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9756 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9757 }
9758
9759 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009760 }
9761
Chris Lattnerd934c702004-04-02 20:23:17 +00009762 OS << "\n";
9763 }
9764
Dan Gohmanbc694912010-01-09 18:17:45 +00009765 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009766 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009767 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009768 for (Loop *I : LI)
9769 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009770}
Dan Gohmane20f8242009-04-21 00:47:46 +00009771
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009772ScalarEvolution::LoopDisposition
9773ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009774 auto &Values = LoopDispositions[S];
9775 for (auto &V : Values) {
9776 if (V.getPointer() == L)
9777 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009778 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009779 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009780 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009781 auto &Values2 = LoopDispositions[S];
9782 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9783 if (V.getPointer() == L) {
9784 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009785 break;
9786 }
9787 }
9788 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009789}
9790
9791ScalarEvolution::LoopDisposition
9792ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009793 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009794 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009795 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009796 case scTruncate:
9797 case scZeroExtend:
9798 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009799 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009800 case scAddRecExpr: {
9801 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9802
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009803 // If L is the addrec's loop, it's computable.
9804 if (AR->getLoop() == L)
9805 return LoopComputable;
9806
Dan Gohmanafd6db92010-11-17 21:23:15 +00009807 // Add recurrences are never invariant in the function-body (null loop).
9808 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009809 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009810
9811 // This recurrence is variant w.r.t. L if L contains AR's loop.
9812 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009813 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009814
9815 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9816 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009817 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009818
9819 // This recurrence is variant w.r.t. L if any of its operands
9820 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009821 for (auto *Op : AR->operands())
9822 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009823 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009824
9825 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009826 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009827 }
9828 case scAddExpr:
9829 case scMulExpr:
9830 case scUMaxExpr:
9831 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009832 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009833 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9834 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009835 if (D == LoopVariant)
9836 return LoopVariant;
9837 if (D == LoopComputable)
9838 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009839 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009840 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009841 }
9842 case scUDivExpr: {
9843 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009844 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9845 if (LD == LoopVariant)
9846 return LoopVariant;
9847 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9848 if (RD == LoopVariant)
9849 return LoopVariant;
9850 return (LD == LoopInvariant && RD == LoopInvariant) ?
9851 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009852 }
9853 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009854 // All non-instruction values are loop invariant. All instructions are loop
9855 // invariant if they are not contained in the specified loop.
9856 // Instructions are never considered invariant in the function body
9857 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009858 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009859 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9860 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009861 case scCouldNotCompute:
9862 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009863 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009864 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009865}
9866
9867bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9868 return getLoopDisposition(S, L) == LoopInvariant;
9869}
9870
9871bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9872 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009873}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009874
Dan Gohman8ea83d82010-11-18 00:34:22 +00009875ScalarEvolution::BlockDisposition
9876ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009877 auto &Values = BlockDispositions[S];
9878 for (auto &V : Values) {
9879 if (V.getPointer() == BB)
9880 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009881 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009882 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009883 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009884 auto &Values2 = BlockDispositions[S];
9885 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9886 if (V.getPointer() == BB) {
9887 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009888 break;
9889 }
9890 }
9891 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009892}
9893
Dan Gohman8ea83d82010-11-18 00:34:22 +00009894ScalarEvolution::BlockDisposition
9895ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009896 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009897 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009898 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009899 case scTruncate:
9900 case scZeroExtend:
9901 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009902 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009903 case scAddRecExpr: {
9904 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009905 // to test for proper dominance too, because the instruction which
9906 // produces the addrec's value is a PHI, and a PHI effectively properly
9907 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009908 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009909 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009910 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009911
9912 // Fall through into SCEVNAryExpr handling.
9913 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009914 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009915 case scAddExpr:
9916 case scMulExpr:
9917 case scUMaxExpr:
9918 case scSMaxExpr: {
9919 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009920 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009921 for (const SCEV *NAryOp : NAry->operands()) {
9922 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009923 if (D == DoesNotDominateBlock)
9924 return DoesNotDominateBlock;
9925 if (D == DominatesBlock)
9926 Proper = false;
9927 }
9928 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009929 }
9930 case scUDivExpr: {
9931 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009932 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9933 BlockDisposition LD = getBlockDisposition(LHS, BB);
9934 if (LD == DoesNotDominateBlock)
9935 return DoesNotDominateBlock;
9936 BlockDisposition RD = getBlockDisposition(RHS, BB);
9937 if (RD == DoesNotDominateBlock)
9938 return DoesNotDominateBlock;
9939 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9940 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009941 }
9942 case scUnknown:
9943 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009944 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9945 if (I->getParent() == BB)
9946 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009947 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009948 return ProperlyDominatesBlock;
9949 return DoesNotDominateBlock;
9950 }
9951 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009952 case scCouldNotCompute:
9953 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009954 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009955 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009956}
9957
9958bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9959 return getBlockDisposition(S, BB) >= DominatesBlock;
9960}
9961
9962bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9963 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009964}
Dan Gohman534749b2010-11-17 22:27:42 +00009965
9966bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009967 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +00009968}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009969
9970void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9971 ValuesAtScopes.erase(S);
9972 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009973 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009974 UnsignedRanges.erase(S);
9975 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009976 ExprValueMap.erase(S);
9977 HasRecMap.erase(S);
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00009978 MinTrailingZerosCache.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009979
Silviu Baranga6f444df2016-04-08 14:29:09 +00009980 auto RemoveSCEVFromBackedgeMap =
9981 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9982 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9983 BackedgeTakenInfo &BEInfo = I->second;
9984 if (BEInfo.hasOperand(S, this)) {
9985 BEInfo.clear();
9986 Map.erase(I++);
9987 } else
9988 ++I;
9989 }
9990 };
9991
9992 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9993 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009994}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009995
9996typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009997
Alp Tokercb402912014-01-24 17:20:08 +00009998/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009999static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10000 size_t Pos = 0;
10001 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10002 Str.replace(Pos, From.size(), To.data(), To.size());
10003 Pos += To.size();
10004 }
10005}
10006
Benjamin Kramer214935e2012-10-26 17:31:32 +000010007/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10008static void
10009getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010010 std::string &S = Map[L];
10011 if (S.empty()) {
10012 raw_string_ostream OS(S);
10013 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010014
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010015 // false and 0 are semantically equivalent. This can happen in dead loops.
10016 replaceSubString(OS.str(), "false", "0");
10017 // Remove wrap flags, their use in SCEV is highly fragile.
10018 // FIXME: Remove this when SCEV gets smarter about them.
10019 replaceSubString(OS.str(), "<nw>", "");
10020 replaceSubString(OS.str(), "<nsw>", "");
10021 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010022 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010023
JF Bastien61ad8b32015-12-23 18:18:53 +000010024 for (auto *R : reverse(*L))
10025 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010026}
10027
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010028void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010029 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10030
10031 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10032 // FIXME: It would be much better to store actual values instead of strings,
10033 // but SCEV pointers will change if we drop the caches.
10034 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010035 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010036 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10037
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010038 // Gather stringified backedge taken counts for all loops using a fresh
10039 // ScalarEvolution object.
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010040 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010041 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10042 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010043
10044 // Now compare whether they're the same with and without caches. This allows
10045 // verifying that no pass changed the cache.
10046 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10047 "New loops suddenly appeared!");
10048
10049 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10050 OldE = BackedgeDumpsOld.end(),
10051 NewI = BackedgeDumpsNew.begin();
10052 OldI != OldE; ++OldI, ++NewI) {
10053 assert(OldI->first == NewI->first && "Loop order changed!");
10054
10055 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10056 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010057 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010058 // means that a pass is buggy or SCEV has to learn a new pattern but is
10059 // usually not harmful.
10060 if (OldI->second != NewI->second &&
10061 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010062 NewI->second.find("undef") == std::string::npos &&
10063 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010064 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010065 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010066 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010067 << "' changed from '" << OldI->second
10068 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010069 std::abort();
10070 }
10071 }
10072
10073 // TODO: Verify more things.
10074}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010075
Chandler Carruth082c1832017-01-09 07:44:34 +000010076bool ScalarEvolution::invalidate(
10077 Function &F, const PreservedAnalyses &PA,
10078 FunctionAnalysisManager::Invalidator &Inv) {
10079 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10080 // of its dependencies is invalidated.
10081 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10082 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10083 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10084 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10085 Inv.invalidate<LoopAnalysis>(F, PA);
10086}
10087
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010088AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010089
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010090ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010091 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010092 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010093 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010094 AM.getResult<DominatorTreeAnalysis>(F),
10095 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010096}
10097
10098PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010099ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010100 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010101 return PreservedAnalyses::all();
10102}
10103
10104INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10105 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010106INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010107INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10108INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10109INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10110INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10111 "Scalar Evolution Analysis", false, true)
10112char ScalarEvolutionWrapperPass::ID = 0;
10113
10114ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10115 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10116}
10117
10118bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10119 SE.reset(new ScalarEvolution(
10120 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010121 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010122 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10123 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10124 return false;
10125}
10126
10127void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10128
10129void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10130 SE->print(OS);
10131}
10132
10133void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10134 if (!VerifySCEV)
10135 return;
10136
10137 SE->verify();
10138}
10139
10140void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10141 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010142 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010143 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10144 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10145 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10146}
Silviu Barangae3c05342015-11-02 14:41:02 +000010147
10148const SCEVPredicate *
10149ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10150 const SCEVConstant *RHS) {
10151 FoldingSetNodeID ID;
10152 // Unique this node based on the arguments
10153 ID.AddInteger(SCEVPredicate::P_Equal);
10154 ID.AddPointer(LHS);
10155 ID.AddPointer(RHS);
10156 void *IP = nullptr;
10157 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10158 return S;
10159 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10160 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10161 UniquePreds.InsertNode(Eq, IP);
10162 return Eq;
10163}
10164
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010165const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10166 const SCEVAddRecExpr *AR,
10167 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10168 FoldingSetNodeID ID;
10169 // Unique this node based on the arguments
10170 ID.AddInteger(SCEVPredicate::P_Wrap);
10171 ID.AddPointer(AR);
10172 ID.AddInteger(AddedFlags);
10173 void *IP = nullptr;
10174 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10175 return S;
10176 auto *OF = new (SCEVAllocator)
10177 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10178 UniquePreds.InsertNode(OF, IP);
10179 return OF;
10180}
10181
Benjamin Kramer83709b12015-11-16 09:01:28 +000010182namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010183
Silviu Barangae3c05342015-11-02 14:41:02 +000010184class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10185public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010186 /// Rewrites \p S in the context of a loop L and the SCEV predication
10187 /// infrastructure.
10188 ///
10189 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10190 /// equivalences present in \p Pred.
10191 ///
10192 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10193 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010194 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010195 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10196 SCEVUnionPredicate *Pred) {
10197 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010198 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010199 }
10200
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010201 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010202 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10203 SCEVUnionPredicate *Pred)
10204 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010205
10206 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010207 if (Pred) {
10208 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10209 for (auto *Pred : ExprPreds)
10210 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10211 if (IPred->getLHS() == Expr)
10212 return IPred->getRHS();
10213 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010214
10215 return Expr;
10216 }
10217
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010218 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10219 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010220 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010221 if (AR && AR->getLoop() == L && AR->isAffine()) {
10222 // This couldn't be folded because the operand didn't have the nuw
10223 // flag. Add the nusw flag as an assumption that we could make.
10224 const SCEV *Step = AR->getStepRecurrence(SE);
10225 Type *Ty = Expr->getType();
10226 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10227 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10228 SE.getSignExtendExpr(Step, Ty), L,
10229 AR->getNoWrapFlags());
10230 }
10231 return SE.getZeroExtendExpr(Operand, Expr->getType());
10232 }
10233
10234 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10235 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010236 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010237 if (AR && AR->getLoop() == L && AR->isAffine()) {
10238 // This couldn't be folded because the operand didn't have the nsw
10239 // flag. Add the nssw flag as an assumption that we could make.
10240 const SCEV *Step = AR->getStepRecurrence(SE);
10241 Type *Ty = Expr->getType();
10242 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10243 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10244 SE.getSignExtendExpr(Step, Ty), L,
10245 AR->getNoWrapFlags());
10246 }
10247 return SE.getSignExtendExpr(Operand, Expr->getType());
10248 }
10249
Silviu Barangae3c05342015-11-02 14:41:02 +000010250private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010251 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10252 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10253 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010254 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010255 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010256 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010257 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010258 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010259 return true;
10260 }
10261
Sanjoy Dasf0022122016-09-28 17:14:58 +000010262 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10263 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010264 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010265};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010266} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010267
Sanjoy Das807d33d2016-02-20 01:44:10 +000010268const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010269 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010270 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010271}
10272
Sanjoy Dasf0022122016-09-28 17:14:58 +000010273const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10274 const SCEV *S, const Loop *L,
10275 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10276
10277 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10278 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010279 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10280
10281 if (!AddRec)
10282 return nullptr;
10283
10284 // Since the transformation was successful, we can now transfer the SCEV
10285 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010286 for (auto *P : TransformPreds)
10287 Preds.insert(P);
10288
Silviu Barangad68ed852016-03-23 15:29:30 +000010289 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010290}
10291
10292/// SCEV predicates
10293SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10294 SCEVPredicateKind Kind)
10295 : FastID(ID), Kind(Kind) {}
10296
10297SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10298 const SCEVUnknown *LHS,
10299 const SCEVConstant *RHS)
10300 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10301
10302bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010303 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010304
10305 if (!Op)
10306 return false;
10307
10308 return Op->LHS == LHS && Op->RHS == RHS;
10309}
10310
10311bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10312
10313const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10314
10315void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10316 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10317}
10318
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010319SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10320 const SCEVAddRecExpr *AR,
10321 IncrementWrapFlags Flags)
10322 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10323
10324const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10325
10326bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10327 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10328
10329 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10330}
10331
10332bool SCEVWrapPredicate::isAlwaysTrue() const {
10333 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10334 IncrementWrapFlags IFlags = Flags;
10335
10336 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10337 IFlags = clearFlags(IFlags, IncrementNSSW);
10338
10339 return IFlags == IncrementAnyWrap;
10340}
10341
10342void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10343 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10344 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10345 OS << "<nusw>";
10346 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10347 OS << "<nssw>";
10348 OS << "\n";
10349}
10350
10351SCEVWrapPredicate::IncrementWrapFlags
10352SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10353 ScalarEvolution &SE) {
10354 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10355 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10356
10357 // We can safely transfer the NSW flag as NSSW.
10358 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10359 ImpliedFlags = IncrementNSSW;
10360
10361 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10362 // If the increment is positive, the SCEV NUW flag will also imply the
10363 // WrapPredicate NUSW flag.
10364 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10365 if (Step->getValue()->getValue().isNonNegative())
10366 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10367 }
10368
10369 return ImpliedFlags;
10370}
10371
Silviu Barangae3c05342015-11-02 14:41:02 +000010372/// Union predicates don't get cached so create a dummy set ID for it.
10373SCEVUnionPredicate::SCEVUnionPredicate()
10374 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10375
10376bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010377 return all_of(Preds,
10378 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010379}
10380
10381ArrayRef<const SCEVPredicate *>
10382SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10383 auto I = SCEVToPreds.find(Expr);
10384 if (I == SCEVToPreds.end())
10385 return ArrayRef<const SCEVPredicate *>();
10386 return I->second;
10387}
10388
10389bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010390 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010391 return all_of(Set->Preds,
10392 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010393
10394 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10395 if (ScevPredsIt == SCEVToPreds.end())
10396 return false;
10397 auto &SCEVPreds = ScevPredsIt->second;
10398
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010399 return any_of(SCEVPreds,
10400 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010401}
10402
10403const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10404
10405void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10406 for (auto Pred : Preds)
10407 Pred->print(OS, Depth);
10408}
10409
10410void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010411 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010412 for (auto Pred : Set->Preds)
10413 add(Pred);
10414 return;
10415 }
10416
10417 if (implies(N))
10418 return;
10419
10420 const SCEV *Key = N->getExpr();
10421 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10422 " associated expression!");
10423
10424 SCEVToPreds[Key].push_back(N);
10425 Preds.push_back(N);
10426}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010427
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010428PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10429 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010430 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010431
10432const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10433 const SCEV *Expr = SE.getSCEV(V);
10434 RewriteEntry &Entry = RewriteMap[Expr];
10435
10436 // If we already have an entry and the version matches, return it.
10437 if (Entry.second && Generation == Entry.first)
10438 return Entry.second;
10439
10440 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010441 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010442 if (Entry.second)
10443 Expr = Entry.second;
10444
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010445 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010446 Entry = {Generation, NewSCEV};
10447
10448 return NewSCEV;
10449}
10450
Silviu Baranga6f444df2016-04-08 14:29:09 +000010451const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10452 if (!BackedgeCount) {
10453 SCEVUnionPredicate BackedgePred;
10454 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10455 addPredicate(BackedgePred);
10456 }
10457 return BackedgeCount;
10458}
10459
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010460void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10461 if (Preds.implies(&Pred))
10462 return;
10463 Preds.add(&Pred);
10464 updateGeneration();
10465}
10466
10467const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10468 return Preds;
10469}
10470
10471void PredicatedScalarEvolution::updateGeneration() {
10472 // If the generation number wrapped recompute everything.
10473 if (++Generation == 0) {
10474 for (auto &II : RewriteMap) {
10475 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010476 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010477 }
10478 }
10479}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010480
10481void PredicatedScalarEvolution::setNoOverflow(
10482 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10483 const SCEV *Expr = getSCEV(V);
10484 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10485
10486 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10487
10488 // Clear the statically implied flags.
10489 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10490 addPredicate(*SE.getWrapPredicate(AR, Flags));
10491
10492 auto II = FlagsMap.insert({V, Flags});
10493 if (!II.second)
10494 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10495}
10496
10497bool PredicatedScalarEvolution::hasNoOverflow(
10498 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10499 const SCEV *Expr = getSCEV(V);
10500 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10501
10502 Flags = SCEVWrapPredicate::clearFlags(
10503 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10504
10505 auto II = FlagsMap.find(V);
10506
10507 if (II != FlagsMap.end())
10508 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10509
10510 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10511}
10512
Silviu Barangad68ed852016-03-23 15:29:30 +000010513const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010514 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010515 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10516 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010517
10518 if (!New)
10519 return nullptr;
10520
Sanjoy Dasf0022122016-09-28 17:14:58 +000010521 for (auto *P : NewPreds)
10522 Preds.add(P);
10523
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010524 updateGeneration();
10525 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10526 return New;
10527}
10528
Silviu Baranga6f444df2016-04-08 14:29:09 +000010529PredicatedScalarEvolution::PredicatedScalarEvolution(
10530 const PredicatedScalarEvolution &Init)
10531 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10532 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010533 for (const auto &I : Init.FlagsMap)
10534 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010535}
Silviu Barangab77365b2016-04-14 16:08:45 +000010536
10537void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10538 // For each block.
10539 for (auto *BB : L.getBlocks())
10540 for (auto &I : *BB) {
10541 if (!SE.isSCEVable(I.getType()))
10542 continue;
10543
10544 auto *Expr = SE.getSCEV(&I);
10545 auto II = RewriteMap.find(Expr);
10546
10547 if (II == RewriteMap.end())
10548 continue;
10549
10550 // Don't print things that are not interesting.
10551 if (II->second.second == Expr)
10552 continue;
10553
10554 OS.indent(Depth) << "[PSE]" << I << ":\n";
10555 OS.indent(Depth + 2) << *Expr << "\n";
10556 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10557 }
10558}