blob: 659a1e5e1e750d845aceeed1dcefcbe4fd2a47bd [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
Max Kazantsev2e44d292017-03-31 12:05:30 +0000140static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
141 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
142 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
143 cl::init(2));
144
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000145static cl::opt<unsigned> MaxValueCompareDepth(
146 "scalar-evolution-max-value-compare-depth", cl::Hidden,
147 cl::desc("Maximum depth of recursive value complexity comparisons"),
148 cl::init(2));
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000149
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000150static cl::opt<unsigned>
151 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
152 cl::desc("Maximum depth of recursive AddExpr"),
153 cl::init(32));
154
Michael Liao468fb742017-01-13 18:28:30 +0000155static cl::opt<unsigned> MaxConstantEvolvingDepth(
156 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
157 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
158
Chris Lattnerd934c702004-04-02 20:23:17 +0000159//===----------------------------------------------------------------------===//
160// SCEV class definitions
161//===----------------------------------------------------------------------===//
162
163//===----------------------------------------------------------------------===//
164// Implementation of the SCEV class.
165//
Dan Gohman3423e722009-06-30 20:13:32 +0000166
Matthias Braun8c209aa2017-01-28 02:02:38 +0000167#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168LLVM_DUMP_METHOD void SCEV::dump() const {
Davide Italiano2071f4c2015-10-25 19:55:24 +0000169 print(dbgs());
170 dbgs() << '\n';
171}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000172#endif
Davide Italiano2071f4c2015-10-25 19:55:24 +0000173
Dan Gohman534749b2010-11-17 22:27:42 +0000174void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000175 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000176 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000177 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000178 return;
179 case scTruncate: {
180 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
181 const SCEV *Op = Trunc->getOperand();
182 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
183 << *Trunc->getType() << ")";
184 return;
185 }
186 case scZeroExtend: {
187 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
188 const SCEV *Op = ZExt->getOperand();
189 OS << "(zext " << *Op->getType() << " " << *Op << " to "
190 << *ZExt->getType() << ")";
191 return;
192 }
193 case scSignExtend: {
194 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
195 const SCEV *Op = SExt->getOperand();
196 OS << "(sext " << *Op->getType() << " " << *Op << " to "
197 << *SExt->getType() << ")";
198 return;
199 }
200 case scAddRecExpr: {
201 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
202 OS << "{" << *AR->getOperand(0);
203 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
204 OS << ",+," << *AR->getOperand(i);
205 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000206 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000207 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000208 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000209 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000210 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000211 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
212 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000213 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000214 OS << ">";
215 return;
216 }
217 case scAddExpr:
218 case scMulExpr:
219 case scUMaxExpr:
220 case scSMaxExpr: {
221 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000222 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000223 switch (NAry->getSCEVType()) {
224 case scAddExpr: OpStr = " + "; break;
225 case scMulExpr: OpStr = " * "; break;
226 case scUMaxExpr: OpStr = " umax "; break;
227 case scSMaxExpr: OpStr = " smax "; break;
228 }
229 OS << "(";
230 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
231 I != E; ++I) {
232 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000233 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000234 OS << OpStr;
235 }
236 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000237 switch (NAry->getSCEVType()) {
238 case scAddExpr:
239 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000240 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000241 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000242 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000243 OS << "<nsw>";
244 }
Dan Gohman534749b2010-11-17 22:27:42 +0000245 return;
246 }
247 case scUDivExpr: {
248 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
249 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
250 return;
251 }
252 case scUnknown: {
253 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000254 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000255 if (U->isSizeOf(AllocTy)) {
256 OS << "sizeof(" << *AllocTy << ")";
257 return;
258 }
259 if (U->isAlignOf(AllocTy)) {
260 OS << "alignof(" << *AllocTy << ")";
261 return;
262 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000263
Chris Lattner229907c2011-07-18 04:54:35 +0000264 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000265 Constant *FieldNo;
266 if (U->isOffsetOf(CTy, FieldNo)) {
267 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000268 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000269 OS << ")";
270 return;
271 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000272
Dan Gohman534749b2010-11-17 22:27:42 +0000273 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000274 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000275 return;
276 }
277 case scCouldNotCompute:
278 OS << "***COULDNOTCOMPUTE***";
279 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000280 }
281 llvm_unreachable("Unknown SCEV kind!");
282}
283
Chris Lattner229907c2011-07-18 04:54:35 +0000284Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000285 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000286 case scConstant:
287 return cast<SCEVConstant>(this)->getType();
288 case scTruncate:
289 case scZeroExtend:
290 case scSignExtend:
291 return cast<SCEVCastExpr>(this)->getType();
292 case scAddRecExpr:
293 case scMulExpr:
294 case scUMaxExpr:
295 case scSMaxExpr:
296 return cast<SCEVNAryExpr>(this)->getType();
297 case scAddExpr:
298 return cast<SCEVAddExpr>(this)->getType();
299 case scUDivExpr:
300 return cast<SCEVUDivExpr>(this)->getType();
301 case scUnknown:
302 return cast<SCEVUnknown>(this)->getType();
303 case scCouldNotCompute:
304 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000305 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000306 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000307}
308
Dan Gohmanbe928e32008-06-18 16:23:07 +0000309bool SCEV::isZero() const {
310 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
311 return SC->getValue()->isZero();
312 return false;
313}
314
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000315bool SCEV::isOne() const {
316 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
317 return SC->getValue()->isOne();
318 return false;
319}
Chris Lattnerd934c702004-04-02 20:23:17 +0000320
Dan Gohman18a96bb2009-06-24 00:30:26 +0000321bool SCEV::isAllOnesValue() const {
322 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
323 return SC->getValue()->isAllOnesValue();
324 return false;
325}
326
Andrew Trick881a7762012-01-07 00:27:31 +0000327bool SCEV::isNonConstantNegative() const {
328 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
329 if (!Mul) return false;
330
331 // If there is a constant factor, it will be first.
332 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
333 if (!SC) return false;
334
335 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000336 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000337}
338
Owen Anderson04052ec2009-06-22 21:57:23 +0000339SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000340 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000341
Chris Lattnerd934c702004-04-02 20:23:17 +0000342bool SCEVCouldNotCompute::classof(const SCEV *S) {
343 return S->getSCEVType() == scCouldNotCompute;
344}
345
Dan Gohmanaf752342009-07-07 17:06:11 +0000346const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000347 FoldingSetNodeID ID;
348 ID.AddInteger(scConstant);
349 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000350 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000351 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000352 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000353 UniqueSCEVs.InsertNode(S, IP);
354 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000355}
Chris Lattnerd934c702004-04-02 20:23:17 +0000356
Nick Lewycky31eaca52014-01-27 10:04:03 +0000357const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000358 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000359}
360
Dan Gohmanaf752342009-07-07 17:06:11 +0000361const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000362ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
363 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000364 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000365}
366
Dan Gohman24ceda82010-06-18 19:54:20 +0000367SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000368 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000369 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000370
Dan Gohman24ceda82010-06-18 19:54:20 +0000371SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000372 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000373 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000374 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
375 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000376 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000377}
Chris Lattnerd934c702004-04-02 20:23:17 +0000378
Dan Gohman24ceda82010-06-18 19:54:20 +0000379SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000380 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000381 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000382 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
383 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000384 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000385}
386
Dan Gohman24ceda82010-06-18 19:54:20 +0000387SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000388 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000389 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000390 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
391 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000392 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000393}
394
Dan Gohman7cac9572010-08-02 23:49:30 +0000395void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000396 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000397 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000398
399 // Remove this SCEVUnknown from the uniquing map.
400 SE->UniqueSCEVs.RemoveNode(this);
401
402 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000403 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000404}
405
406void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000407 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000408 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000409
410 // Remove this SCEVUnknown from the uniquing map.
411 SE->UniqueSCEVs.RemoveNode(this);
412
413 // Update this SCEVUnknown to point to the new value. This is needed
414 // because there may still be outstanding SCEVs which still point to
415 // this SCEVUnknown.
416 setValPtr(New);
417}
418
Chris Lattner229907c2011-07-18 04:54:35 +0000419bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000420 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000421 if (VCE->getOpcode() == Instruction::PtrToInt)
422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000423 if (CE->getOpcode() == Instruction::GetElementPtr &&
424 CE->getOperand(0)->isNullValue() &&
425 CE->getNumOperands() == 2)
426 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
427 if (CI->isOne()) {
428 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
429 ->getElementType();
430 return true;
431 }
Dan Gohmancf913832010-01-28 02:15:55 +0000432
433 return false;
434}
435
Chris Lattner229907c2011-07-18 04:54:35 +0000436bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000442 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000443 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000444 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000445 if (!STy->isPacked() &&
446 CE->getNumOperands() == 3 &&
447 CE->getOperand(1)->isNullValue()) {
448 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
449 if (CI->isOne() &&
450 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000451 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000452 AllocTy = STy->getElementType(1);
453 return true;
454 }
455 }
456 }
Dan Gohmancf913832010-01-28 02:15:55 +0000457
458 return false;
459}
460
Chris Lattner229907c2011-07-18 04:54:35 +0000461bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000462 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000463 if (VCE->getOpcode() == Instruction::PtrToInt)
464 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
465 if (CE->getOpcode() == Instruction::GetElementPtr &&
466 CE->getNumOperands() == 3 &&
467 CE->getOperand(0)->isNullValue() &&
468 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000469 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000470 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
471 // Ignore vector types here so that ScalarEvolutionExpander doesn't
472 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000473 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000474 CTy = Ty;
475 FieldNo = CE->getOperand(2);
476 return true;
477 }
478 }
479
480 return false;
481}
482
Chris Lattnereb3e8402004-06-20 06:23:15 +0000483//===----------------------------------------------------------------------===//
484// SCEV Utilities
485//===----------------------------------------------------------------------===//
486
Sanjoy Das17078692016-10-31 03:32:43 +0000487/// Compare the two values \p LV and \p RV in terms of their "complexity" where
488/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
489/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
490/// have been previously deemed to be "equally complex" by this routine. It is
491/// intended to avoid exponential time complexity in cases like:
492///
493/// %a = f(%x, %y)
494/// %b = f(%a, %a)
495/// %c = f(%b, %b)
496///
497/// %d = f(%x, %y)
498/// %e = f(%d, %d)
499/// %f = f(%e, %e)
500///
501/// CompareValueComplexity(%f, %c)
502///
503/// Since we do not continue running this routine on expression trees once we
504/// have seen unequal values, there is no need to track them in the cache.
505static int
506CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
507 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000508 unsigned Depth) {
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000509 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000510 return 0;
511
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000512 // Order pointer values after integer values. This helps SCEVExpander form
513 // GEPs.
514 bool LIsPointer = LV->getType()->isPointerTy(),
515 RIsPointer = RV->getType()->isPointerTy();
516 if (LIsPointer != RIsPointer)
517 return (int)LIsPointer - (int)RIsPointer;
518
519 // Compare getValueID values.
520 unsigned LID = LV->getValueID(), RID = RV->getValueID();
521 if (LID != RID)
522 return (int)LID - (int)RID;
523
524 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000525 if (const auto *LA = dyn_cast<Argument>(LV)) {
526 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000527 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
528 return (int)LArgNo - (int)RArgNo;
529 }
530
Sanjoy Das299e6722016-10-30 23:52:56 +0000531 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
532 const auto *RGV = cast<GlobalValue>(RV);
533
534 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
535 auto LT = GV->getLinkage();
536 return !(GlobalValue::isPrivateLinkage(LT) ||
537 GlobalValue::isInternalLinkage(LT));
538 };
539
540 // Use the names to distinguish the two values, but only if the
541 // names are semantically important.
542 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
543 return LGV->getName().compare(RGV->getName());
544 }
545
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000546 // For instructions, compare their loop depth, and their operand count. This
547 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000548 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
549 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000550
551 // Compare loop depths.
552 const BasicBlock *LParent = LInst->getParent(),
553 *RParent = RInst->getParent();
554 if (LParent != RParent) {
555 unsigned LDepth = LI->getLoopDepth(LParent),
556 RDepth = LI->getLoopDepth(RParent);
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Compare the number of operands.
562 unsigned LNumOps = LInst->getNumOperands(),
563 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000564 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000565 return (int)LNumOps - (int)RNumOps;
566
Sanjoy Das17078692016-10-31 03:32:43 +0000567 for (unsigned Idx : seq(0u, LNumOps)) {
568 int Result =
569 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000570 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000571 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000572 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000573 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000574 }
575
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000576 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000577 return 0;
578}
579
Sanjoy Das237c8452016-09-27 18:01:48 +0000580// Return negative, zero, or positive, if LHS is less than, equal to, or greater
581// than RHS, respectively. A three-way result allows recursive comparisons to be
582// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000583static int CompareSCEVComplexity(
584 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
585 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
586 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000587 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
588 if (LHS == RHS)
589 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000590
Sanjoy Das237c8452016-09-27 18:01:48 +0000591 // Primarily, sort the SCEVs by their getSCEVType().
592 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
593 if (LType != RType)
594 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000595
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000596 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000597 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000598 // Aside from the getSCEVType() ordering, the particular ordering
599 // isn't very important except that it's beneficial to be consistent,
600 // so that (a + b) and (b + a) don't end up as different expressions.
601 switch (static_cast<SCEVTypes>(LType)) {
602 case scUnknown: {
603 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
604 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000605
Sanjoy Das17078692016-10-31 03:32:43 +0000606 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000607 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
608 Depth + 1);
609 if (X == 0)
610 EqCacheSCEV.insert({LHS, RHS});
611 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000612 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000613
Sanjoy Das237c8452016-09-27 18:01:48 +0000614 case scConstant: {
615 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
616 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
617
618 // Compare constant values.
619 const APInt &LA = LC->getAPInt();
620 const APInt &RA = RC->getAPInt();
621 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
622 if (LBitWidth != RBitWidth)
623 return (int)LBitWidth - (int)RBitWidth;
624 return LA.ult(RA) ? -1 : 1;
625 }
626
627 case scAddRecExpr: {
628 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
629 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
630
631 // Compare addrec loop depths.
632 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
633 if (LLoop != RLoop) {
634 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
635 if (LDepth != RDepth)
636 return (int)LDepth - (int)RDepth;
637 }
638
639 // Addrec complexity grows with operand count.
640 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
641 if (LNumOps != RNumOps)
642 return (int)LNumOps - (int)RNumOps;
643
644 // Lexicographically compare.
645 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000646 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
647 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000648 if (X != 0)
649 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000650 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000651 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000652 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000653 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000654
655 case scAddExpr:
656 case scMulExpr:
657 case scSMaxExpr:
658 case scUMaxExpr: {
659 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
660 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
661
662 // Lexicographically compare n-ary expressions.
663 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
664 if (LNumOps != RNumOps)
665 return (int)LNumOps - (int)RNumOps;
666
667 for (unsigned i = 0; i != LNumOps; ++i) {
668 if (i >= RNumOps)
669 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000670 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
671 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000672 if (X != 0)
673 return X;
674 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000675 EqCacheSCEV.insert({LHS, RHS});
676 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000677 }
678
679 case scUDivExpr: {
680 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
681 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
682
683 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000684 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
685 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000686 if (X != 0)
687 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000688 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
689 Depth + 1);
690 if (X == 0)
691 EqCacheSCEV.insert({LHS, RHS});
692 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000693 }
694
695 case scTruncate:
696 case scZeroExtend:
697 case scSignExtend: {
698 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
699 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
700
701 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000702 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
703 RC->getOperand(), Depth + 1);
704 if (X == 0)
705 EqCacheSCEV.insert({LHS, RHS});
706 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000707 }
708
709 case scCouldNotCompute:
710 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
711 }
712 llvm_unreachable("Unknown SCEV kind!");
713}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000714
Sanjoy Dasf8570812016-05-29 00:38:22 +0000715/// Given a list of SCEV objects, order them by their complexity, and group
716/// objects of the same complexity together by value. When this routine is
717/// finished, we know that any duplicates in the vector are consecutive and that
718/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000719///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000720/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000721/// results from this routine. In other words, we don't want the results of
722/// this to depend on where the addresses of various SCEV objects happened to
723/// land in memory.
724///
Dan Gohmanaf752342009-07-07 17:06:11 +0000725static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000726 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000727 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000728
729 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000730 if (Ops.size() == 2) {
731 // This is the common case, which also happens to be trivially simple.
732 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000733 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000734 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000735 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000736 return;
737 }
738
Dan Gohman24ceda82010-06-18 19:54:20 +0000739 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000740 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000741 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
742 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000743 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000744
745 // Now that we are sorted by complexity, group elements of the same
746 // complexity. Note that this is, at worst, N^2, but the vector is likely to
747 // be extremely short in practice. Note that we take this approach because we
748 // do not want to depend on the addresses of the objects we are grouping.
749 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
750 const SCEV *S = Ops[i];
751 unsigned Complexity = S->getSCEVType();
752
753 // If there are any objects of the same complexity and same value as this
754 // one, group them.
755 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
756 if (Ops[j] == S) { // Found a duplicate.
757 // Move it to immediately after i'th element.
758 std::swap(Ops[i+1], Ops[j]);
759 ++i; // no need to rescan it.
760 if (i == e-2) return; // Done!
761 }
762 }
763 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000764}
765
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000766// Returns the size of the SCEV S.
767static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000768 struct FindSCEVSize {
769 int Size;
770 FindSCEVSize() : Size(0) {}
771
772 bool follow(const SCEV *S) {
773 ++Size;
774 // Keep looking at all operands of S.
775 return true;
776 }
777 bool isDone() const {
778 return false;
779 }
780 };
781
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000782 FindSCEVSize F;
783 SCEVTraversal<FindSCEVSize> ST(F);
784 ST.visitAll(S);
785 return F.Size;
786}
787
788namespace {
789
David Majnemer4e879362014-12-14 09:12:33 +0000790struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000791public:
792 // Computes the Quotient and Remainder of the division of Numerator by
793 // Denominator.
794 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
795 const SCEV *Denominator, const SCEV **Quotient,
796 const SCEV **Remainder) {
797 assert(Numerator && Denominator && "Uninitialized SCEV");
798
David Majnemer4e879362014-12-14 09:12:33 +0000799 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000800
801 // Check for the trivial case here to avoid having to check for it in the
802 // rest of the code.
803 if (Numerator == Denominator) {
804 *Quotient = D.One;
805 *Remainder = D.Zero;
806 return;
807 }
808
809 if (Numerator->isZero()) {
810 *Quotient = D.Zero;
811 *Remainder = D.Zero;
812 return;
813 }
814
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000815 // A simple case when N/1. The quotient is N.
816 if (Denominator->isOne()) {
817 *Quotient = Numerator;
818 *Remainder = D.Zero;
819 return;
820 }
821
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000822 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000823 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000824 const SCEV *Q, *R;
825 *Quotient = Numerator;
826 for (const SCEV *Op : T->operands()) {
827 divide(SE, *Quotient, Op, &Q, &R);
828 *Quotient = Q;
829
830 // Bail out when the Numerator is not divisible by one of the terms of
831 // the Denominator.
832 if (!R->isZero()) {
833 *Quotient = D.Zero;
834 *Remainder = Numerator;
835 return;
836 }
837 }
838 *Remainder = D.Zero;
839 return;
840 }
841
842 D.visit(Numerator);
843 *Quotient = D.Quotient;
844 *Remainder = D.Remainder;
845 }
846
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000847 // Except in the trivial case described above, we do not know how to divide
848 // Expr by Denominator for the following functions with empty implementation.
849 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
850 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
851 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
852 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
853 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
854 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
855 void visitUnknown(const SCEVUnknown *Numerator) {}
856 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
857
David Majnemer4e879362014-12-14 09:12:33 +0000858 void visitConstant(const SCEVConstant *Numerator) {
859 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000860 APInt NumeratorVal = Numerator->getAPInt();
861 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000862 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
863 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
864
865 if (NumeratorBW > DenominatorBW)
866 DenominatorVal = DenominatorVal.sext(NumeratorBW);
867 else if (NumeratorBW < DenominatorBW)
868 NumeratorVal = NumeratorVal.sext(DenominatorBW);
869
870 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
871 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
872 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
873 Quotient = SE.getConstant(QuotientVal);
874 Remainder = SE.getConstant(RemainderVal);
875 return;
876 }
877 }
878
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000879 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
880 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000881 if (!Numerator->isAffine())
882 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000883 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
884 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000885 // Bail out if the types do not match.
886 Type *Ty = Denominator->getType();
887 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000888 Ty != StepQ->getType() || Ty != StepR->getType())
889 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000890 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
891 Numerator->getNoWrapFlags());
892 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
893 Numerator->getNoWrapFlags());
894 }
895
896 void visitAddExpr(const SCEVAddExpr *Numerator) {
897 SmallVector<const SCEV *, 2> Qs, Rs;
898 Type *Ty = Denominator->getType();
899
900 for (const SCEV *Op : Numerator->operands()) {
901 const SCEV *Q, *R;
902 divide(SE, Op, Denominator, &Q, &R);
903
904 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000905 if (Ty != Q->getType() || Ty != R->getType())
906 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000907
908 Qs.push_back(Q);
909 Rs.push_back(R);
910 }
911
912 if (Qs.size() == 1) {
913 Quotient = Qs[0];
914 Remainder = Rs[0];
915 return;
916 }
917
918 Quotient = SE.getAddExpr(Qs);
919 Remainder = SE.getAddExpr(Rs);
920 }
921
922 void visitMulExpr(const SCEVMulExpr *Numerator) {
923 SmallVector<const SCEV *, 2> Qs;
924 Type *Ty = Denominator->getType();
925
926 bool FoundDenominatorTerm = false;
927 for (const SCEV *Op : Numerator->operands()) {
928 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000929 if (Ty != Op->getType())
930 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000931
932 if (FoundDenominatorTerm) {
933 Qs.push_back(Op);
934 continue;
935 }
936
937 // Check whether Denominator divides one of the product operands.
938 const SCEV *Q, *R;
939 divide(SE, Op, Denominator, &Q, &R);
940 if (!R->isZero()) {
941 Qs.push_back(Op);
942 continue;
943 }
944
945 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000946 if (Ty != Q->getType())
947 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000948
949 FoundDenominatorTerm = true;
950 Qs.push_back(Q);
951 }
952
953 if (FoundDenominatorTerm) {
954 Remainder = Zero;
955 if (Qs.size() == 1)
956 Quotient = Qs[0];
957 else
958 Quotient = SE.getMulExpr(Qs);
959 return;
960 }
961
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000962 if (!isa<SCEVUnknown>(Denominator))
963 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000964
965 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
966 ValueToValueMap RewriteMap;
967 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
968 cast<SCEVConstant>(Zero)->getValue();
969 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
970
971 if (Remainder->isZero()) {
972 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
973 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
974 cast<SCEVConstant>(One)->getValue();
975 Quotient =
976 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
977 return;
978 }
979
980 // Quotient is (Numerator - Remainder) divided by Denominator.
981 const SCEV *Q, *R;
982 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000983 // This SCEV does not seem to simplify: fail the division here.
984 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
985 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000986 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000987 if (R != Zero)
988 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000989 Quotient = Q;
990 }
991
992private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000993 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
994 const SCEV *Denominator)
995 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000996 Zero = SE.getZero(Denominator->getType());
997 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000998
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000999 // We generally do not know how to divide Expr by Denominator. We
1000 // initialize the division to a "cannot divide" state to simplify the rest
1001 // of the code.
1002 cannotDivide(Numerator);
1003 }
1004
1005 // Convenience function for giving up on the division. We set the quotient to
1006 // be equal to zero and the remainder to be equal to the numerator.
1007 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +00001008 Quotient = Zero;
1009 Remainder = Numerator;
1010 }
1011
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001012 ScalarEvolution &SE;
1013 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +00001014};
1015
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001016}
Mark Heffernan2beab5f2014-10-10 17:39:11 +00001017
Chris Lattnerd934c702004-04-02 20:23:17 +00001018//===----------------------------------------------------------------------===//
1019// Simple SCEV method implementations
1020//===----------------------------------------------------------------------===//
1021
Sanjoy Dasf8570812016-05-29 00:38:22 +00001022/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +00001023static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +00001024 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001025 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001026 // Handle the simplest case efficiently.
1027 if (K == 1)
1028 return SE.getTruncateOrZeroExtend(It, ResultTy);
1029
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001030 // We are using the following formula for BC(It, K):
1031 //
1032 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1033 //
Eli Friedman61f67622008-08-04 23:49:06 +00001034 // Suppose, W is the bitwidth of the return value. We must be prepared for
1035 // overflow. Hence, we must assure that the result of our computation is
1036 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1037 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001038 //
Eli Friedman61f67622008-08-04 23:49:06 +00001039 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001040 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001041 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1042 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001043 //
Eli Friedman61f67622008-08-04 23:49:06 +00001044 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001045 //
Eli Friedman61f67622008-08-04 23:49:06 +00001046 // This formula is trivially equivalent to the previous formula. However,
1047 // this formula can be implemented much more efficiently. The trick is that
1048 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1049 // arithmetic. To do exact division in modular arithmetic, all we have
1050 // to do is multiply by the inverse. Therefore, this step can be done at
1051 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001052 //
Eli Friedman61f67622008-08-04 23:49:06 +00001053 // The next issue is how to safely do the division by 2^T. The way this
1054 // is done is by doing the multiplication step at a width of at least W + T
1055 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1056 // when we perform the division by 2^T (which is equivalent to a right shift
1057 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1058 // truncated out after the division by 2^T.
1059 //
1060 // In comparison to just directly using the first formula, this technique
1061 // is much more efficient; using the first formula requires W * K bits,
1062 // but this formula less than W + K bits. Also, the first formula requires
1063 // a division step, whereas this formula only requires multiplies and shifts.
1064 //
1065 // It doesn't matter whether the subtraction step is done in the calculation
1066 // width or the input iteration count's width; if the subtraction overflows,
1067 // the result must be zero anyway. We prefer here to do it in the width of
1068 // the induction variable because it helps a lot for certain cases; CodeGen
1069 // isn't smart enough to ignore the overflow, which leads to much less
1070 // efficient code if the width of the subtraction is wider than the native
1071 // register width.
1072 //
1073 // (It's possible to not widen at all by pulling out factors of 2 before
1074 // the multiplication; for example, K=2 can be calculated as
1075 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1076 // extra arithmetic, so it's not an obvious win, and it gets
1077 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001078
Eli Friedman61f67622008-08-04 23:49:06 +00001079 // Protection from insane SCEVs; this bound is conservative,
1080 // but it probably doesn't matter.
1081 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001082 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001083
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001084 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001085
Eli Friedman61f67622008-08-04 23:49:06 +00001086 // Calculate K! / 2^T and T; we divide out the factors of two before
1087 // multiplying for calculating K! / 2^T to avoid overflow.
1088 // Other overflow doesn't matter because we only care about the bottom
1089 // W bits of the result.
1090 APInt OddFactorial(W, 1);
1091 unsigned T = 1;
1092 for (unsigned i = 3; i <= K; ++i) {
1093 APInt Mult(W, i);
1094 unsigned TwoFactors = Mult.countTrailingZeros();
1095 T += TwoFactors;
1096 Mult = Mult.lshr(TwoFactors);
1097 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001098 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001099
Eli Friedman61f67622008-08-04 23:49:06 +00001100 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001101 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001102
Dan Gohman8b0a4192010-03-01 17:49:51 +00001103 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001104 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001105
1106 // Calculate the multiplicative inverse of K! / 2^T;
1107 // this multiplication factor will perform the exact division by
1108 // K! / 2^T.
1109 APInt Mod = APInt::getSignedMinValue(W+1);
1110 APInt MultiplyFactor = OddFactorial.zext(W+1);
1111 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1112 MultiplyFactor = MultiplyFactor.trunc(W);
1113
1114 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001115 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001116 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001117 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001118 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001119 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001120 Dividend = SE.getMulExpr(Dividend,
1121 SE.getTruncateOrZeroExtend(S, CalculationTy));
1122 }
1123
1124 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001125 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001126
1127 // Truncate the result, and divide by K! / 2^T.
1128
1129 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1130 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001131}
1132
Sanjoy Dasf8570812016-05-29 00:38:22 +00001133/// Return the value of this chain of recurrences at the specified iteration
1134/// number. We can evaluate this recurrence by multiplying each element in the
1135/// chain by the binomial coefficient corresponding to it. In other words, we
1136/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001137///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001138/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001139///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001140/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001141///
Dan Gohmanaf752342009-07-07 17:06:11 +00001142const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001143 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001144 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001145 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001146 // The computation is correct in the face of overflow provided that the
1147 // multiplication is performed _after_ the evaluation of the binomial
1148 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001149 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001150 if (isa<SCEVCouldNotCompute>(Coeff))
1151 return Coeff;
1152
1153 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001154 }
1155 return Result;
1156}
1157
Chris Lattnerd934c702004-04-02 20:23:17 +00001158//===----------------------------------------------------------------------===//
1159// SCEV Expression folder implementations
1160//===----------------------------------------------------------------------===//
1161
Dan Gohmanaf752342009-07-07 17:06:11 +00001162const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001163 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001164 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001165 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001166 assert(isSCEVable(Ty) &&
1167 "This is not a conversion to a SCEVable type!");
1168 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001169
Dan Gohman3a302cb2009-07-13 20:50:19 +00001170 FoldingSetNodeID ID;
1171 ID.AddInteger(scTruncate);
1172 ID.AddPointer(Op);
1173 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001174 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1176
Dan Gohman3423e722009-06-30 20:13:32 +00001177 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001178 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001179 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001180 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001181
Dan Gohman79af8542009-04-22 16:20:48 +00001182 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001183 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001184 return getTruncateExpr(ST->getOperand(), Ty);
1185
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001186 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001187 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001188 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1189
1190 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001191 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001192 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1193
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001194 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001195 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001196 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1197 SmallVector<const SCEV *, 4> Operands;
1198 bool hasTrunc = false;
1199 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1200 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001201 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1202 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001203 Operands.push_back(S);
1204 }
1205 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001206 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001207 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001208 }
1209
Nick Lewycky5c901f32011-01-19 18:56:00 +00001210 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001211 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001212 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1213 SmallVector<const SCEV *, 4> Operands;
1214 bool hasTrunc = false;
1215 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1216 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001217 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1218 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001219 Operands.push_back(S);
1220 }
1221 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001222 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001223 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001224 }
1225
Dan Gohman5a728c92009-06-18 16:24:47 +00001226 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001227 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001228 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001229 for (const SCEV *Op : AddRec->operands())
1230 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001231 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001232 }
1233
Dan Gohman89dd42a2010-06-25 18:47:08 +00001234 // The cast wasn't folded; create an explicit cast node. We can reuse
1235 // the existing insert position since if we get here, we won't have
1236 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001237 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1238 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001239 UniqueSCEVs.InsertNode(S, IP);
1240 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001241}
1242
Sanjoy Das4153f472015-02-18 01:47:07 +00001243// Get the limit of a recurrence such that incrementing by Step cannot cause
1244// signed overflow as long as the value of the recurrence within the
1245// loop does not exceed this limit before incrementing.
1246static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1247 ICmpInst::Predicate *Pred,
1248 ScalarEvolution *SE) {
1249 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1250 if (SE->isKnownPositive(Step)) {
1251 *Pred = ICmpInst::ICMP_SLT;
1252 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1253 SE->getSignedRange(Step).getSignedMax());
1254 }
1255 if (SE->isKnownNegative(Step)) {
1256 *Pred = ICmpInst::ICMP_SGT;
1257 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1258 SE->getSignedRange(Step).getSignedMin());
1259 }
1260 return nullptr;
1261}
1262
1263// Get the limit of a recurrence such that incrementing by Step cannot cause
1264// unsigned overflow as long as the value of the recurrence within the loop does
1265// not exceed this limit before incrementing.
1266static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1267 ICmpInst::Predicate *Pred,
1268 ScalarEvolution *SE) {
1269 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1270 *Pred = ICmpInst::ICMP_ULT;
1271
1272 return SE->getConstant(APInt::getMinValue(BitWidth) -
1273 SE->getUnsignedRange(Step).getUnsignedMax());
1274}
1275
1276namespace {
1277
1278struct ExtendOpTraitsBase {
1279 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1280};
1281
1282// Used to make code generic over signed and unsigned overflow.
1283template <typename ExtendOp> struct ExtendOpTraits {
1284 // Members present:
1285 //
1286 // static const SCEV::NoWrapFlags WrapType;
1287 //
1288 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1289 //
1290 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1291 // ICmpInst::Predicate *Pred,
1292 // ScalarEvolution *SE);
1293};
1294
1295template <>
1296struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1297 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1298
1299 static const GetExtendExprTy GetExtendExpr;
1300
1301 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1302 ICmpInst::Predicate *Pred,
1303 ScalarEvolution *SE) {
1304 return getSignedOverflowLimitForStep(Step, Pred, SE);
1305 }
1306};
1307
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001308const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001309 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1310
1311template <>
1312struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1313 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1314
1315 static const GetExtendExprTy GetExtendExpr;
1316
1317 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1318 ICmpInst::Predicate *Pred,
1319 ScalarEvolution *SE) {
1320 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1321 }
1322};
1323
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001324const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001325 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001326}
Sanjoy Das4153f472015-02-18 01:47:07 +00001327
1328// The recurrence AR has been shown to have no signed/unsigned wrap or something
1329// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1330// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1331// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1332// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1333// expression "Step + sext/zext(PreIncAR)" is congruent with
1334// "sext/zext(PostIncAR)"
1335template <typename ExtendOpTy>
1336static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1337 ScalarEvolution *SE) {
1338 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1339 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1340
1341 const Loop *L = AR->getLoop();
1342 const SCEV *Start = AR->getStart();
1343 const SCEV *Step = AR->getStepRecurrence(*SE);
1344
1345 // Check for a simple looking step prior to loop entry.
1346 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1347 if (!SA)
1348 return nullptr;
1349
1350 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1351 // subtraction is expensive. For this purpose, perform a quick and dirty
1352 // difference, by checking for Step in the operand list.
1353 SmallVector<const SCEV *, 4> DiffOps;
1354 for (const SCEV *Op : SA->operands())
1355 if (Op != Step)
1356 DiffOps.push_back(Op);
1357
1358 if (DiffOps.size() == SA->getNumOperands())
1359 return nullptr;
1360
1361 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1362 // `Step`:
1363
1364 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001365 auto PreStartFlags =
1366 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1367 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001368 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1369 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1370
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001371 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1372 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001373 //
1374
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001375 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1376 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1377 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001378 return PreStart;
1379
1380 // 2. Direct overflow check on the step operation's expression.
1381 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1382 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1383 const SCEV *OperandExtendedStart =
1384 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1385 (SE->*GetExtendExpr)(Step, WideTy));
1386 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1387 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1388 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1389 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1390 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1391 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1392 }
1393 return PreStart;
1394 }
1395
1396 // 3. Loop precondition.
1397 ICmpInst::Predicate Pred;
1398 const SCEV *OverflowLimit =
1399 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1400
1401 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001402 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001403 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001404
Sanjoy Das4153f472015-02-18 01:47:07 +00001405 return nullptr;
1406}
1407
1408// Get the normalized zero or sign extended expression for this AddRec's Start.
1409template <typename ExtendOpTy>
1410static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1411 ScalarEvolution *SE) {
1412 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1413
1414 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1415 if (!PreStart)
1416 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1417
1418 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1419 (SE->*GetExtendExpr)(PreStart, Ty));
1420}
1421
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001422// Try to prove away overflow by looking at "nearby" add recurrences. A
1423// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1424// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1425//
1426// Formally:
1427//
1428// {S,+,X} == {S-T,+,X} + T
1429// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1430//
1431// If ({S-T,+,X} + T) does not overflow ... (1)
1432//
1433// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1434//
1435// If {S-T,+,X} does not overflow ... (2)
1436//
1437// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1438// == {Ext(S-T)+Ext(T),+,Ext(X)}
1439//
1440// If (S-T)+T does not overflow ... (3)
1441//
1442// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1443// == {Ext(S),+,Ext(X)} == LHS
1444//
1445// Thus, if (1), (2) and (3) are true for some T, then
1446// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1447//
1448// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1449// does not overflow" restricted to the 0th iteration. Therefore we only need
1450// to check for (1) and (2).
1451//
1452// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1453// is `Delta` (defined below).
1454//
1455template <typename ExtendOpTy>
1456bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1457 const SCEV *Step,
1458 const Loop *L) {
1459 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1460
1461 // We restrict `Start` to a constant to prevent SCEV from spending too much
1462 // time here. It is correct (but more expensive) to continue with a
1463 // non-constant `Start` and do a general SCEV subtraction to compute
1464 // `PreStart` below.
1465 //
1466 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1467 if (!StartC)
1468 return false;
1469
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001470 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001471
1472 for (unsigned Delta : {-2, -1, 1, 2}) {
1473 const SCEV *PreStart = getConstant(StartAI - Delta);
1474
Sanjoy Das42801102015-10-23 06:57:21 +00001475 FoldingSetNodeID ID;
1476 ID.AddInteger(scAddRecExpr);
1477 ID.AddPointer(PreStart);
1478 ID.AddPointer(Step);
1479 ID.AddPointer(L);
1480 void *IP = nullptr;
1481 const auto *PreAR =
1482 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1483
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001484 // Give up if we don't already have the add recurrence we need because
1485 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001486 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1487 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1488 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1489 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1490 DeltaS, &Pred, this);
1491 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1492 return true;
1493 }
1494 }
1495
1496 return false;
1497}
1498
Dan Gohmanaf752342009-07-07 17:06:11 +00001499const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001500 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001501 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001502 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001503 assert(isSCEVable(Ty) &&
1504 "This is not a conversion to a SCEVable type!");
1505 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001506
Dan Gohman3423e722009-06-30 20:13:32 +00001507 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001508 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1509 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001510 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001511
Dan Gohman79af8542009-04-22 16:20:48 +00001512 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001513 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001514 return getZeroExtendExpr(SZ->getOperand(), Ty);
1515
Dan Gohman74a0ba12009-07-13 20:55:53 +00001516 // Before doing any expensive analysis, check to see if we've already
1517 // computed a SCEV for this Op and Ty.
1518 FoldingSetNodeID ID;
1519 ID.AddInteger(scZeroExtend);
1520 ID.AddPointer(Op);
1521 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001522 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001523 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1524
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001525 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1526 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1527 // It's possible the bits taken off by the truncate were all zero bits. If
1528 // so, we should be able to simplify this further.
1529 const SCEV *X = ST->getOperand();
1530 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001531 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1532 unsigned NewBits = getTypeSizeInBits(Ty);
1533 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001534 CR.zextOrTrunc(NewBits)))
1535 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001536 }
1537
Dan Gohman76466372009-04-27 20:16:15 +00001538 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001539 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001540 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001541 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001542 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001543 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001544 const SCEV *Start = AR->getStart();
1545 const SCEV *Step = AR->getStepRecurrence(*this);
1546 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1547 const Loop *L = AR->getLoop();
1548
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001549 if (!AR->hasNoUnsignedWrap()) {
1550 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1551 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1552 }
1553
Dan Gohman62ef6a72009-07-25 01:22:26 +00001554 // If we have special knowledge that this addrec won't overflow,
1555 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001556 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001557 return getAddRecExpr(
1558 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1559 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001560
Dan Gohman76466372009-04-27 20:16:15 +00001561 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1562 // Note that this serves two purposes: It filters out loops that are
1563 // simply not analyzable, and it covers the case where this code is
1564 // being called from within backedge-taken count analysis, such that
1565 // attempting to ask for the backedge-taken count would likely result
1566 // in infinite recursion. In the later case, the analysis code will
1567 // cope with a conservative value, and it will take care to purge
1568 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001569 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001570 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001571 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001572 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001573
1574 // Check whether the backedge-taken count can be losslessly casted to
1575 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001576 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001577 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001578 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001579 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1580 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001581 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001582 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001583 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001584 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1585 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1586 const SCEV *WideMaxBECount =
1587 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001588 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001589 getAddExpr(WideStart,
1590 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001591 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001592 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001593 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1594 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001595 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001596 return getAddRecExpr(
1597 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1598 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001599 }
Dan Gohman76466372009-04-27 20:16:15 +00001600 // Similar to above, only this time treat the step value as signed.
1601 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001602 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001603 getAddExpr(WideStart,
1604 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001605 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001606 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001607 // Cache knowledge of AR NW, which is propagated to this AddRec.
1608 // Negative step causes unsigned wrap, but it still can't self-wrap.
1609 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001610 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001611 return getAddRecExpr(
1612 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1613 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001614 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001615 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001616 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001617
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001618 // Normally, in the cases we can prove no-overflow via a
1619 // backedge guarding condition, we can also compute a backedge
1620 // taken count for the loop. The exceptions are assumptions and
1621 // guards present in the loop -- SCEV is not great at exploiting
1622 // these to compute max backedge taken counts, but can still use
1623 // these to prove lack of overflow. Use this fact to avoid
1624 // doing extra work that may not pay off.
1625 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001626 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001627 // If the backedge is guarded by a comparison with the pre-inc
1628 // value the addrec is safe. Also, if the entry is guarded by
1629 // a comparison with the start value and the backedge is
1630 // guarded by a comparison with the post-inc value, the addrec
1631 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001632 if (isKnownPositive(Step)) {
1633 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1634 getUnsignedRange(Step).getUnsignedMax());
1635 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001636 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001637 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001638 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001639 // Cache knowledge of AR NUW, which is propagated to this
1640 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001641 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001642 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001643 return getAddRecExpr(
1644 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1645 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001646 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001647 } else if (isKnownNegative(Step)) {
1648 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1649 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001650 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1651 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001652 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001653 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001654 // Cache knowledge of AR NW, which is propagated to this
1655 // AddRec. Negative step causes unsigned wrap, but it
1656 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001657 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1658 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001659 return getAddRecExpr(
1660 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1661 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001662 }
Dan Gohman76466372009-04-27 20:16:15 +00001663 }
1664 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001665
1666 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1667 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1668 return getAddRecExpr(
1669 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1670 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1671 }
Dan Gohman76466372009-04-27 20:16:15 +00001672 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001673
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001674 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1675 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001676 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001677 // If the addition does not unsign overflow then we can, by definition,
1678 // commute the zero extension with the addition operation.
1679 SmallVector<const SCEV *, 4> Ops;
1680 for (const auto *Op : SA->operands())
1681 Ops.push_back(getZeroExtendExpr(Op, Ty));
1682 return getAddExpr(Ops, SCEV::FlagNUW);
1683 }
1684 }
1685
Dan Gohman74a0ba12009-07-13 20:55:53 +00001686 // The cast wasn't folded; create an explicit cast node.
1687 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001688 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001689 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1690 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001691 UniqueSCEVs.InsertNode(S, IP);
1692 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001693}
1694
Dan Gohmanaf752342009-07-07 17:06:11 +00001695const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001696 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001697 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001698 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001699 assert(isSCEVable(Ty) &&
1700 "This is not a conversion to a SCEVable type!");
1701 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001702
Dan Gohman3423e722009-06-30 20:13:32 +00001703 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001704 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1705 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001706 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001707
Dan Gohman79af8542009-04-22 16:20:48 +00001708 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001709 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001710 return getSignExtendExpr(SS->getOperand(), Ty);
1711
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001712 // sext(zext(x)) --> zext(x)
1713 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1714 return getZeroExtendExpr(SZ->getOperand(), Ty);
1715
Dan Gohman74a0ba12009-07-13 20:55:53 +00001716 // Before doing any expensive analysis, check to see if we've already
1717 // computed a SCEV for this Op and Ty.
1718 FoldingSetNodeID ID;
1719 ID.AddInteger(scSignExtend);
1720 ID.AddPointer(Op);
1721 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001722 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001723 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1724
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001725 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1726 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1727 // It's possible the bits taken off by the truncate were all sign bits. If
1728 // so, we should be able to simplify this further.
1729 const SCEV *X = ST->getOperand();
1730 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001731 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1732 unsigned NewBits = getTypeSizeInBits(Ty);
1733 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001734 CR.sextOrTrunc(NewBits)))
1735 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001736 }
1737
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001738 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001739 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001740 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001741 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1742 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001743 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001744 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001745 const APInt &C1 = SC1->getAPInt();
1746 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001747 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001748 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001749 return getAddExpr(getSignExtendExpr(SC1, Ty),
1750 getSignExtendExpr(SMul, Ty));
1751 }
1752 }
1753 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001754
1755 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001756 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001757 // If the addition does not sign overflow then we can, by definition,
1758 // commute the sign extension with the addition operation.
1759 SmallVector<const SCEV *, 4> Ops;
1760 for (const auto *Op : SA->operands())
1761 Ops.push_back(getSignExtendExpr(Op, Ty));
1762 return getAddExpr(Ops, SCEV::FlagNSW);
1763 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001764 }
Dan Gohman76466372009-04-27 20:16:15 +00001765 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001766 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001767 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001768 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001769 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001770 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001771 const SCEV *Start = AR->getStart();
1772 const SCEV *Step = AR->getStepRecurrence(*this);
1773 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1774 const Loop *L = AR->getLoop();
1775
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001776 if (!AR->hasNoSignedWrap()) {
1777 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1778 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1779 }
1780
Dan Gohman62ef6a72009-07-25 01:22:26 +00001781 // If we have special knowledge that this addrec won't overflow,
1782 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001783 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001784 return getAddRecExpr(
1785 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1786 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001787
Dan Gohman76466372009-04-27 20:16:15 +00001788 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1789 // Note that this serves two purposes: It filters out loops that are
1790 // simply not analyzable, and it covers the case where this code is
1791 // being called from within backedge-taken count analysis, such that
1792 // attempting to ask for the backedge-taken count would likely result
1793 // in infinite recursion. In the later case, the analysis code will
1794 // cope with a conservative value, and it will take care to purge
1795 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001796 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001797 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001798 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001799 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001800
1801 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001802 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001803 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001804 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001805 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001806 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1807 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001808 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001809 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001810 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001811 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1812 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1813 const SCEV *WideMaxBECount =
1814 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001815 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001816 getAddExpr(WideStart,
1817 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001818 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001819 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001820 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1821 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001822 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001823 return getAddRecExpr(
1824 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1825 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001826 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001827 // Similar to above, only this time treat the step value as unsigned.
1828 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001829 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001830 getAddExpr(WideStart,
1831 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001832 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001833 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001834 // If AR wraps around then
1835 //
1836 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1837 // => SAdd != OperandExtendedAdd
1838 //
1839 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1840 // (SAdd == OperandExtendedAdd => AR is NW)
1841
1842 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1843
Dan Gohman8c129d72009-07-16 17:34:36 +00001844 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001845 return getAddRecExpr(
1846 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1847 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001848 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001849 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001850 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001851
Sanjoy Das787c2462016-05-11 17:41:26 +00001852 // Normally, in the cases we can prove no-overflow via a
1853 // backedge guarding condition, we can also compute a backedge
1854 // taken count for the loop. The exceptions are assumptions and
1855 // guards present in the loop -- SCEV is not great at exploiting
1856 // these to compute max backedge taken counts, but can still use
1857 // these to prove lack of overflow. Use this fact to avoid
1858 // doing extra work that may not pay off.
1859
1860 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001861 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001862 // If the backedge is guarded by a comparison with the pre-inc
1863 // value the addrec is safe. Also, if the entry is guarded by
1864 // a comparison with the start value and the backedge is
1865 // guarded by a comparison with the post-inc value, the addrec
1866 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001867 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001868 const SCEV *OverflowLimit =
1869 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001870 if (OverflowLimit &&
1871 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1872 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1873 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1874 OverflowLimit)))) {
1875 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001877 return getAddRecExpr(
1878 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1879 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001880 }
1881 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001882
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001883 // If Start and Step are constants, check if we can apply this
1884 // transformation:
1885 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001886 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1887 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001888 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001889 const APInt &C1 = SC1->getAPInt();
1890 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001891 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1892 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001893 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001894 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1895 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001896 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1897 }
1898 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001899
1900 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1901 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1902 return getAddRecExpr(
1903 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1904 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1905 }
Dan Gohman76466372009-04-27 20:16:15 +00001906 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001907
Sanjoy Das11ef6062016-03-03 18:31:23 +00001908 // If the input value is provably positive and we could not simplify
1909 // away the sext build a zext instead.
1910 if (isKnownNonNegative(Op))
1911 return getZeroExtendExpr(Op, Ty);
1912
Dan Gohman74a0ba12009-07-13 20:55:53 +00001913 // The cast wasn't folded; create an explicit cast node.
1914 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001916 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1917 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001918 UniqueSCEVs.InsertNode(S, IP);
1919 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001920}
1921
Dan Gohman8db2edc2009-06-13 15:56:47 +00001922/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1923/// unspecified bits out to the given type.
1924///
Dan Gohmanaf752342009-07-07 17:06:11 +00001925const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001926 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001927 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1928 "This is not an extending conversion!");
1929 assert(isSCEVable(Ty) &&
1930 "This is not a conversion to a SCEVable type!");
1931 Ty = getEffectiveSCEVType(Ty);
1932
1933 // Sign-extend negative constants.
1934 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001935 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001936 return getSignExtendExpr(Op, Ty);
1937
1938 // Peel off a truncate cast.
1939 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001940 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001941 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1942 return getAnyExtendExpr(NewOp, Ty);
1943 return getTruncateOrNoop(NewOp, Ty);
1944 }
1945
1946 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001947 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001948 if (!isa<SCEVZeroExtendExpr>(ZExt))
1949 return ZExt;
1950
1951 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001952 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001953 if (!isa<SCEVSignExtendExpr>(SExt))
1954 return SExt;
1955
Dan Gohman51ad99d2010-01-21 02:09:26 +00001956 // Force the cast to be folded into the operands of an addrec.
1957 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1958 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001959 for (const SCEV *Op : AR->operands())
1960 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001961 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001962 }
1963
Dan Gohman8db2edc2009-06-13 15:56:47 +00001964 // If the expression is obviously signed, use the sext cast value.
1965 if (isa<SCEVSMaxExpr>(Op))
1966 return SExt;
1967
1968 // Absent any other information, use the zext cast value.
1969 return ZExt;
1970}
1971
Sanjoy Dasf8570812016-05-29 00:38:22 +00001972/// Process the given Ops list, which is a list of operands to be added under
1973/// the given scale, update the given map. This is a helper function for
1974/// getAddRecExpr. As an example of what it does, given a sequence of operands
1975/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001976///
Tobias Grosserba49e422014-03-05 10:37:17 +00001977/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001978///
1979/// where A and B are constants, update the map with these values:
1980///
1981/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1982///
1983/// and add 13 + A*B*29 to AccumulatedConstant.
1984/// This will allow getAddRecExpr to produce this:
1985///
1986/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1987///
1988/// This form often exposes folding opportunities that are hidden in
1989/// the original operand list.
1990///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001991/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001992/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1993/// the common case where no interesting opportunities are present, and
1994/// is also used as a check to avoid infinite recursion.
1995///
1996static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001997CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001998 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001999 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002000 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00002001 const APInt &Scale,
2002 ScalarEvolution &SE) {
2003 bool Interesting = false;
2004
Dan Gohman45073042010-06-18 19:12:32 +00002005 // Iterate over the add operands. They are sorted, with constants first.
2006 unsigned i = 0;
2007 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2008 ++i;
2009 // Pull a buried constant out to the outside.
2010 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2011 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002012 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00002013 }
2014
2015 // Next comes everything else. We're especially interested in multiplies
2016 // here, but they're in the middle, so just visit the rest with one loop.
2017 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002018 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2019 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2020 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002021 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002022 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2023 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002024 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002025 Interesting |=
2026 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002027 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002028 NewScale, SE);
2029 } else {
2030 // A multiplication of a constant with some other value. Update
2031 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002032 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2033 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002034 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002035 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002036 NewOps.push_back(Pair.first->first);
2037 } else {
2038 Pair.first->second += NewScale;
2039 // The map already had an entry for this value, which may indicate
2040 // a folding opportunity.
2041 Interesting = true;
2042 }
2043 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002044 } else {
2045 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002046 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002047 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002048 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002049 NewOps.push_back(Pair.first->first);
2050 } else {
2051 Pair.first->second += Scale;
2052 // The map already had an entry for this value, which may indicate
2053 // a folding opportunity.
2054 Interesting = true;
2055 }
2056 }
2057 }
2058
2059 return Interesting;
2060}
2061
Sanjoy Das81401d42015-01-10 23:41:24 +00002062// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2063// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2064// can't-overflow flags for the operation if possible.
2065static SCEV::NoWrapFlags
2066StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2067 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002068 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002069 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002070 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002071
2072 bool CanAnalyze =
2073 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2074 (void)CanAnalyze;
2075 assert(CanAnalyze && "don't call from other places!");
2076
2077 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2078 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002079 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002080
2081 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002082 auto IsKnownNonNegative = [&](const SCEV *S) {
2083 return SE->isKnownNonNegative(S);
2084 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002085
Sanjoy Das3b827c72015-11-29 23:40:53 +00002086 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002087 Flags =
2088 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002089
Sanjoy Das8f274152015-10-22 19:57:19 +00002090 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2091
2092 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2093 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2094
2095 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2096 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2097
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002098 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002099 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002100 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2101 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002102 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2103 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2104 }
2105 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002106 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2107 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002108 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2109 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2110 }
2111 }
2112
2113 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002114}
2115
Sanjoy Dasf8570812016-05-29 00:38:22 +00002116/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002117const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002118 SCEV::NoWrapFlags Flags,
2119 unsigned Depth) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002120 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2121 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002122 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002123 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002124#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002125 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002126 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002127 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002128 "SCEVAddExpr operand types don't match!");
2129#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002130
2131 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002132 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002133
Sanjoy Das64895612015-10-09 02:44:45 +00002134 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2135
Chris Lattnerd934c702004-04-02 20:23:17 +00002136 // If there are any constants, fold them together.
2137 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002138 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002139 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002140 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002141 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002142 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002143 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002144 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002145 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002146 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002147 }
2148
2149 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002150 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002151 Ops.erase(Ops.begin());
2152 --Idx;
2153 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002154
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002155 if (Ops.size() == 1) return Ops[0];
2156 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002157
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002158 // Limit recursion calls depth
2159 if (Depth > MaxAddExprDepth)
2160 return getOrCreateAddExpr(Ops, Flags);
2161
Dan Gohman15871f22010-08-27 21:39:59 +00002162 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002163 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002164 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002165 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002166 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002167 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002168 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002169 // Scan ahead to count how many equal operands there are.
2170 unsigned Count = 2;
2171 while (i+Count != e && Ops[i+Count] == Ops[i])
2172 ++Count;
2173 // Merge the values into a multiply.
2174 const SCEV *Scale = getConstant(Ty, Count);
2175 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2176 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002177 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002178 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002179 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002180 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002181 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002182 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002183 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002184 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002185
Dan Gohman2e55cc52009-05-08 21:03:19 +00002186 // Check for truncates. If all the operands are truncated from the same
2187 // type, see if factoring out the truncate would permit the result to be
2188 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2189 // if the contents of the resulting outer trunc fold to something simple.
2190 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2191 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002192 Type *DstType = Trunc->getType();
2193 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002194 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002195 bool Ok = true;
2196 // Check all the operands to see if they can be represented in the
2197 // source type of the truncate.
2198 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2199 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2200 if (T->getOperand()->getType() != SrcType) {
2201 Ok = false;
2202 break;
2203 }
2204 LargeOps.push_back(T->getOperand());
2205 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002206 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002207 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002208 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002209 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2210 if (const SCEVTruncateExpr *T =
2211 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2212 if (T->getOperand()->getType() != SrcType) {
2213 Ok = false;
2214 break;
2215 }
2216 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002217 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002218 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002219 } else {
2220 Ok = false;
2221 break;
2222 }
2223 }
2224 if (Ok)
2225 LargeOps.push_back(getMulExpr(LargeMulOps));
2226 } else {
2227 Ok = false;
2228 break;
2229 }
2230 }
2231 if (Ok) {
2232 // Evaluate the expression in the larger type.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002233 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002234 // If it folds to something simple, use it. Otherwise, don't.
2235 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2236 return getTruncateExpr(Fold, DstType);
2237 }
2238 }
2239
2240 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002241 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2242 ++Idx;
2243
2244 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002245 if (Idx < Ops.size()) {
2246 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002247 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Daniil Fukalovb09dac52017-01-26 13:33:17 +00002248 if (Ops.size() > AddOpsInlineThreshold ||
2249 Add->getNumOperands() > AddOpsInlineThreshold)
2250 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002251 // If we have an add, expand the add operands onto the end of the operands
2252 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002253 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002254 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002255 DeletedAdd = true;
2256 }
2257
2258 // If we deleted at least one add, we added operands to the end of the list,
2259 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002260 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002261 if (DeletedAdd)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002262 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002263 }
2264
2265 // Skip over the add expression until we get to a multiply.
2266 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2267 ++Idx;
2268
Dan Gohman038d02e2009-06-14 22:58:51 +00002269 // Check to see if there are any folding opportunities present with
2270 // operands multiplied by constant values.
2271 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2272 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002273 DenseMap<const SCEV *, APInt> M;
2274 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002275 APInt AccumulatedConstant(BitWidth, 0);
2276 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002277 Ops.data(), Ops.size(),
2278 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002279 struct APIntCompare {
2280 bool operator()(const APInt &LHS, const APInt &RHS) const {
2281 return LHS.ult(RHS);
2282 }
2283 };
2284
Dan Gohman038d02e2009-06-14 22:58:51 +00002285 // Some interesting folding opportunity is present, so its worthwhile to
2286 // re-generate the operands list. Group the operands by constant scale,
2287 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002288 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002289 for (const SCEV *NewOp : NewOps)
2290 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002291 // Re-generate the operands list.
2292 Ops.clear();
2293 if (AccumulatedConstant != 0)
2294 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002295 for (auto &MulOp : MulOpLists)
2296 if (MulOp.first != 0)
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002297 Ops.push_back(getMulExpr(
2298 getConstant(MulOp.first),
2299 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002300 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002301 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002302 if (Ops.size() == 1)
2303 return Ops[0];
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002304 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman038d02e2009-06-14 22:58:51 +00002305 }
2306 }
2307
Chris Lattnerd934c702004-04-02 20:23:17 +00002308 // If we are adding something to a multiply expression, make sure the
2309 // something is not already an operand of the multiply. If so, merge it into
2310 // the multiply.
2311 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002312 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002313 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002314 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002315 if (isa<SCEVConstant>(MulOpSCEV))
2316 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002317 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002318 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002319 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002320 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002321 if (Mul->getNumOperands() != 2) {
2322 // If the multiply has more than two operands, we must get the
2323 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002324 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2325 Mul->op_begin()+MulOp);
2326 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002327 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002328 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002329 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2330 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohman157847f2010-08-12 14:52:55 +00002331 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002332 if (Ops.size() == 2) return OuterMul;
2333 if (AddOp < Idx) {
2334 Ops.erase(Ops.begin()+AddOp);
2335 Ops.erase(Ops.begin()+Idx-1);
2336 } else {
2337 Ops.erase(Ops.begin()+Idx);
2338 Ops.erase(Ops.begin()+AddOp-1);
2339 }
2340 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002341 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002342 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002343
Chris Lattnerd934c702004-04-02 20:23:17 +00002344 // Check this multiply against other multiplies being added together.
2345 for (unsigned OtherMulIdx = Idx+1;
2346 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2347 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002348 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002349 // If MulOp occurs in OtherMul, we can fold the two multiplies
2350 // together.
2351 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2352 OMulOp != e; ++OMulOp)
2353 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2354 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002355 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002356 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002357 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002358 Mul->op_begin()+MulOp);
2359 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002360 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002361 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002362 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002363 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002364 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002365 OtherMul->op_begin()+OMulOp);
2366 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002367 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002368 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002369 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2370 const SCEV *InnerMulSum =
2371 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanaf752342009-07-07 17:06:11 +00002372 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002373 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002374 Ops.erase(Ops.begin()+Idx);
2375 Ops.erase(Ops.begin()+OtherMulIdx-1);
2376 Ops.push_back(OuterMul);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002377 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002378 }
2379 }
2380 }
2381 }
2382
2383 // If there are any add recurrences in the operands list, see if any other
2384 // added values are loop invariant. If so, we can fold them into the
2385 // recurrence.
2386 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2387 ++Idx;
2388
2389 // Scan over all recurrences, trying to fold loop invariants into them.
2390 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2391 // Scan all of the other operands to this add and add them to the vector if
2392 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002393 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002394 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002395 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002396 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002397 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002398 LIOps.push_back(Ops[i]);
2399 Ops.erase(Ops.begin()+i);
2400 --i; --e;
2401 }
2402
2403 // If we found some loop invariants, fold them into the recurrence.
2404 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002405 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002406 LIOps.push_back(AddRec->getStart());
2407
Dan Gohmanaf752342009-07-07 17:06:11 +00002408 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002409 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002410 // This follows from the fact that the no-wrap flags on the outer add
2411 // expression are applicable on the 0th iteration, when the add recurrence
2412 // will be equal to its start value.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002413 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002414
Dan Gohman16206132010-06-30 07:16:37 +00002415 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002416 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002417 // Always propagate NW.
2418 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002419 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002420
Chris Lattnerd934c702004-04-02 20:23:17 +00002421 // If all of the other operands were loop invariant, we are done.
2422 if (Ops.size() == 1) return NewRec;
2423
Nick Lewyckydb66b822011-09-06 05:08:09 +00002424 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002425 for (unsigned i = 0;; ++i)
2426 if (Ops[i] == AddRec) {
2427 Ops[i] = NewRec;
2428 break;
2429 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002430 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002431 }
2432
2433 // Okay, if there weren't any loop invariants to be folded, check to see if
2434 // there are multiple AddRec's with the same loop induction variable being
2435 // added together. If so, we can fold them.
2436 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002437 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2438 ++OtherIdx)
2439 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2440 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2441 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2442 AddRec->op_end());
2443 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2444 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002445 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002446 if (OtherAddRec->getLoop() == AddRecLoop) {
2447 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2448 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002449 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002450 AddRecOps.append(OtherAddRec->op_begin()+i,
2451 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002452 break;
2453 }
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002454 SmallVector<const SCEV *, 2> TwoOps = {
2455 AddRecOps[i], OtherAddRec->getOperand(i)};
2456 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002457 }
2458 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002459 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002460 // Step size has changed, so we cannot guarantee no self-wraparound.
2461 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002462 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002463 }
2464
2465 // Otherwise couldn't fold anything into this recurrence. Move onto the
2466 // next one.
2467 }
2468
2469 // Okay, it looks like we really DO need an add expr. Check to see if we
2470 // already have one, otherwise create a new one.
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002471 return getOrCreateAddExpr(Ops, Flags);
2472}
2473
2474const SCEV *
2475ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2476 SCEV::NoWrapFlags Flags) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002477 FoldingSetNodeID ID;
2478 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002479 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2480 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002481 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002482 SCEVAddExpr *S =
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002483 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
Dan Gohman51ad99d2010-01-21 02:09:26 +00002484 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002485 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2486 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +00002487 S = new (SCEVAllocator)
2488 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002489 UniqueSCEVs.InsertNode(S, IP);
2490 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002491 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002492 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002493}
2494
Nick Lewycky287682e2011-10-04 06:51:26 +00002495static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2496 uint64_t k = i*j;
2497 if (j > 1 && k / j != i) Overflow = true;
2498 return k;
2499}
2500
2501/// Compute the result of "n choose k", the binomial coefficient. If an
2502/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002503/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002504static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2505 // We use the multiplicative formula:
2506 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2507 // At each iteration, we take the n-th term of the numeral and divide by the
2508 // (k-n)th term of the denominator. This division will always produce an
2509 // integral result, and helps reduce the chance of overflow in the
2510 // intermediate computations. However, we can still overflow even when the
2511 // final result would fit.
2512
2513 if (n == 0 || n == k) return 1;
2514 if (k > n) return 0;
2515
2516 if (k > n/2)
2517 k = n-k;
2518
2519 uint64_t r = 1;
2520 for (uint64_t i = 1; i <= k; ++i) {
2521 r = umul_ov(r, n-(i-1), Overflow);
2522 r /= i;
2523 }
2524 return r;
2525}
2526
Nick Lewycky05044c22014-12-06 00:45:50 +00002527/// Determine if any of the operands in this SCEV are a constant or if
2528/// any of the add or multiply expressions in this SCEV contain a constant.
2529static bool containsConstantSomewhere(const SCEV *StartExpr) {
2530 SmallVector<const SCEV *, 4> Ops;
2531 Ops.push_back(StartExpr);
2532 while (!Ops.empty()) {
2533 const SCEV *CurrentExpr = Ops.pop_back_val();
2534 if (isa<SCEVConstant>(*CurrentExpr))
2535 return true;
2536
2537 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2538 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002539 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002540 }
2541 }
2542 return false;
2543}
2544
Sanjoy Dasf8570812016-05-29 00:38:22 +00002545/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002546const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002547 SCEV::NoWrapFlags Flags) {
2548 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2549 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002550 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002551 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002552#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002553 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002554 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002555 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002556 "SCEVMulExpr operand types don't match!");
2557#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002558
2559 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002560 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002561
Sanjoy Das64895612015-10-09 02:44:45 +00002562 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2563
Chris Lattnerd934c702004-04-02 20:23:17 +00002564 // If there are any constants, fold them together.
2565 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002566 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002567
2568 // C1*(C2+V) -> C1*C2 + C1*V
2569 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002570 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2571 // If any of Add's ops are Adds or Muls with a constant,
2572 // apply this transformation as well.
2573 if (Add->getNumOperands() == 2)
2574 if (containsConstantSomewhere(Add))
2575 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2576 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002577
Chris Lattnerd934c702004-04-02 20:23:17 +00002578 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002579 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002580 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002581 ConstantInt *Fold =
2582 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002583 Ops[0] = getConstant(Fold);
2584 Ops.erase(Ops.begin()+1); // Erase the folded element
2585 if (Ops.size() == 1) return Ops[0];
2586 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002587 }
2588
2589 // If we are left with a constant one being multiplied, strip it off.
2590 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2591 Ops.erase(Ops.begin());
2592 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002593 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002594 // If we have a multiply of zero, it will always be zero.
2595 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002596 } else if (Ops[0]->isAllOnesValue()) {
2597 // If we have a mul by -1 of an add, try distributing the -1 among the
2598 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002599 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002600 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2601 SmallVector<const SCEV *, 4> NewOps;
2602 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002603 for (const SCEV *AddOp : Add->operands()) {
2604 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002605 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2606 NewOps.push_back(Mul);
2607 }
2608 if (AnyFolded)
2609 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002610 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002611 // Negation preserves a recurrence's no self-wrap property.
2612 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002613 for (const SCEV *AddRecOp : AddRec->operands())
2614 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2615
Andrew Tricke92dcce2011-03-14 17:38:54 +00002616 return getAddRecExpr(Operands, AddRec->getLoop(),
2617 AddRec->getNoWrapFlags(SCEV::FlagNW));
2618 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002619 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002620 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002621
2622 if (Ops.size() == 1)
2623 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002624 }
2625
2626 // Skip over the add expression until we get to a multiply.
2627 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2628 ++Idx;
2629
Chris Lattnerd934c702004-04-02 20:23:17 +00002630 // If there are mul operands inline them all into this expression.
2631 if (Idx < Ops.size()) {
2632 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002633 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002634 if (Ops.size() > MulOpsInlineThreshold)
2635 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002636 // If we have an mul, expand the mul operands onto the end of the operands
2637 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002638 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002639 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002640 DeletedMul = true;
2641 }
2642
2643 // If we deleted at least one mul, we added operands to the end of the list,
2644 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002645 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002646 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002647 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002648 }
2649
2650 // If there are any add recurrences in the operands list, see if any other
2651 // added values are loop invariant. If so, we can fold them into the
2652 // recurrence.
2653 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2654 ++Idx;
2655
2656 // Scan over all recurrences, trying to fold loop invariants into them.
2657 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2658 // Scan all of the other operands to this mul and add them to the vector if
2659 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002660 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002661 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002662 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002663 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002664 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002665 LIOps.push_back(Ops[i]);
2666 Ops.erase(Ops.begin()+i);
2667 --i; --e;
2668 }
2669
2670 // If we found some loop invariants, fold them into the recurrence.
2671 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002672 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002673 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002674 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002675 const SCEV *Scale = getMulExpr(LIOps);
2676 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2677 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002678
Dan Gohman16206132010-06-30 07:16:37 +00002679 // Build the new addrec. Propagate the NUW and NSW flags if both the
2680 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002681 //
2682 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002683 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002684 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2685 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002686
2687 // If all of the other operands were loop invariant, we are done.
2688 if (Ops.size() == 1) return NewRec;
2689
Nick Lewyckydb66b822011-09-06 05:08:09 +00002690 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002691 for (unsigned i = 0;; ++i)
2692 if (Ops[i] == AddRec) {
2693 Ops[i] = NewRec;
2694 break;
2695 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002696 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002697 }
2698
2699 // Okay, if there weren't any loop invariants to be folded, check to see if
2700 // there are multiple AddRec's with the same loop induction variable being
2701 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002702
2703 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2704 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2705 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2706 // ]]],+,...up to x=2n}.
2707 // Note that the arguments to choose() are always integers with values
2708 // known at compile time, never SCEV objects.
2709 //
2710 // The implementation avoids pointless extra computations when the two
2711 // addrec's are of different length (mathematically, it's equivalent to
2712 // an infinite stream of zeros on the right).
2713 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002714 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002715 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002716 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002717 const SCEVAddRecExpr *OtherAddRec =
2718 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2719 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002720 continue;
2721
Nick Lewycky97756402014-09-01 05:17:15 +00002722 bool Overflow = false;
2723 Type *Ty = AddRec->getType();
2724 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2725 SmallVector<const SCEV*, 7> AddRecOps;
2726 for (int x = 0, xe = AddRec->getNumOperands() +
2727 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002728 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002729 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2730 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2731 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2732 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2733 z < ze && !Overflow; ++z) {
2734 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2735 uint64_t Coeff;
2736 if (LargerThan64Bits)
2737 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2738 else
2739 Coeff = Coeff1*Coeff2;
2740 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2741 const SCEV *Term1 = AddRec->getOperand(y-z);
2742 const SCEV *Term2 = OtherAddRec->getOperand(z);
2743 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002744 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002745 }
Nick Lewycky97756402014-09-01 05:17:15 +00002746 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002747 }
Nick Lewycky97756402014-09-01 05:17:15 +00002748 if (!Overflow) {
2749 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2750 SCEV::FlagAnyWrap);
2751 if (Ops.size() == 2) return NewAddRec;
2752 Ops[Idx] = NewAddRec;
2753 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2754 OpsModified = true;
2755 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2756 if (!AddRec)
2757 break;
2758 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002759 }
Nick Lewycky97756402014-09-01 05:17:15 +00002760 if (OpsModified)
2761 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002762
2763 // Otherwise couldn't fold anything into this recurrence. Move onto the
2764 // next one.
2765 }
2766
2767 // Okay, it looks like we really DO need an mul expr. Check to see if we
2768 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002769 FoldingSetNodeID ID;
2770 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002771 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2772 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002773 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002774 SCEVMulExpr *S =
2775 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2776 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002777 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2778 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002779 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2780 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002781 UniqueSCEVs.InsertNode(S, IP);
2782 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002783 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002784 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002785}
2786
Sanjoy Dasf8570812016-05-29 00:38:22 +00002787/// Get a canonical unsigned division expression, or something simpler if
2788/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002789const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2790 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002791 assert(getEffectiveSCEVType(LHS->getType()) ==
2792 getEffectiveSCEVType(RHS->getType()) &&
2793 "SCEVUDivExpr operand types don't match!");
2794
Dan Gohmana30370b2009-05-04 22:02:23 +00002795 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002796 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002797 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002798 // If the denominator is zero, the result of the udiv is undefined. Don't
2799 // try to analyze it, because the resolution chosen here may differ from
2800 // the resolution chosen in other parts of the compiler.
2801 if (!RHSC->getValue()->isZero()) {
2802 // Determine if the division can be folded into the operands of
2803 // its operands.
2804 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002805 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002806 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002807 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002808 // For non-power-of-two values, effectively round the value up to the
2809 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002810 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002811 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002812 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002813 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002814 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2815 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002816 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2817 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002818 const APInt &StepInt = Step->getAPInt();
2819 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002820 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002821 getZeroExtendExpr(AR, ExtTy) ==
2822 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2823 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002824 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002825 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002826 for (const SCEV *Op : AR->operands())
2827 Operands.push_back(getUDivExpr(Op, RHS));
2828 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002829 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002830 /// Get a canonical UDivExpr for a recurrence.
2831 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2832 // We can currently only fold X%N if X is constant.
2833 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2834 if (StartC && !DivInt.urem(StepInt) &&
2835 getZeroExtendExpr(AR, ExtTy) ==
2836 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2837 getZeroExtendExpr(Step, ExtTy),
2838 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002839 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002840 const APInt &StartRem = StartInt.urem(StepInt);
2841 if (StartRem != 0)
2842 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2843 AR->getLoop(), SCEV::FlagNW);
2844 }
2845 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002846 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2847 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2848 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002849 for (const SCEV *Op : M->operands())
2850 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002851 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2852 // Find an operand that's safely divisible.
2853 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2854 const SCEV *Op = M->getOperand(i);
2855 const SCEV *Div = getUDivExpr(Op, RHSC);
2856 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2857 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2858 M->op_end());
2859 Operands[i] = Div;
2860 return getMulExpr(Operands);
2861 }
2862 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002863 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002864 // (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 +00002865 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002866 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002867 for (const SCEV *Op : A->operands())
2868 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002869 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2870 Operands.clear();
2871 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2872 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2873 if (isa<SCEVUDivExpr>(Op) ||
2874 getMulExpr(Op, RHS) != A->getOperand(i))
2875 break;
2876 Operands.push_back(Op);
2877 }
2878 if (Operands.size() == A->getNumOperands())
2879 return getAddExpr(Operands);
2880 }
2881 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002882
Dan Gohmanacd700a2010-04-22 01:35:11 +00002883 // Fold if both operands are constant.
2884 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2885 Constant *LHSCV = LHSC->getValue();
2886 Constant *RHSCV = RHSC->getValue();
2887 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2888 RHSCV)));
2889 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002890 }
2891 }
2892
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002893 FoldingSetNodeID ID;
2894 ID.AddInteger(scUDivExpr);
2895 ID.AddPointer(LHS);
2896 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002897 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002898 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002899 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2900 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002901 UniqueSCEVs.InsertNode(S, IP);
2902 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002903}
2904
Nick Lewycky31eaca52014-01-27 10:04:03 +00002905static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002906 APInt A = C1->getAPInt().abs();
2907 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002908 uint32_t ABW = A.getBitWidth();
2909 uint32_t BBW = B.getBitWidth();
2910
2911 if (ABW > BBW)
2912 B = B.zext(ABW);
2913 else if (ABW < BBW)
2914 A = A.zext(BBW);
2915
2916 return APIntOps::GreatestCommonDivisor(A, B);
2917}
2918
Sanjoy Dasf8570812016-05-29 00:38:22 +00002919/// Get a canonical unsigned division expression, or something simpler if
2920/// possible. There is no representation for an exact udiv in SCEV IR, but we
2921/// can attempt to remove factors from the LHS and RHS. We can't do this when
2922/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002923const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2924 const SCEV *RHS) {
2925 // TODO: we could try to find factors in all sorts of things, but for now we
2926 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2927 // end of this file for inspiration.
2928
2929 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
Eli Friedmanf1f49c82017-01-18 23:56:42 +00002930 if (!Mul || !Mul->hasNoUnsignedWrap())
Nick Lewycky31eaca52014-01-27 10:04:03 +00002931 return getUDivExpr(LHS, RHS);
2932
2933 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2934 // If the mulexpr multiplies by a constant, then that constant must be the
2935 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002936 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002937 if (LHSCst == RHSCst) {
2938 SmallVector<const SCEV *, 2> Operands;
2939 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2940 return getMulExpr(Operands);
2941 }
2942
2943 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2944 // that there's a factor provided by one of the other terms. We need to
2945 // check.
2946 APInt Factor = gcd(LHSCst, RHSCst);
2947 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002948 LHSCst =
2949 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2950 RHSCst =
2951 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002952 SmallVector<const SCEV *, 2> Operands;
2953 Operands.push_back(LHSCst);
2954 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2955 LHS = getMulExpr(Operands);
2956 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002957 Mul = dyn_cast<SCEVMulExpr>(LHS);
2958 if (!Mul)
2959 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002960 }
2961 }
2962 }
2963
2964 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2965 if (Mul->getOperand(i) == RHS) {
2966 SmallVector<const SCEV *, 2> Operands;
2967 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2968 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2969 return getMulExpr(Operands);
2970 }
2971 }
2972
2973 return getUDivExpr(LHS, RHS);
2974}
Chris Lattnerd934c702004-04-02 20:23:17 +00002975
Sanjoy Dasf8570812016-05-29 00:38:22 +00002976/// Get an add recurrence expression for the specified loop. Simplify the
2977/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002978const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2979 const Loop *L,
2980 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002981 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002982 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002983 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002984 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002985 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002986 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002987 }
2988
2989 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002990 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002991}
2992
Sanjoy Dasf8570812016-05-29 00:38:22 +00002993/// Get an add recurrence expression for the specified loop. Simplify the
2994/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002995const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002996ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002997 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002998 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002999#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003000 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003001 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003002 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003003 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003004 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00003005 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00003006 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00003007#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00003008
Dan Gohmanbe928e32008-06-18 16:23:07 +00003009 if (Operands.back()->isZero()) {
3010 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00003011 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00003012 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003013
Dan Gohmancf9c64e2010-02-19 18:49:22 +00003014 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3015 // use that information to infer NUW and NSW flags. However, computing a
3016 // BE count requires calling getAddRecExpr, so we may not yet have a
3017 // meaningful BE count at this point (and if we don't, we'd be stuck
3018 // with a SCEVCouldNotCompute as the cached BE count).
3019
Sanjoy Das81401d42015-01-10 23:41:24 +00003020 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003021
Dan Gohman223a5d22008-08-08 18:33:12 +00003022 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00003023 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00003024 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003025 if (L->contains(NestedLoop)
3026 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3027 : (!NestedLoop->contains(L) &&
3028 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003029 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00003030 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00003031 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00003032 // AddRecs require their operands be loop-invariant with respect to their
3033 // loops. Don't perform this transformation if it would break this
3034 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00003035 bool AllInvariant = all_of(
3036 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003037
Dan Gohmancc030b72009-06-26 22:36:20 +00003038 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003039 // Create a recurrence for the outer loop with the same step size.
3040 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003041 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3042 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003043 SCEV::NoWrapFlags OuterFlags =
3044 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003045
3046 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003047 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3048 return isLoopInvariant(Op, NestedLoop);
3049 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003050
Andrew Trick8b55b732011-03-14 16:50:06 +00003051 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003052 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003053 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003054 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3055 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003056 SCEV::NoWrapFlags InnerFlags =
3057 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003058 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3059 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003060 }
3061 // Reset Operands to its original state.
3062 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003063 }
3064 }
3065
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003066 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3067 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003068 FoldingSetNodeID ID;
3069 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003070 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3071 ID.AddPointer(Operands[i]);
3072 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003073 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003074 SCEVAddRecExpr *S =
3075 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3076 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003077 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3078 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003079 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3080 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003081 UniqueSCEVs.InsertNode(S, IP);
3082 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003083 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003084 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003085}
3086
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003087const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003088ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3089 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3090 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003091 // getSCEV(Base)->getType() has the same address space as Base->getType()
3092 // because SCEV::getType() preserves the address space.
3093 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3094 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3095 // instruction to its SCEV, because the Instruction may be guarded by control
3096 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003097 // context. This can be fixed similarly to how these flags are handled for
3098 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003099 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3100 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003101
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003102 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003103 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003104 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003105 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003106 for (const SCEV *IndexExpr : IndexExprs) {
3107 // Compute the (potentially symbolic) offset in bytes for this index.
3108 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3109 // For a struct, add the member offset.
3110 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3111 unsigned FieldNo = Index->getZExtValue();
3112 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3113
3114 // Add the field offset to the running total offset.
3115 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3116
3117 // Update CurTy to the type of the field at Index.
3118 CurTy = STy->getTypeAtIndex(Index);
3119 } else {
3120 // Update CurTy to its element type.
3121 CurTy = cast<SequentialType>(CurTy)->getElementType();
3122 // For an array, add the element offset, explicitly scaled.
3123 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3124 // Getelementptr indices are signed.
3125 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3126
3127 // Multiply the index by the element size to compute the element offset.
3128 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3129
3130 // Add the element offset to the running total offset.
3131 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3132 }
3133 }
3134
3135 // Add the total offset from all the GEP indices to the base.
3136 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3137}
3138
Dan Gohmanabd17092009-06-24 14:49:00 +00003139const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3140 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003141 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003142 return getSMaxExpr(Ops);
3143}
3144
Dan Gohmanaf752342009-07-07 17:06:11 +00003145const SCEV *
3146ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003147 assert(!Ops.empty() && "Cannot get empty smax!");
3148 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003149#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003150 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003151 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003152 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003153 "SCEVSMaxExpr operand types don't match!");
3154#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003155
3156 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003157 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003158
3159 // If there are any constants, fold them together.
3160 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003161 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003162 ++Idx;
3163 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003164 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003165 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003166 ConstantInt *Fold = ConstantInt::get(
3167 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003168 Ops[0] = getConstant(Fold);
3169 Ops.erase(Ops.begin()+1); // Erase the folded element
3170 if (Ops.size() == 1) return Ops[0];
3171 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003172 }
3173
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003174 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003175 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3176 Ops.erase(Ops.begin());
3177 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003178 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3179 // If we have an smax with a constant maximum-int, it will always be
3180 // maximum-int.
3181 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003182 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003183
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003184 if (Ops.size() == 1) return Ops[0];
3185 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003186
3187 // Find the first SMax
3188 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3189 ++Idx;
3190
3191 // Check to see if one of the operands is an SMax. If so, expand its operands
3192 // onto our operand list, and recurse to simplify.
3193 if (Idx < Ops.size()) {
3194 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003195 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003196 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003197 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003198 DeletedSMax = true;
3199 }
3200
3201 if (DeletedSMax)
3202 return getSMaxExpr(Ops);
3203 }
3204
3205 // Okay, check to see if the same value occurs in the operand list twice. If
3206 // so, delete one. Since we sorted the list, these values are required to
3207 // be adjacent.
3208 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003209 // X smax Y smax Y --> X smax Y
3210 // X smax Y --> X, if X is always greater than Y
3211 if (Ops[i] == Ops[i+1] ||
3212 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3213 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3214 --i; --e;
3215 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003216 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3217 --i; --e;
3218 }
3219
3220 if (Ops.size() == 1) return Ops[0];
3221
3222 assert(!Ops.empty() && "Reduced smax down to nothing!");
3223
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003224 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003225 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003226 FoldingSetNodeID ID;
3227 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003228 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3229 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003230 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003231 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003232 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3233 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003234 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3235 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003236 UniqueSCEVs.InsertNode(S, IP);
3237 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003238}
3239
Dan Gohmanabd17092009-06-24 14:49:00 +00003240const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3241 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003242 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003243 return getUMaxExpr(Ops);
3244}
3245
Dan Gohmanaf752342009-07-07 17:06:11 +00003246const SCEV *
3247ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003248 assert(!Ops.empty() && "Cannot get empty umax!");
3249 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003250#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003251 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003252 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003253 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003254 "SCEVUMaxExpr operand types don't match!");
3255#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003256
3257 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003258 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003259
3260 // If there are any constants, fold them together.
3261 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003262 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003263 ++Idx;
3264 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003265 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003266 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003267 ConstantInt *Fold = ConstantInt::get(
3268 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003269 Ops[0] = getConstant(Fold);
3270 Ops.erase(Ops.begin()+1); // Erase the folded element
3271 if (Ops.size() == 1) return Ops[0];
3272 LHSC = cast<SCEVConstant>(Ops[0]);
3273 }
3274
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003275 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003276 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3277 Ops.erase(Ops.begin());
3278 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003279 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3280 // If we have an umax with a constant maximum-int, it will always be
3281 // maximum-int.
3282 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003283 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003284
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003285 if (Ops.size() == 1) return Ops[0];
3286 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003287
3288 // Find the first UMax
3289 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3290 ++Idx;
3291
3292 // Check to see if one of the operands is a UMax. If so, expand its operands
3293 // onto our operand list, and recurse to simplify.
3294 if (Idx < Ops.size()) {
3295 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003296 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003297 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003298 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003299 DeletedUMax = true;
3300 }
3301
3302 if (DeletedUMax)
3303 return getUMaxExpr(Ops);
3304 }
3305
3306 // Okay, check to see if the same value occurs in the operand list twice. If
3307 // so, delete one. Since we sorted the list, these values are required to
3308 // be adjacent.
3309 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003310 // X umax Y umax Y --> X umax Y
3311 // X umax Y --> X, if X is always greater than Y
3312 if (Ops[i] == Ops[i+1] ||
3313 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3314 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3315 --i; --e;
3316 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003317 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3318 --i; --e;
3319 }
3320
3321 if (Ops.size() == 1) return Ops[0];
3322
3323 assert(!Ops.empty() && "Reduced umax down to nothing!");
3324
3325 // Okay, it looks like we really DO need a umax expr. Check to see if we
3326 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003327 FoldingSetNodeID ID;
3328 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003329 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3330 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003331 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003332 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003333 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3334 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003335 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3336 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003337 UniqueSCEVs.InsertNode(S, IP);
3338 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003339}
3340
Dan Gohmanabd17092009-06-24 14:49:00 +00003341const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3342 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003343 // ~smax(~x, ~y) == smin(x, y).
3344 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3345}
3346
Dan Gohmanabd17092009-06-24 14:49:00 +00003347const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3348 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003349 // ~umax(~x, ~y) == umin(x, y)
3350 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3351}
3352
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003353const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003354 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003355 // constant expression and then folding it back into a ConstantInt.
3356 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003357 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003358}
3359
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003360const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3361 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003362 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003363 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003364 // constant expression and then folding it back into a ConstantInt.
3365 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003366 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003367 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003368}
3369
Dan Gohmanaf752342009-07-07 17:06:11 +00003370const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003371 // Don't attempt to do anything other than create a SCEVUnknown object
3372 // here. createSCEV only calls getUnknown after checking for all other
3373 // interesting possibilities, and any other code that calls getUnknown
3374 // is doing so in order to hide a value from SCEV canonicalization.
3375
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003376 FoldingSetNodeID ID;
3377 ID.AddInteger(scUnknown);
3378 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003379 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003380 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3381 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3382 "Stale SCEVUnknown in uniquing map!");
3383 return S;
3384 }
3385 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3386 FirstUnknown);
3387 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003388 UniqueSCEVs.InsertNode(S, IP);
3389 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003390}
3391
Chris Lattnerd934c702004-04-02 20:23:17 +00003392//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003393// Basic SCEV Analysis and PHI Idiom Recognition Code
3394//
3395
Sanjoy Dasf8570812016-05-29 00:38:22 +00003396/// Test if values of the given type are analyzable within the SCEV
3397/// framework. This primarily includes integer types, and it can optionally
3398/// include pointer types if the ScalarEvolution class has access to
3399/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003400bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003401 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003402 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003403}
3404
Sanjoy Dasf8570812016-05-29 00:38:22 +00003405/// Return the size in bits of the specified type, for which isSCEVable must
3406/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003407uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003408 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003409 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003410}
3411
Sanjoy Dasf8570812016-05-29 00:38:22 +00003412/// Return a type with the same bitwidth as the given type and which represents
3413/// how SCEV will treat the given type, for which isSCEVable must return
3414/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003415Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003416 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3417
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003418 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003419 return Ty;
3420
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003421 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003422 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003423 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003424}
Chris Lattnerd934c702004-04-02 20:23:17 +00003425
Max Kazantsev2e44d292017-03-31 12:05:30 +00003426Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3427 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3428}
3429
Dan Gohmanaf752342009-07-07 17:06:11 +00003430const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003431 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003432}
3433
Sanjoy Das7d752672015-12-08 04:32:54 +00003434bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003435 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3436 auto *SU = dyn_cast<SCEVUnknown>(S);
3437 return SU && SU->getValue() == nullptr;
3438 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003439
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003440 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003441}
3442
Wei Mia49559b2016-02-04 01:27:38 +00003443bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003444 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003445 if (I != HasRecMap.end())
3446 return I->second;
3447
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003448 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003449 HasRecMap.insert({S, FoundAddRec});
3450 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003451}
3452
Wei Mi785858c2016-08-09 20:37:50 +00003453/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3454/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3455/// offset I, then return {S', I}, else return {\p S, nullptr}.
3456static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3457 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3458 if (!Add)
3459 return {S, nullptr};
3460
3461 if (Add->getNumOperands() != 2)
3462 return {S, nullptr};
3463
3464 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3465 if (!ConstOp)
3466 return {S, nullptr};
3467
3468 return {Add->getOperand(1), ConstOp->getValue()};
3469}
3470
3471/// Return the ValueOffsetPair set for \p S. \p S can be represented
3472/// by the value and offset from any ValueOffsetPair in the set.
3473SetVector<ScalarEvolution::ValueOffsetPair> *
3474ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003475 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3476 if (SI == ExprValueMap.end())
3477 return nullptr;
3478#ifndef NDEBUG
3479 if (VerifySCEVMap) {
3480 // Check there is no dangling Value in the set returned.
3481 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003482 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003483 }
3484#endif
3485 return &SI->second;
3486}
3487
Wei Mi785858c2016-08-09 20:37:50 +00003488/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3489/// cannot be used separately. eraseValueFromMap should be used to remove
3490/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003491void ScalarEvolution::eraseValueFromMap(Value *V) {
3492 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3493 if (I != ValueExprMap.end()) {
3494 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003495 // Remove {V, 0} from the set of ExprValueMap[S]
3496 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3497 SV->remove({V, nullptr});
3498
3499 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3500 const SCEV *Stripped;
3501 ConstantInt *Offset;
3502 std::tie(Stripped, Offset) = splitAddExpr(S);
3503 if (Offset != nullptr) {
3504 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3505 SV->remove({V, Offset});
3506 }
Wei Mia49559b2016-02-04 01:27:38 +00003507 ValueExprMap.erase(V);
3508 }
3509}
3510
Sanjoy Dasf8570812016-05-29 00:38:22 +00003511/// Return an existing SCEV if it exists, otherwise analyze the expression and
3512/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003513const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003514 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003515
Jingyue Wu42f1d672015-07-28 18:22:40 +00003516 const SCEV *S = getExistingSCEV(V);
3517 if (S == nullptr) {
3518 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003519 // During PHI resolution, it is possible to create two SCEVs for the same
3520 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003521 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003522 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003523 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003524 if (Pair.second) {
3525 ExprValueMap[S].insert({V, nullptr});
3526
3527 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3528 // ExprValueMap.
3529 const SCEV *Stripped = S;
3530 ConstantInt *Offset = nullptr;
3531 std::tie(Stripped, Offset) = splitAddExpr(S);
3532 // If stripped is SCEVUnknown, don't bother to save
3533 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3534 // increase the complexity of the expansion code.
3535 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3536 // because it may generate add/sub instead of GEP in SCEV expansion.
3537 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3538 !isa<GetElementPtrInst>(V))
3539 ExprValueMap[Stripped].insert({V, Offset});
3540 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003541 }
3542 return S;
3543}
3544
3545const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3546 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3547
Shuxin Yangefc4c012013-07-08 17:33:13 +00003548 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3549 if (I != ValueExprMap.end()) {
3550 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003551 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003552 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003553 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003554 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003555 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003556 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003557}
3558
Sanjoy Dasf8570812016-05-29 00:38:22 +00003559/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003560///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003561const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3562 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003563 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003564 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003565 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003566
Chris Lattner229907c2011-07-18 04:54:35 +00003567 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003568 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003569 return getMulExpr(
3570 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003571}
3572
Sanjoy Dasf8570812016-05-29 00:38:22 +00003573/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003574const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003575 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003576 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003577 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003578
Chris Lattner229907c2011-07-18 04:54:35 +00003579 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003580 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003581 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003582 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003583 return getMinusSCEV(AllOnes, V);
3584}
3585
Chris Lattnerfc877522011-01-09 22:26:35 +00003586const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003587 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003588 // Fast path: X - X --> 0.
3589 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003590 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003591
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003592 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3593 // makes it so that we cannot make much use of NUW.
3594 auto AddFlags = SCEV::FlagAnyWrap;
3595 const bool RHSIsNotMinSigned =
3596 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3597 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3598 // Let M be the minimum representable signed value. Then (-1)*RHS
3599 // signed-wraps if and only if RHS is M. That can happen even for
3600 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3601 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3602 // (-1)*RHS, we need to prove that RHS != M.
3603 //
3604 // If LHS is non-negative and we know that LHS - RHS does not
3605 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3606 // either by proving that RHS > M or that LHS >= 0.
3607 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3608 AddFlags = SCEV::FlagNSW;
3609 }
3610 }
3611
3612 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3613 // RHS is NSW and LHS >= 0.
3614 //
3615 // The difficulty here is that the NSW flag may have been proven
3616 // relative to a loop that is to be found in a recurrence in LHS and
3617 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3618 // larger scope than intended.
3619 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3620
3621 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003622}
3623
Dan Gohmanaf752342009-07-07 17:06:11 +00003624const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003625ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3626 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003627 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3628 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003629 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003630 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003631 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003632 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003633 return getTruncateExpr(V, Ty);
3634 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003635}
3636
Dan Gohmanaf752342009-07-07 17:06:11 +00003637const SCEV *
3638ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003639 Type *Ty) {
3640 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003641 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3642 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003643 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003644 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003645 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003646 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003647 return getTruncateExpr(V, Ty);
3648 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003649}
3650
Dan Gohmanaf752342009-07-07 17:06:11 +00003651const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003652ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3653 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003654 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3655 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003656 "Cannot noop or zero extend with non-integer arguments!");
3657 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3658 "getNoopOrZeroExtend cannot truncate!");
3659 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3660 return V; // No conversion
3661 return getZeroExtendExpr(V, Ty);
3662}
3663
Dan Gohmanaf752342009-07-07 17:06:11 +00003664const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003665ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3666 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003667 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3668 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003669 "Cannot noop or sign extend with non-integer arguments!");
3670 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3671 "getNoopOrSignExtend cannot truncate!");
3672 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3673 return V; // No conversion
3674 return getSignExtendExpr(V, Ty);
3675}
3676
Dan Gohmanaf752342009-07-07 17:06:11 +00003677const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003678ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3679 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003680 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3681 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003682 "Cannot noop or any extend with non-integer arguments!");
3683 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3684 "getNoopOrAnyExtend cannot truncate!");
3685 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3686 return V; // No conversion
3687 return getAnyExtendExpr(V, Ty);
3688}
3689
Dan Gohmanaf752342009-07-07 17:06:11 +00003690const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003691ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3692 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003693 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3694 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003695 "Cannot truncate or noop with non-integer arguments!");
3696 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3697 "getTruncateOrNoop cannot extend!");
3698 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3699 return V; // No conversion
3700 return getTruncateExpr(V, Ty);
3701}
3702
Dan Gohmanabd17092009-06-24 14:49:00 +00003703const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3704 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003705 const SCEV *PromotedLHS = LHS;
3706 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003707
3708 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3709 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3710 else
3711 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3712
3713 return getUMaxExpr(PromotedLHS, PromotedRHS);
3714}
3715
Dan Gohmanabd17092009-06-24 14:49:00 +00003716const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3717 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003718 const SCEV *PromotedLHS = LHS;
3719 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003720
3721 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3722 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3723 else
3724 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3725
3726 return getUMinExpr(PromotedLHS, PromotedRHS);
3727}
3728
Andrew Trick87716c92011-03-17 23:51:11 +00003729const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3730 // A pointer operand may evaluate to a nonpointer expression, such as null.
3731 if (!V->getType()->isPointerTy())
3732 return V;
3733
3734 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3735 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003736 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003737 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003738 for (const SCEV *NAryOp : NAry->operands()) {
3739 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003740 // Cannot find the base of an expression with multiple pointer operands.
3741 if (PtrOp)
3742 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003743 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003744 }
3745 }
3746 if (!PtrOp)
3747 return V;
3748 return getPointerBase(PtrOp);
3749 }
3750 return V;
3751}
3752
Sanjoy Dasf8570812016-05-29 00:38:22 +00003753/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003754static void
3755PushDefUseChildren(Instruction *I,
3756 SmallVectorImpl<Instruction *> &Worklist) {
3757 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003758 for (User *U : I->users())
3759 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003760}
3761
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003762void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003763 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003764 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003765
Dan Gohman0b89dff2009-07-25 01:13:03 +00003766 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003767 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003768 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003769 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003770 if (!Visited.insert(I).second)
3771 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003772
Sanjoy Das63914592015-10-18 00:29:20 +00003773 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003774 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003775 const SCEV *Old = It->second;
3776
Dan Gohman0b89dff2009-07-25 01:13:03 +00003777 // Short-circuit the def-use traversal if the symbolic name
3778 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003779 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003780 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003781
Dan Gohman0b89dff2009-07-25 01:13:03 +00003782 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003783 // structure, it's a PHI that's in the progress of being computed
3784 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3785 // additional loop trip count information isn't going to change anything.
3786 // In the second case, createNodeForPHI will perform the necessary
3787 // updates on its own when it gets to that point. In the third, we do
3788 // want to forget the SCEVUnknown.
3789 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003790 !isa<SCEVUnknown>(Old) ||
3791 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003792 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003793 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003794 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003795 }
3796
3797 PushDefUseChildren(I, Worklist);
3798 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003799}
Chris Lattnerd934c702004-04-02 20:23:17 +00003800
Benjamin Kramer83709b12015-11-16 09:01:28 +00003801namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003802class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3803public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003804 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003805 ScalarEvolution &SE) {
3806 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003807 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003808 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3809 }
3810
3811 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3812 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3813
3814 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3815 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3816 Valid = false;
3817 return Expr;
3818 }
3819
3820 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3821 // Only allow AddRecExprs for this loop.
3822 if (Expr->getLoop() == L)
3823 return Expr->getStart();
3824 Valid = false;
3825 return Expr;
3826 }
3827
3828 bool isValid() { return Valid; }
3829
3830private:
3831 const Loop *L;
3832 bool Valid;
3833};
3834
3835class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3836public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003837 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003838 ScalarEvolution &SE) {
3839 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003840 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003841 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3842 }
3843
3844 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3845 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3846
3847 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3848 // Only allow AddRecExprs for this loop.
3849 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3850 Valid = false;
3851 return Expr;
3852 }
3853
3854 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3855 if (Expr->getLoop() == L && Expr->isAffine())
3856 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3857 Valid = false;
3858 return Expr;
3859 }
3860 bool isValid() { return Valid; }
3861
3862private:
3863 const Loop *L;
3864 bool Valid;
3865};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003866} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003867
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003868SCEV::NoWrapFlags
3869ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3870 if (!AR->isAffine())
3871 return SCEV::FlagAnyWrap;
3872
3873 typedef OverflowingBinaryOperator OBO;
3874 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3875
3876 if (!AR->hasNoSignedWrap()) {
3877 ConstantRange AddRecRange = getSignedRange(AR);
3878 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3879
3880 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3881 Instruction::Add, IncRange, OBO::NoSignedWrap);
3882 if (NSWRegion.contains(AddRecRange))
3883 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3884 }
3885
3886 if (!AR->hasNoUnsignedWrap()) {
3887 ConstantRange AddRecRange = getUnsignedRange(AR);
3888 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3889
3890 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3891 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3892 if (NUWRegion.contains(AddRecRange))
3893 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3894 }
3895
3896 return Result;
3897}
3898
Sanjoy Das118d9192016-03-31 05:14:22 +00003899namespace {
3900/// Represents an abstract binary operation. This may exist as a
3901/// normal instruction or constant expression, or may have been
3902/// derived from an expression tree.
3903struct BinaryOp {
3904 unsigned Opcode;
3905 Value *LHS;
3906 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003907 bool IsNSW;
3908 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003909
3910 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3911 /// constant expression.
3912 Operator *Op;
3913
3914 explicit BinaryOp(Operator *Op)
3915 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003916 IsNSW(false), IsNUW(false), Op(Op) {
3917 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3918 IsNSW = OBO->hasNoSignedWrap();
3919 IsNUW = OBO->hasNoUnsignedWrap();
3920 }
3921 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003922
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003923 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3924 bool IsNUW = false)
3925 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3926 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003927};
3928}
3929
3930
3931/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003932static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003933 auto *Op = dyn_cast<Operator>(V);
3934 if (!Op)
3935 return None;
3936
3937 // Implementation detail: all the cleverness here should happen without
3938 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3939 // SCEV expressions when possible, and we should not break that.
3940
3941 switch (Op->getOpcode()) {
3942 case Instruction::Add:
3943 case Instruction::Sub:
3944 case Instruction::Mul:
3945 case Instruction::UDiv:
3946 case Instruction::And:
3947 case Instruction::Or:
3948 case Instruction::AShr:
3949 case Instruction::Shl:
3950 return BinaryOp(Op);
3951
3952 case Instruction::Xor:
3953 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3954 // If the RHS of the xor is a signbit, then this is just an add.
3955 // Instcombine turns add of signbit into xor as a strength reduction step.
3956 if (RHSC->getValue().isSignBit())
3957 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3958 return BinaryOp(Op);
3959
3960 case Instruction::LShr:
3961 // Turn logical shift right of a constant into a unsigned divide.
3962 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3963 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3964
3965 // If the shift count is not less than the bitwidth, the result of
3966 // the shift is undefined. Don't try to analyze it, because the
3967 // resolution chosen here may differ from the resolution chosen in
3968 // other parts of the compiler.
3969 if (SA->getValue().ult(BitWidth)) {
3970 Constant *X =
3971 ConstantInt::get(SA->getContext(),
3972 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3973 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3974 }
3975 }
3976 return BinaryOp(Op);
3977
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003978 case Instruction::ExtractValue: {
3979 auto *EVI = cast<ExtractValueInst>(Op);
3980 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3981 break;
3982
3983 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3984 if (!CI)
3985 break;
3986
3987 if (auto *F = CI->getCalledFunction())
3988 switch (F->getIntrinsicID()) {
3989 case Intrinsic::sadd_with_overflow:
3990 case Intrinsic::uadd_with_overflow: {
3991 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3992 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3993 CI->getArgOperand(1));
3994
3995 // Now that we know that all uses of the arithmetic-result component of
3996 // CI are guarded by the overflow check, we can go ahead and pretend
3997 // that the arithmetic is non-overflowing.
3998 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3999 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4000 CI->getArgOperand(1), /* IsNSW = */ true,
4001 /* IsNUW = */ false);
4002 else
4003 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4004 CI->getArgOperand(1), /* IsNSW = */ false,
4005 /* IsNUW*/ true);
4006 }
4007
4008 case Intrinsic::ssub_with_overflow:
4009 case Intrinsic::usub_with_overflow:
4010 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4011 CI->getArgOperand(1));
4012
4013 case Intrinsic::smul_with_overflow:
4014 case Intrinsic::umul_with_overflow:
4015 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4016 CI->getArgOperand(1));
4017 default:
4018 break;
4019 }
4020 }
4021
Sanjoy Das118d9192016-03-31 05:14:22 +00004022 default:
4023 break;
4024 }
4025
4026 return None;
4027}
4028
Sanjoy Das55015d22015-10-02 23:09:44 +00004029const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4030 const Loop *L = LI.getLoopFor(PN->getParent());
4031 if (!L || L->getHeader() != PN->getParent())
4032 return nullptr;
4033
4034 // The loop may have multiple entrances or multiple exits; we can analyze
4035 // this phi as an addrec if it has a unique entry value and a unique
4036 // backedge value.
4037 Value *BEValueV = nullptr, *StartValueV = nullptr;
4038 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4039 Value *V = PN->getIncomingValue(i);
4040 if (L->contains(PN->getIncomingBlock(i))) {
4041 if (!BEValueV) {
4042 BEValueV = V;
4043 } else if (BEValueV != V) {
4044 BEValueV = nullptr;
4045 break;
4046 }
4047 } else if (!StartValueV) {
4048 StartValueV = V;
4049 } else if (StartValueV != V) {
4050 StartValueV = nullptr;
4051 break;
4052 }
4053 }
4054 if (BEValueV && StartValueV) {
4055 // While we are analyzing this PHI node, handle its value symbolically.
4056 const SCEV *SymbolicName = getUnknown(PN);
4057 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4058 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00004059 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004060
4061 // Using this symbolic name for the PHI, analyze the value coming around
4062 // the back-edge.
4063 const SCEV *BEValue = getSCEV(BEValueV);
4064
4065 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4066 // has a special value for the first iteration of the loop.
4067
4068 // If the value coming around the backedge is an add with the symbolic
4069 // value we just inserted, then we found a simple induction variable!
4070 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4071 // If there is a single occurrence of the symbolic value, replace it
4072 // with a recurrence.
4073 unsigned FoundIndex = Add->getNumOperands();
4074 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4075 if (Add->getOperand(i) == SymbolicName)
4076 if (FoundIndex == e) {
4077 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004078 break;
4079 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004080
4081 if (FoundIndex != Add->getNumOperands()) {
4082 // Create an add with everything but the specified operand.
4083 SmallVector<const SCEV *, 8> Ops;
4084 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4085 if (i != FoundIndex)
4086 Ops.push_back(Add->getOperand(i));
4087 const SCEV *Accum = getAddExpr(Ops);
4088
4089 // This is not a valid addrec if the step amount is varying each
4090 // loop iteration, but is not itself an addrec in this loop.
4091 if (isLoopInvariant(Accum, L) ||
4092 (isa<SCEVAddRecExpr>(Accum) &&
4093 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4094 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4095
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004096 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004097 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4098 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004099 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004100 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004101 Flags = setFlags(Flags, SCEV::FlagNSW);
4102 }
4103 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4104 // If the increment is an inbounds GEP, then we know the address
4105 // space cannot be wrapped around. We cannot make any guarantee
4106 // about signed or unsigned overflow because pointers are
4107 // unsigned but we may have a negative index from the base
4108 // pointer. We can guarantee that no unsigned wrap occurs if the
4109 // indices form a positive value.
4110 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4111 Flags = setFlags(Flags, SCEV::FlagNW);
4112
4113 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4114 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4115 Flags = setFlags(Flags, SCEV::FlagNUW);
4116 }
4117
4118 // We cannot transfer nuw and nsw flags from subtraction
4119 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4120 // for instance.
4121 }
4122
4123 const SCEV *StartVal = getSCEV(StartValueV);
4124 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4125
Sanjoy Das55015d22015-10-02 23:09:44 +00004126 // Okay, for the entire analysis of this edge we assumed the PHI
4127 // to be symbolic. We now need to go back and purge all of the
4128 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004129 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004130 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004131
4132 // We can add Flags to the post-inc expression only if we
4133 // know that it us *undefined behavior* for BEValueV to
4134 // overflow.
4135 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4136 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4137 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4138
Sanjoy Das55015d22015-10-02 23:09:44 +00004139 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004140 }
4141 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004142 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004143 // Otherwise, this could be a loop like this:
4144 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4145 // In this case, j = {1,+,1} and BEValue is j.
4146 // Because the other in-value of i (0) fits the evolution of BEValue
4147 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004148 //
4149 // We can generalize this saying that i is the shifted value of BEValue
4150 // by one iteration:
4151 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4152 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4153 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4154 if (Shifted != getCouldNotCompute() &&
4155 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004156 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004157 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004158 // Okay, for the entire analysis of this edge we assumed the PHI
4159 // to be symbolic. We now need to go back and purge all of the
4160 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004161 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004162 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4163 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004164 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004165 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004166 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004167
4168 // Remove the temporary PHI node SCEV that has been inserted while intending
4169 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4170 // as it will prevent later (possibly simpler) SCEV expressions to be added
4171 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004172 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004173 }
4174
4175 return nullptr;
4176}
4177
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004178// Checks if the SCEV S is available at BB. S is considered available at BB
4179// if S can be materialized at BB without introducing a fault.
4180static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4181 BasicBlock *BB) {
4182 struct CheckAvailable {
4183 bool TraversalDone = false;
4184 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004185
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004186 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4187 BasicBlock *BB = nullptr;
4188 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004189
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004190 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4191 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004192
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004193 bool setUnavailable() {
4194 TraversalDone = true;
4195 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004196 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004197 }
4198
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004199 bool follow(const SCEV *S) {
4200 switch (S->getSCEVType()) {
4201 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4202 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004203 // These expressions are available if their operand(s) is/are.
4204 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004205
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004206 case scAddRecExpr: {
4207 // We allow add recurrences that are on the loop BB is in, or some
4208 // outer loop. This guarantees availability because the value of the
4209 // add recurrence at BB is simply the "current" value of the induction
4210 // variable. We can relax this in the future; for instance an add
4211 // recurrence on a sibling dominating loop is also available at BB.
4212 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4213 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004214 return true;
4215
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004216 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004217 }
4218
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004219 case scUnknown: {
4220 // For SCEVUnknown, we check for simple dominance.
4221 const auto *SU = cast<SCEVUnknown>(S);
4222 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004223
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004224 if (isa<Argument>(V))
4225 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004226
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004227 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4228 return false;
4229
4230 return setUnavailable();
4231 }
4232
4233 case scUDivExpr:
4234 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004235 // We do not try to smart about these at all.
4236 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004237 }
4238 llvm_unreachable("switch should be fully covered!");
4239 }
4240
4241 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004242 };
4243
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004244 CheckAvailable CA(L, BB, DT);
4245 SCEVTraversal<CheckAvailable> ST(CA);
4246
4247 ST.visitAll(S);
4248 return CA.Available;
4249}
4250
4251// Try to match a control flow sequence that branches out at BI and merges back
4252// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4253// match.
4254static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4255 Value *&C, Value *&LHS, Value *&RHS) {
4256 C = BI->getCondition();
4257
4258 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4259 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4260
4261 if (!LeftEdge.isSingleEdge())
4262 return false;
4263
4264 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4265
4266 Use &LeftUse = Merge->getOperandUse(0);
4267 Use &RightUse = Merge->getOperandUse(1);
4268
4269 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4270 LHS = LeftUse;
4271 RHS = RightUse;
4272 return true;
4273 }
4274
4275 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4276 LHS = RightUse;
4277 RHS = LeftUse;
4278 return true;
4279 }
4280
4281 return false;
4282}
4283
4284const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004285 auto IsReachable =
4286 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4287 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004288 const Loop *L = LI.getLoopFor(PN->getParent());
4289
Sanjoy Das337d4782015-10-31 23:21:40 +00004290 // We don't want to break LCSSA, even in a SCEV expression tree.
4291 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4292 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4293 return nullptr;
4294
Sanjoy Das55015d22015-10-02 23:09:44 +00004295 // Try to match
4296 //
4297 // br %cond, label %left, label %right
4298 // left:
4299 // br label %merge
4300 // right:
4301 // br label %merge
4302 // merge:
4303 // V = phi [ %x, %left ], [ %y, %right ]
4304 //
4305 // as "select %cond, %x, %y"
4306
4307 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4308 assert(IDom && "At least the entry block should dominate PN");
4309
4310 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4311 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4312
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004313 if (BI && BI->isConditional() &&
4314 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4315 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4316 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004317 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4318 }
4319
4320 return nullptr;
4321}
4322
4323const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4324 if (const SCEV *S = createAddRecFromPHI(PN))
4325 return S;
4326
4327 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4328 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004329
Dan Gohmana9c205c2010-02-25 06:57:05 +00004330 // If the PHI has a single incoming value, follow that value, unless the
4331 // PHI's incoming blocks are in a different loop, in which case doing so
4332 // risks breaking LCSSA form. Instcombine would normally zap these, but
4333 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004334 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004335 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004336 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004337
Chris Lattnerd934c702004-04-02 20:23:17 +00004338 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004339 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004340}
4341
Sanjoy Das55015d22015-10-02 23:09:44 +00004342const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4343 Value *Cond,
4344 Value *TrueVal,
4345 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004346 // Handle "constant" branch or select. This can occur for instance when a
4347 // loop pass transforms an inner loop and moves on to process the outer loop.
4348 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4349 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4350
Sanjoy Dasd0671342015-10-02 19:39:59 +00004351 // Try to match some simple smax or umax patterns.
4352 auto *ICI = dyn_cast<ICmpInst>(Cond);
4353 if (!ICI)
4354 return getUnknown(I);
4355
4356 Value *LHS = ICI->getOperand(0);
4357 Value *RHS = ICI->getOperand(1);
4358
4359 switch (ICI->getPredicate()) {
4360 case ICmpInst::ICMP_SLT:
4361 case ICmpInst::ICMP_SLE:
4362 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004363 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004364 case ICmpInst::ICMP_SGT:
4365 case ICmpInst::ICMP_SGE:
4366 // a >s b ? a+x : b+x -> smax(a, b)+x
4367 // a >s b ? b+x : a+x -> smin(a, b)+x
4368 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4369 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4370 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4371 const SCEV *LA = getSCEV(TrueVal);
4372 const SCEV *RA = getSCEV(FalseVal);
4373 const SCEV *LDiff = getMinusSCEV(LA, LS);
4374 const SCEV *RDiff = getMinusSCEV(RA, RS);
4375 if (LDiff == RDiff)
4376 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4377 LDiff = getMinusSCEV(LA, RS);
4378 RDiff = getMinusSCEV(RA, LS);
4379 if (LDiff == RDiff)
4380 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4381 }
4382 break;
4383 case ICmpInst::ICMP_ULT:
4384 case ICmpInst::ICMP_ULE:
4385 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004386 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004387 case ICmpInst::ICMP_UGT:
4388 case ICmpInst::ICMP_UGE:
4389 // a >u b ? a+x : b+x -> umax(a, b)+x
4390 // a >u b ? b+x : a+x -> umin(a, b)+x
4391 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4392 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4393 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4394 const SCEV *LA = getSCEV(TrueVal);
4395 const SCEV *RA = getSCEV(FalseVal);
4396 const SCEV *LDiff = getMinusSCEV(LA, LS);
4397 const SCEV *RDiff = getMinusSCEV(RA, RS);
4398 if (LDiff == RDiff)
4399 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4400 LDiff = getMinusSCEV(LA, RS);
4401 RDiff = getMinusSCEV(RA, LS);
4402 if (LDiff == RDiff)
4403 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4404 }
4405 break;
4406 case ICmpInst::ICMP_NE:
4407 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4408 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4409 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4410 const SCEV *One = getOne(I->getType());
4411 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4412 const SCEV *LA = getSCEV(TrueVal);
4413 const SCEV *RA = getSCEV(FalseVal);
4414 const SCEV *LDiff = getMinusSCEV(LA, LS);
4415 const SCEV *RDiff = getMinusSCEV(RA, One);
4416 if (LDiff == RDiff)
4417 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4418 }
4419 break;
4420 case ICmpInst::ICMP_EQ:
4421 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4422 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4423 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4424 const SCEV *One = getOne(I->getType());
4425 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4426 const SCEV *LA = getSCEV(TrueVal);
4427 const SCEV *RA = getSCEV(FalseVal);
4428 const SCEV *LDiff = getMinusSCEV(LA, One);
4429 const SCEV *RDiff = getMinusSCEV(RA, LS);
4430 if (LDiff == RDiff)
4431 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4432 }
4433 break;
4434 default:
4435 break;
4436 }
4437
4438 return getUnknown(I);
4439}
4440
Sanjoy Dasf8570812016-05-29 00:38:22 +00004441/// Expand GEP instructions into add and multiply operations. This allows them
4442/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004443const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004444 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004445 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004446 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004447
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004448 SmallVector<const SCEV *, 4> IndexExprs;
4449 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4450 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004451 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004452}
4453
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004454uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004455 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004456 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004457
Dan Gohmana30370b2009-05-04 22:02:23 +00004458 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004459 return std::min(GetMinTrailingZeros(T->getOperand()),
4460 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004461
Dan Gohmana30370b2009-05-04 22:02:23 +00004462 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004463 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004464 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4465 ? getTypeSizeInBits(E->getType())
4466 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004467 }
4468
Dan Gohmana30370b2009-05-04 22:02:23 +00004469 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004470 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004471 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4472 ? getTypeSizeInBits(E->getType())
4473 : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004474 }
4475
Dan Gohmana30370b2009-05-04 22:02:23 +00004476 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004477 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004478 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004479 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004480 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004481 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004482 }
4483
Dan Gohmana30370b2009-05-04 22:02:23 +00004484 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004485 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004486 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4487 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004488 for (unsigned i = 1, e = M->getNumOperands();
4489 SumOpRes != BitWidth && i != e; ++i)
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004490 SumOpRes =
4491 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
Nick Lewycky3783b462007-11-22 07:59:40 +00004492 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004493 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004494
Dan Gohmana30370b2009-05-04 22:02:23 +00004495 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004496 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004497 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004498 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004500 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004501 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004502
Dan Gohmana30370b2009-05-04 22:02:23 +00004503 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004504 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004505 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004506 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004507 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004508 return MinOpRes;
4509 }
4510
Dan Gohmana30370b2009-05-04 22:02:23 +00004511 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004512 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004513 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004514 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004515 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004516 return MinOpRes;
4517 }
4518
Dan Gohmanc702fc02009-06-19 23:29:04 +00004519 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4520 // For a SCEVUnknown, ask ValueTracking.
4521 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004522 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004523 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004524 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004525 return Zeros.countTrailingOnes();
4526 }
4527
4528 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004529 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004530}
Chris Lattnerd934c702004-04-02 20:23:17 +00004531
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00004532uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4533 auto I = MinTrailingZerosCache.find(S);
4534 if (I != MinTrailingZerosCache.end())
4535 return I->second;
4536
4537 uint32_t Result = GetMinTrailingZerosImpl(S);
4538 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4539 assert(InsertPair.second && "Should insert a new key");
4540 return InsertPair.first->second;
4541}
4542
Sanjoy Dasf8570812016-05-29 00:38:22 +00004543/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004544static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004545 if (Instruction *I = dyn_cast<Instruction>(V))
4546 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4547 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004548
4549 return None;
4550}
4551
Sanjoy Dasf8570812016-05-29 00:38:22 +00004552/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004553/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4554/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004555ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004556ScalarEvolution::getRange(const SCEV *S,
4557 ScalarEvolution::RangeSignHint SignHint) {
4558 DenseMap<const SCEV *, ConstantRange> &Cache =
4559 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4560 : SignedRanges;
4561
Dan Gohman761065e2010-11-17 02:44:44 +00004562 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004563 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4564 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004565 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004566
4567 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004568 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004569
Dan Gohman85be4332010-01-26 19:19:05 +00004570 unsigned BitWidth = getTypeSizeInBits(S->getType());
4571 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4572
Sanjoy Das91b54772015-03-09 21:43:43 +00004573 // If the value has known zeros, the maximum value will have those known zeros
4574 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004575 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004576 if (TZ != 0) {
4577 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4578 ConservativeResult =
4579 ConstantRange(APInt::getMinValue(BitWidth),
4580 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4581 else
4582 ConservativeResult = ConstantRange(
4583 APInt::getSignedMinValue(BitWidth),
4584 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4585 }
Dan Gohman85be4332010-01-26 19:19:05 +00004586
Dan Gohmane65c9172009-07-13 21:35:55 +00004587 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004588 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004589 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004590 X = X.add(getRange(Add->getOperand(i), SignHint));
4591 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004592 }
4593
4594 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004595 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004596 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004597 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4598 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004599 }
4600
4601 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004602 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004603 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004604 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4605 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004606 }
4607
4608 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004609 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004610 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004611 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4612 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004613 }
4614
4615 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004616 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4617 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4618 return setRange(UDiv, SignHint,
4619 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004620 }
4621
4622 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004623 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4624 return setRange(ZExt, SignHint,
4625 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004626 }
4627
4628 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004629 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4630 return setRange(SExt, SignHint,
4631 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004632 }
4633
4634 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004635 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4636 return setRange(Trunc, SignHint,
4637 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004638 }
4639
Dan Gohmane65c9172009-07-13 21:35:55 +00004640 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004641 // If there's no unsigned wrap, the value will never be less than its
4642 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004643 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004644 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004645 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004646 ConservativeResult = ConservativeResult.intersectWith(
4647 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004648
Dan Gohman51ad99d2010-01-21 02:09:26 +00004649 // If there's no signed wrap, and all the operands have the same sign or
4650 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004651 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004652 bool AllNonNeg = true;
4653 bool AllNonPos = true;
4654 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4655 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4656 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4657 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004658 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004659 ConservativeResult = ConservativeResult.intersectWith(
4660 ConstantRange(APInt(BitWidth, 0),
4661 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004662 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004663 ConservativeResult = ConservativeResult.intersectWith(
4664 ConstantRange(APInt::getSignedMinValue(BitWidth),
4665 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004666 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004667
4668 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004669 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004670 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004671 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4672 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004673 auto RangeFromAffine = getRangeForAffineAR(
4674 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4675 BitWidth);
4676 if (!RangeFromAffine.isFullSet())
4677 ConservativeResult =
4678 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004679
4680 auto RangeFromFactoring = getRangeViaFactoring(
4681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4682 BitWidth);
4683 if (!RangeFromFactoring.isFullSet())
4684 ConservativeResult =
4685 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004686 }
Dan Gohmand261d272009-06-24 01:05:09 +00004687 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004688
Sanjoy Das91b54772015-03-09 21:43:43 +00004689 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004690 }
4691
Dan Gohmanc702fc02009-06-19 23:29:04 +00004692 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004693 // Check if the IR explicitly contains !range metadata.
4694 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4695 if (MDRange.hasValue())
4696 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4697
Sanjoy Das91b54772015-03-09 21:43:43 +00004698 // Split here to avoid paying the compile-time cost of calling both
4699 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4700 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004701 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004702 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4703 // For a SCEVUnknown, ask ValueTracking.
4704 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004705 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004706 if (Ones != ~Zeros + 1)
4707 ConservativeResult =
4708 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4709 } else {
4710 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4711 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004712 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004713 if (NS > 1)
4714 ConservativeResult = ConservativeResult.intersectWith(
4715 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4716 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004717 }
4718
4719 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004720 }
4721
Sanjoy Das91b54772015-03-09 21:43:43 +00004722 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004723}
4724
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004725// Given a StartRange, Step and MaxBECount for an expression compute a range of
4726// values that the expression can take. Initially, the expression has a value
4727// from StartRange and then is changed by Step up to MaxBECount times. Signed
4728// argument defines if we treat Step as signed or unsigned.
4729static ConstantRange getRangeForAffineARHelper(APInt Step,
4730 ConstantRange StartRange,
4731 APInt MaxBECount,
4732 unsigned BitWidth, bool Signed) {
4733 // If either Step or MaxBECount is 0, then the expression won't change, and we
4734 // just need to return the initial range.
4735 if (Step == 0 || MaxBECount == 0)
4736 return StartRange;
4737
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00004738 // If we don't know anything about the initial value (i.e. StartRange is
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004739 // FullRange), then we don't know anything about the final range either.
4740 // Return FullRange.
4741 if (StartRange.isFullSet())
4742 return ConstantRange(BitWidth, /* isFullSet = */ true);
4743
4744 // If Step is signed and negative, then we use its absolute value, but we also
4745 // note that we're moving in the opposite direction.
4746 bool Descending = Signed && Step.isNegative();
4747
4748 if (Signed)
4749 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4750 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4751 // This equations hold true due to the well-defined wrap-around behavior of
4752 // APInt.
4753 Step = Step.abs();
4754
4755 // Check if Offset is more than full span of BitWidth. If it is, the
4756 // expression is guaranteed to overflow.
4757 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4758 return ConstantRange(BitWidth, /* isFullSet = */ true);
4759
4760 // Offset is by how much the expression can change. Checks above guarantee no
4761 // overflow here.
4762 APInt Offset = Step * MaxBECount;
4763
4764 // Minimum value of the final range will match the minimal value of StartRange
4765 // if the expression is increasing and will be decreased by Offset otherwise.
4766 // Maximum value of the final range will match the maximal value of StartRange
4767 // if the expression is decreasing and will be increased by Offset otherwise.
4768 APInt StartLower = StartRange.getLower();
4769 APInt StartUpper = StartRange.getUpper() - 1;
4770 APInt MovedBoundary =
4771 Descending ? (StartLower - Offset) : (StartUpper + Offset);
4772
4773 // It's possible that the new minimum/maximum value will fall into the initial
4774 // range (due to wrap around). This means that the expression can take any
4775 // value in this bitwidth, and we have to return full range.
4776 if (StartRange.contains(MovedBoundary))
4777 return ConstantRange(BitWidth, /* isFullSet = */ true);
4778
4779 APInt NewLower, NewUpper;
4780 if (Descending) {
4781 NewLower = MovedBoundary;
4782 NewUpper = StartUpper;
4783 } else {
4784 NewLower = StartLower;
4785 NewUpper = MovedBoundary;
4786 }
4787
4788 // If we end up with full range, return a proper full range.
4789 if (NewLower == NewUpper + 1)
4790 return ConstantRange(BitWidth, /* isFullSet = */ true);
4791
4792 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4793 return ConstantRange(NewLower, NewUpper + 1);
4794}
4795
Sanjoy Dasb765b632016-03-02 00:57:39 +00004796ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4797 const SCEV *Step,
4798 const SCEV *MaxBECount,
4799 unsigned BitWidth) {
4800 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4801 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4802 "Precondition!");
4803
Sanjoy Dasb765b632016-03-02 00:57:39 +00004804 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4805 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004806 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
Sanjoy Dasb765b632016-03-02 00:57:39 +00004807
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004808 // First, consider step signed.
Sanjoy Dasb765b632016-03-02 00:57:39 +00004809 ConstantRange StartSRange = getSignedRange(Start);
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004810 ConstantRange StepSRange = getSignedRange(Step);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004811
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004812 // If Step can be both positive and negative, we need to find ranges for the
4813 // maximum absolute step values in both directions and union them.
4814 ConstantRange SR =
4815 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4816 MaxBECountValue, BitWidth, /* Signed = */ true);
4817 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4818 StartSRange, MaxBECountValue,
4819 BitWidth, /* Signed = */ true));
Sanjoy Dasb765b632016-03-02 00:57:39 +00004820
Michael Zolotukhin99de88d2017-03-16 21:07:38 +00004821 // Next, consider step unsigned.
4822 ConstantRange UR = getRangeForAffineARHelper(
4823 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4824 MaxBECountValue, BitWidth, /* Signed = */ false);
4825
4826 // Finally, intersect signed and unsigned ranges.
4827 return SR.intersectWith(UR);
Sanjoy Dasb765b632016-03-02 00:57:39 +00004828}
4829
Sanjoy Dasbf730982016-03-02 00:57:54 +00004830ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4831 const SCEV *Step,
4832 const SCEV *MaxBECount,
4833 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004834 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4835 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4836
4837 struct SelectPattern {
4838 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004839 APInt TrueValue;
4840 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004841
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004842 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4843 const SCEV *S) {
4844 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004845 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004846
4847 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4848 "Should be!");
4849
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004850 // Peel off a constant offset:
4851 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4852 // In the future we could consider being smarter here and handle
4853 // {Start+Step,+,Step} too.
4854 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4855 return;
4856
4857 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4858 S = SA->getOperand(1);
4859 }
4860
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004861 // Peel off a cast operation
4862 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4863 CastOp = SCast->getSCEVType();
4864 S = SCast->getOperand();
4865 }
4866
Sanjoy Dasbf730982016-03-02 00:57:54 +00004867 using namespace llvm::PatternMatch;
4868
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004869 auto *SU = dyn_cast<SCEVUnknown>(S);
4870 const APInt *TrueVal, *FalseVal;
4871 if (!SU ||
4872 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4873 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004874 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004875 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004876 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004877
4878 TrueValue = *TrueVal;
4879 FalseValue = *FalseVal;
4880
4881 // Re-apply the cast we peeled off earlier
4882 if (CastOp.hasValue())
4883 switch (*CastOp) {
4884 default:
4885 llvm_unreachable("Unknown SCEV cast type!");
4886
4887 case scTruncate:
4888 TrueValue = TrueValue.trunc(BitWidth);
4889 FalseValue = FalseValue.trunc(BitWidth);
4890 break;
4891 case scZeroExtend:
4892 TrueValue = TrueValue.zext(BitWidth);
4893 FalseValue = FalseValue.zext(BitWidth);
4894 break;
4895 case scSignExtend:
4896 TrueValue = TrueValue.sext(BitWidth);
4897 FalseValue = FalseValue.sext(BitWidth);
4898 break;
4899 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004900
4901 // Re-apply the constant offset we peeled off earlier
4902 TrueValue += Offset;
4903 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004904 }
4905
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004906 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004907 };
4908
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004909 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004910 if (!StartPattern.isRecognized())
4911 return ConstantRange(BitWidth, /* isFullSet = */ true);
4912
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004913 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004914 if (!StepPattern.isRecognized())
4915 return ConstantRange(BitWidth, /* isFullSet = */ true);
4916
4917 if (StartPattern.Condition != StepPattern.Condition) {
4918 // We don't handle this case today; but we could, by considering four
4919 // possibilities below instead of two. I'm not sure if there are cases where
4920 // that will help over what getRange already does, though.
4921 return ConstantRange(BitWidth, /* isFullSet = */ true);
4922 }
4923
4924 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4925 // construct arbitrary general SCEV expressions here. This function is called
4926 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4927 // say) can end up caching a suboptimal value.
4928
Sanjoy Das6b017a12016-03-02 02:56:29 +00004929 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4930 // C2352 and C2512 (otherwise it isn't needed).
4931
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004932 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004933 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004934 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004935 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004936
Sanjoy Das1168f932016-03-02 02:34:20 +00004937 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004938 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004939 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004940 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004941
4942 return TrueRange.unionWith(FalseRange);
4943}
4944
Jingyue Wu42f1d672015-07-28 18:22:40 +00004945SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004946 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004947 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4948
4949 // Return early if there are no flags to propagate to the SCEV.
4950 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4951 if (BinOp->hasNoUnsignedWrap())
4952 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4953 if (BinOp->hasNoSignedWrap())
4954 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004955 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004956 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004957
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004958 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4959}
4960
4961bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4962 // Here we check that I is in the header of the innermost loop containing I,
4963 // since we only deal with instructions in the loop header. The actual loop we
4964 // need to check later will come from an add recurrence, but getting that
4965 // requires computing the SCEV of the operands, which can be expensive. This
4966 // check we can do cheaply to rule out some cases early.
4967 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004968 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004969 InnermostContainingLoop->getHeader() != I->getParent())
4970 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004971
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004972 // Only proceed if we can prove that I does not yield poison.
4973 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004974
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004975 // At this point we know that if I is executed, then it does not wrap
4976 // according to at least one of NSW or NUW. If I is not executed, then we do
4977 // not know if the calculation that I represents would wrap. Multiple
4978 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004979 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4980 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004981 // that guarantee for cases where I is not executed. So we need to find the
4982 // loop that I is considered in relation to and prove that I is executed for
4983 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004984 // calculates does not wrap anywhere in the loop, so then we can apply the
4985 // flags to the SCEV.
4986 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004987 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4988 // from different loops, so that we know which loop to prove that I is
4989 // executed in.
4990 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004991 // I could be an extractvalue from a call to an overflow intrinsic.
4992 // TODO: We can do better here in some cases.
4993 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4994 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004995 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004996 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004997 bool AllOtherOpsLoopInvariant = true;
4998 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4999 ++OtherOpIndex) {
5000 if (OtherOpIndex != OpIndex) {
5001 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5002 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5003 AllOtherOpsLoopInvariant = false;
5004 break;
5005 }
5006 }
5007 }
5008 if (AllOtherOpsLoopInvariant &&
5009 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5010 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005011 }
5012 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00005013 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00005014}
5015
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005016bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5017 // If we know that \c I can never be poison period, then that's enough.
5018 if (isSCEVExprNeverPoison(I))
5019 return true;
5020
5021 // For an add recurrence specifically, we assume that infinite loops without
5022 // side effects are undefined behavior, and then reason as follows:
5023 //
5024 // If the add recurrence is poison in any iteration, it is poison on all
5025 // future iterations (since incrementing poison yields poison). If the result
5026 // of the add recurrence is fed into the loop latch condition and the loop
5027 // does not contain any throws or exiting blocks other than the latch, we now
5028 // have the ability to "choose" whether the backedge is taken or not (by
5029 // choosing a sufficiently evil value for the poison feeding into the branch)
5030 // for every iteration including and after the one in which \p I first became
5031 // poison. There are two possibilities (let's call the iteration in which \p
5032 // I first became poison as K):
5033 //
5034 // 1. In the set of iterations including and after K, the loop body executes
5035 // no side effects. In this case executing the backege an infinte number
5036 // of times will yield undefined behavior.
5037 //
5038 // 2. In the set of iterations including and after K, the loop body executes
5039 // at least one side effect. In this case, that specific instance of side
5040 // effect is control dependent on poison, which also yields undefined
5041 // behavior.
5042
5043 auto *ExitingBB = L->getExitingBlock();
5044 auto *LatchBB = L->getLoopLatch();
5045 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5046 return false;
5047
5048 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005049 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005050
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005051 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5052 // things that are known to be fully poison under that assumption go on the
5053 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005054 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005055 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005056
5057 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00005058 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005059 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005060
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005061 for (auto *PoisonUser : Poison->users()) {
5062 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5063 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5064 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5065 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005066 assert(BI->isConditional() && "Only possibility!");
5067 if (BI->getParent() == LatchBB) {
5068 LatchControlDependentOnPoison = true;
5069 break;
5070 }
5071 }
5072 }
5073 }
5074
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005075 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5076}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005077
Sanjoy Das5603fc02016-09-26 02:44:07 +00005078ScalarEvolution::LoopProperties
5079ScalarEvolution::getLoopProperties(const Loop *L) {
5080 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005081
Sanjoy Das5603fc02016-09-26 02:44:07 +00005082 auto Itr = LoopPropertiesCache.find(L);
5083 if (Itr == LoopPropertiesCache.end()) {
5084 auto HasSideEffects = [](Instruction *I) {
5085 if (auto *SI = dyn_cast<StoreInst>(I))
5086 return !SI->isSimple();
5087
5088 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005089 };
5090
Sanjoy Das5603fc02016-09-26 02:44:07 +00005091 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5092 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005093
Sanjoy Das5603fc02016-09-26 02:44:07 +00005094 for (auto *BB : L->getBlocks())
5095 for (auto &I : *BB) {
5096 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5097 LP.HasNoAbnormalExits = false;
5098 if (HasSideEffects(&I))
5099 LP.HasNoSideEffects = false;
5100 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5101 break; // We're already as pessimistic as we can get.
5102 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005103
Sanjoy Das5603fc02016-09-26 02:44:07 +00005104 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005105 assert(InsertPair.second && "We just checked!");
5106 Itr = InsertPair.first;
5107 }
5108
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005109 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005110}
5111
Dan Gohmanaf752342009-07-07 17:06:11 +00005112const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005113 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005114 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005115
Dan Gohman69451a02010-03-09 23:46:50 +00005116 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005117 // Don't attempt to analyze instructions in blocks that aren't
5118 // reachable. Such instructions don't matter, and they aren't required
5119 // to obey basic rules for definitions dominating uses which this
5120 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005121 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005122 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005123 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005124 return getConstant(CI);
5125 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005126 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005127 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005128 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005129 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005130 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005131
Dan Gohman80ca01c2009-07-17 20:47:02 +00005132 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005133 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005134 switch (BO->Opcode) {
5135 case Instruction::Add: {
5136 // The simple thing to do would be to just call getSCEV on both operands
5137 // and call getAddExpr with the result. However if we're looking at a
5138 // bunch of things all added together, this can be quite inefficient,
5139 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5140 // Instead, gather up all the operands and make a single getAddExpr call.
5141 // LLVM IR canonical form means we need only traverse the left operands.
5142 SmallVector<const SCEV *, 4> AddOps;
5143 do {
5144 if (BO->Op) {
5145 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5146 AddOps.push_back(OpSCEV);
5147 break;
5148 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005149
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005150 // If a NUW or NSW flag can be applied to the SCEV for this
5151 // addition, then compute the SCEV for this addition by itself
5152 // with a separate call to getAddExpr. We need to do that
5153 // instead of pushing the operands of the addition onto AddOps,
5154 // since the flags are only known to apply to this particular
5155 // addition - they may not apply to other additions that can be
5156 // formed with operands from AddOps.
5157 const SCEV *RHS = getSCEV(BO->RHS);
5158 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5159 if (Flags != SCEV::FlagAnyWrap) {
5160 const SCEV *LHS = getSCEV(BO->LHS);
5161 if (BO->Opcode == Instruction::Sub)
5162 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5163 else
5164 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5165 break;
5166 }
Dan Gohman36bad002009-09-17 18:05:20 +00005167 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005168
5169 if (BO->Opcode == Instruction::Sub)
5170 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5171 else
5172 AddOps.push_back(getSCEV(BO->RHS));
5173
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005174 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005175 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5176 NewBO->Opcode != Instruction::Sub)) {
5177 AddOps.push_back(getSCEV(BO->LHS));
5178 break;
5179 }
5180 BO = NewBO;
5181 } while (true);
5182
5183 return getAddExpr(AddOps);
5184 }
5185
5186 case Instruction::Mul: {
5187 SmallVector<const SCEV *, 4> MulOps;
5188 do {
5189 if (BO->Op) {
5190 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5191 MulOps.push_back(OpSCEV);
5192 break;
5193 }
5194
5195 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5196 if (Flags != SCEV::FlagAnyWrap) {
5197 MulOps.push_back(
5198 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5199 break;
5200 }
5201 }
5202
5203 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005204 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005205 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5206 MulOps.push_back(getSCEV(BO->LHS));
5207 break;
5208 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005209 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005210 } while (true);
5211
5212 return getMulExpr(MulOps);
5213 }
5214 case Instruction::UDiv:
5215 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5216 case Instruction::Sub: {
5217 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5218 if (BO->Op)
5219 Flags = getNoWrapFlagsFromUB(BO->Op);
5220 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5221 }
5222 case Instruction::And:
5223 // For an expression like x&255 that merely masks off the high bits,
5224 // use zext(trunc(x)) as the SCEV expression.
5225 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5226 if (CI->isNullValue())
5227 return getSCEV(BO->RHS);
5228 if (CI->isAllOnesValue())
5229 return getSCEV(BO->LHS);
5230 const APInt &A = CI->getValue();
5231
5232 // Instcombine's ShrinkDemandedConstant may strip bits out of
5233 // constants, obscuring what would otherwise be a low-bits mask.
5234 // Use computeKnownBits to compute what ShrinkDemandedConstant
5235 // knew about to reconstruct a low-bits mask value.
5236 unsigned LZ = A.countLeadingZeros();
5237 unsigned TZ = A.countTrailingZeros();
5238 unsigned BitWidth = A.getBitWidth();
5239 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5240 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005241 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005242
5243 APInt EffectiveMask =
5244 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5245 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005246 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5247 const SCEV *LHS = getSCEV(BO->LHS);
5248 const SCEV *ShiftedLHS = nullptr;
5249 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5250 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5251 // For an expression like (x * 8) & 8, simplify the multiply.
5252 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5253 unsigned GCD = std::min(MulZeros, TZ);
5254 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5255 SmallVector<const SCEV*, 4> MulOps;
5256 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5257 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5258 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5259 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5260 }
5261 }
5262 if (!ShiftedLHS)
5263 ShiftedLHS = getUDivExpr(LHS, MulCount);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005264 return getMulExpr(
5265 getZeroExtendExpr(
Eli Friedmanf1f49c82017-01-18 23:56:42 +00005266 getTruncateExpr(ShiftedLHS,
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005267 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5268 BO->LHS->getType()),
5269 MulCount);
5270 }
Dan Gohman36bad002009-09-17 18:05:20 +00005271 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005272 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005273
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005274 case Instruction::Or:
5275 // If the RHS of the Or is a constant, we may have something like:
5276 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5277 // optimizations will transparently handle this case.
5278 //
5279 // In order for this transformation to be safe, the LHS must be of the
5280 // form X*(2^n) and the Or constant must be less than 2^n.
5281 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5282 const SCEV *LHS = getSCEV(BO->LHS);
5283 const APInt &CIVal = CI->getValue();
5284 if (GetMinTrailingZeros(LHS) >=
5285 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5286 // Build a plain add SCEV.
5287 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5288 // If the LHS of the add was an addrec and it has no-wrap flags,
5289 // transfer the no-wrap flags, since an or won't introduce a wrap.
5290 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5291 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5292 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5293 OldAR->getNoWrapFlags());
5294 }
5295 return S;
5296 }
5297 }
5298 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005299
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005300 case Instruction::Xor:
5301 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5302 // If the RHS of xor is -1, then this is a not operation.
5303 if (CI->isAllOnesValue())
5304 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005305
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005306 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5307 // This is a variant of the check for xor with -1, and it handles
5308 // the case where instcombine has trimmed non-demanded bits out
5309 // of an xor with -1.
5310 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5311 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5312 if (LBO->getOpcode() == Instruction::And &&
5313 LCI->getValue() == CI->getValue())
5314 if (const SCEVZeroExtendExpr *Z =
5315 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5316 Type *UTy = BO->LHS->getType();
5317 const SCEV *Z0 = Z->getOperand();
5318 Type *Z0Ty = Z0->getType();
5319 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005320
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005321 // If C is a low-bits mask, the zero extend is serving to
5322 // mask off the high bits. Complement the operand and
5323 // re-apply the zext.
5324 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5325 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5326
5327 // If C is a single bit, it may be in the sign-bit position
5328 // before the zero-extend. In this case, represent the xor
5329 // using an add, which is equivalent, and re-apply the zext.
5330 APInt Trunc = CI->getValue().trunc(Z0TySize);
5331 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5332 Trunc.isSignBit())
5333 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5334 UTy);
5335 }
5336 }
5337 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005338
5339 case Instruction::Shl:
5340 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005341 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5342 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005343
5344 // If the shift count is not less than the bitwidth, the result of
5345 // the shift is undefined. Don't try to analyze it, because the
5346 // resolution chosen here may differ from the resolution chosen in
5347 // other parts of the compiler.
5348 if (SA->getValue().uge(BitWidth))
5349 break;
5350
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005351 // It is currently not resolved how to interpret NSW for left
5352 // shift by BitWidth - 1, so we avoid applying flags in that
5353 // case. Remove this check (or this comment) once the situation
5354 // is resolved. See
5355 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5356 // and http://reviews.llvm.org/D8890 .
5357 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005358 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5359 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005360
Owen Andersonedb4a702009-07-24 23:12:02 +00005361 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005362 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005363 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005364 }
5365 break;
5366
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005367 case Instruction::AShr:
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005368 // AShr X, C, where C is a constant.
5369 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5370 if (!CI)
5371 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005372
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005373 Type *OuterTy = BO->LHS->getType();
5374 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5375 // If the shift count is not less than the bitwidth, the result of
5376 // the shift is undefined. Don't try to analyze it, because the
5377 // resolution chosen here may differ from the resolution chosen in
5378 // other parts of the compiler.
5379 if (CI->getValue().uge(BitWidth))
5380 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005381
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005382 if (CI->isNullValue())
5383 return getSCEV(BO->LHS); // shift by zero --> noop
5384
5385 uint64_t AShrAmt = CI->getZExtValue();
5386 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5387
5388 Operator *L = dyn_cast<Operator>(BO->LHS);
5389 if (L && L->getOpcode() == Instruction::Shl) {
5390 // X = Shl A, n
5391 // Y = AShr X, m
5392 // Both n and m are constant.
5393
5394 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5395 if (L->getOperand(1) == BO->RHS)
5396 // For a two-shift sext-inreg, i.e. n = m,
5397 // use sext(trunc(x)) as the SCEV expression.
5398 return getSignExtendExpr(
5399 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5400
5401 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5402 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5403 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5404 if (ShlAmt > AShrAmt) {
5405 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5406 // expression. We already checked that ShlAmt < BitWidth, so
5407 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5408 // ShlAmt - AShrAmt < Amt.
5409 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5410 ShlAmt - AShrAmt);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005411 return getSignExtendExpr(
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005412 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5413 getConstant(Mul)), OuterTy);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005414 }
Zhaoshi Zhenge3c90702017-03-23 18:06:09 +00005415 }
5416 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005417 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005418 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005419 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005420
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005421 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005422 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005423 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005424
5425 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005426 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005427
5428 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005429 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005430
5431 case Instruction::BitCast:
5432 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005433 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005434 return getSCEV(U->getOperand(0));
5435 break;
5436
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005437 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5438 // lead to pointer expressions which cannot safely be expanded to GEPs,
5439 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5440 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005441
Dan Gohmanee750d12009-05-08 20:26:55 +00005442 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005443 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005444
Dan Gohman05e89732008-06-22 19:56:46 +00005445 case Instruction::PHI:
5446 return createNodeForPHI(cast<PHINode>(U));
5447
5448 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005449 // U can also be a select constant expr, which let fall through. Since
5450 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5451 // constant expressions cannot have instructions as operands, we'd have
5452 // returned getUnknown for a select constant expressions anyway.
5453 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005454 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5455 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005456 break;
5457
5458 case Instruction::Call:
5459 case Instruction::Invoke:
5460 if (Value *RV = CallSite(U).getReturnedArgOperand())
5461 return getSCEV(RV);
5462 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005463 }
5464
Dan Gohmanc8e23622009-04-21 23:15:49 +00005465 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005466}
5467
5468
5469
5470//===----------------------------------------------------------------------===//
5471// Iteration Count Computation Code
5472//
5473
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005474static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5475 if (!ExitCount)
5476 return 0;
5477
5478 ConstantInt *ExitConst = ExitCount->getValue();
5479
5480 // Guard against huge trip counts.
5481 if (ExitConst->getValue().getActiveBits() > 32)
5482 return 0;
5483
5484 // In case of integer overflow, this returns 0, which is correct.
5485 return ((unsigned)ExitConst->getZExtValue()) + 1;
5486}
5487
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005488unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005489 if (BasicBlock *ExitingBB = L->getExitingBlock())
5490 return getSmallConstantTripCount(L, ExitingBB);
5491
5492 // No trip count information for multiple exits.
5493 return 0;
5494}
5495
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005496unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005497 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005498 assert(ExitingBlock && "Must pass a non-null exiting block!");
5499 assert(L->isLoopExiting(ExitingBlock) &&
5500 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005501 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005502 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005503 return getConstantTripCount(ExitCount);
5504}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005505
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005506unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005507 const auto *MaxExitCount =
5508 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5509 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005510}
5511
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005512unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005513 if (BasicBlock *ExitingBB = L->getExitingBlock())
5514 return getSmallConstantTripMultiple(L, ExitingBB);
5515
5516 // No trip multiple information for multiple exits.
5517 return 0;
5518}
5519
Sanjoy Dasf8570812016-05-29 00:38:22 +00005520/// Returns the largest constant divisor of the trip count of this loop as a
5521/// normal unsigned value, if possible. This means that the actual trip count is
5522/// always a multiple of the returned value (don't forget the trip count could
5523/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005524///
5525/// Returns 1 if the trip count is unknown or not guaranteed to be the
5526/// multiple of a constant (which is also the case if the trip count is simply
5527/// constant, use getSmallConstantTripCount for that case), Will also return 1
5528/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005529///
5530/// As explained in the comments for getSmallConstantTripCount, this assumes
5531/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005532unsigned
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005533ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005534 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005535 assert(ExitingBlock && "Must pass a non-null exiting block!");
5536 assert(L->isLoopExiting(ExitingBlock) &&
5537 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005538 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005539 if (ExitCount == getCouldNotCompute())
5540 return 1;
5541
5542 // Get the trip count from the BE count by adding 1.
Eli Friedmanb1578d32017-03-20 20:25:46 +00005543 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005544
Eli Friedmanb1578d32017-03-20 20:25:46 +00005545 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5546 if (!TC)
5547 // Attempt to factor more general cases. Returns the greatest power of
5548 // two divisor. If overflow happens, the trip count expression is still
5549 // divisible by the greatest power of 2 divisor returned.
5550 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005551
Eli Friedmanb1578d32017-03-20 20:25:46 +00005552 ConstantInt *Result = TC->getValue();
Andrew Trick2b6860f2011-08-11 23:36:16 +00005553
Hal Finkel30bd9342012-10-24 19:46:44 +00005554 // Guard against huge trip counts (this requires checking
5555 // for zero to handle the case where the trip count == -1 and the
5556 // addition wraps).
5557 if (!Result || Result->getValue().getActiveBits() > 32 ||
5558 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005559 return 1;
5560
5561 return (unsigned)Result->getZExtValue();
5562}
5563
Sanjoy Dasf8570812016-05-29 00:38:22 +00005564/// Get the expression for the number of loop iterations for which this loop is
5565/// guaranteed not to exit via ExitingBlock. Otherwise return
5566/// SCEVCouldNotCompute.
Eli Friedmanf7b060b2017-03-17 22:19:52 +00005567const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5568 BasicBlock *ExitingBlock) {
Andrew Trick77c55422011-08-02 04:23:35 +00005569 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005570}
5571
Silviu Baranga6f444df2016-04-08 14:29:09 +00005572const SCEV *
5573ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5574 SCEVUnionPredicate &Preds) {
5575 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5576}
5577
Dan Gohmanaf752342009-07-07 17:06:11 +00005578const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005579 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005580}
5581
Sanjoy Dasf8570812016-05-29 00:38:22 +00005582/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5583/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005584const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005585 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005586}
5587
John Brawn84b21832016-10-21 11:08:48 +00005588bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5589 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5590}
5591
Sanjoy Dasf8570812016-05-29 00:38:22 +00005592/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005593static void
5594PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5595 BasicBlock *Header = L->getHeader();
5596
5597 // Push all Loop-header PHIs onto the Worklist stack.
5598 for (BasicBlock::iterator I = Header->begin();
5599 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5600 Worklist.push_back(PN);
5601}
5602
Dan Gohman2b8da352009-04-30 20:47:05 +00005603const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005604ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5605 auto &BTI = getBackedgeTakenInfo(L);
5606 if (BTI.hasFullInfo())
5607 return BTI;
5608
5609 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5610
5611 if (!Pair.second)
5612 return Pair.first->second;
5613
5614 BackedgeTakenInfo Result =
5615 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5616
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005617 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005618}
5619
5620const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005621ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005622 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005623 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005624 // update the value. The temporary CouldNotCompute value tells SCEV
5625 // code elsewhere that it shouldn't attempt to request a new
5626 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005627 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005628 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005629 if (!Pair.second)
5630 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005631
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005632 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005633 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5634 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005635 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005636
5637 if (Result.getExact(this) != getCouldNotCompute()) {
5638 assert(isLoopInvariant(Result.getExact(this), L) &&
5639 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005640 "Computed backedge-taken count isn't loop invariant for loop!");
5641 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005642 }
5643 else if (Result.getMax(this) == getCouldNotCompute() &&
5644 isa<PHINode>(L->getHeader()->begin())) {
5645 // Only count loops that have phi nodes as not being computable.
5646 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005647 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005648
Chris Lattnera337f5e2011-01-09 02:16:18 +00005649 // Now that we know more about the trip count for this loop, forget any
5650 // existing SCEV values for PHI nodes in this loop since they are only
5651 // conservative estimates made without the benefit of trip count
5652 // information. This is similar to the code in forgetLoop, except that
5653 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005654 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005655 SmallVector<Instruction *, 16> Worklist;
5656 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005657
Chris Lattnera337f5e2011-01-09 02:16:18 +00005658 SmallPtrSet<Instruction *, 8> Visited;
5659 while (!Worklist.empty()) {
5660 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005661 if (!Visited.insert(I).second)
5662 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005663
Chris Lattnera337f5e2011-01-09 02:16:18 +00005664 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005665 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005666 if (It != ValueExprMap.end()) {
5667 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005668
Chris Lattnera337f5e2011-01-09 02:16:18 +00005669 // SCEVUnknown for a PHI either means that it has an unrecognized
5670 // structure, or it's a PHI that's in the progress of being computed
5671 // by createNodeForPHI. In the former case, additional loop trip
5672 // count information isn't going to change anything. In the later
5673 // case, createNodeForPHI will perform the necessary updates on its
5674 // own when it gets to that point.
5675 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005676 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005677 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005678 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005679 if (PHINode *PN = dyn_cast<PHINode>(I))
5680 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005681 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005682
5683 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005684 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005685 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005686
5687 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005688 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005689 // recusive call to getBackedgeTakenInfo (on a different
5690 // loop), which would invalidate the iterator computed
5691 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005692 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005693}
5694
Dan Gohman880c92a2009-10-31 15:04:55 +00005695void ScalarEvolution::forgetLoop(const Loop *L) {
5696 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005697 auto RemoveLoopFromBackedgeMap =
5698 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5699 auto BTCPos = Map.find(L);
5700 if (BTCPos != Map.end()) {
5701 BTCPos->second.clear();
5702 Map.erase(BTCPos);
5703 }
5704 };
5705
5706 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5707 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005708
Dan Gohman880c92a2009-10-31 15:04:55 +00005709 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005710 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005711 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005712
Dan Gohmandc191042009-07-08 19:23:34 +00005713 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005714 while (!Worklist.empty()) {
5715 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005716 if (!Visited.insert(I).second)
5717 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005718
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005719 ValueExprMapType::iterator It =
5720 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005721 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005722 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005723 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005724 if (PHINode *PN = dyn_cast<PHINode>(I))
5725 ConstantEvolutionLoopExitValue.erase(PN);
5726 }
5727
5728 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005729 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005730
5731 // Forget all contained loops too, to avoid dangling entries in the
5732 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005733 for (Loop *I : *L)
5734 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005735
Sanjoy Das5603fc02016-09-26 02:44:07 +00005736 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005737}
5738
Eric Christopheref6d5932010-07-29 01:25:38 +00005739void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005740 Instruction *I = dyn_cast<Instruction>(V);
5741 if (!I) return;
5742
5743 // Drop information about expressions based on loop-header PHIs.
5744 SmallVector<Instruction *, 16> Worklist;
5745 Worklist.push_back(I);
5746
5747 SmallPtrSet<Instruction *, 8> Visited;
5748 while (!Worklist.empty()) {
5749 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005750 if (!Visited.insert(I).second)
5751 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005752
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005753 ValueExprMapType::iterator It =
5754 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005755 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005756 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005757 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005758 if (PHINode *PN = dyn_cast<PHINode>(I))
5759 ConstantEvolutionLoopExitValue.erase(PN);
5760 }
5761
5762 PushDefUseChildren(I, Worklist);
5763 }
5764}
5765
Sanjoy Dasf8570812016-05-29 00:38:22 +00005766/// Get the exact loop backedge taken count considering all loop exits. A
5767/// computable result can only be returned for loops with a single exit.
5768/// Returning the minimum taken count among all exits is incorrect because one
5769/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5770/// the limit of each loop test is never skipped. This is a valid assumption as
5771/// long as the loop exits via that test. For precise results, it is the
5772/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005773/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005774const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005775ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5776 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005777 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005778 if (!isComplete() || ExitNotTaken.empty())
5779 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005780
Craig Topper9f008862014-04-15 04:59:12 +00005781 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005782 for (auto &ENT : ExitNotTaken) {
5783 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005784
5785 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005786 BECount = ENT.ExactNotTaken;
5787 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005788 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005789 if (Preds && !ENT.hasAlwaysTruePredicate())
5790 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005791
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005792 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005793 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005794 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005795
Andrew Trickbbb226a2011-09-02 21:20:46 +00005796 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005797 return BECount;
5798}
5799
Sanjoy Dasf8570812016-05-29 00:38:22 +00005800/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005801const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005802ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005803 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005804 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005805 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005806 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005807
Andrew Trick3ca3f982011-07-26 17:19:55 +00005808 return SE->getCouldNotCompute();
5809}
5810
5811/// getMax - Get the max backedge taken count for the loop.
5812const SCEV *
5813ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005814 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5815 return !ENT.hasAlwaysTruePredicate();
5816 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005817
Sanjoy Das73268612016-09-26 01:10:22 +00005818 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5819 return SE->getCouldNotCompute();
5820
5821 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005822}
5823
John Brawn84b21832016-10-21 11:08:48 +00005824bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5825 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5826 return !ENT.hasAlwaysTruePredicate();
5827 };
5828 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5829}
5830
Andrew Trick9093e152013-03-26 03:14:53 +00005831bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5832 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005833 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5834 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005835 return true;
5836
Silviu Baranga6f444df2016-04-08 14:29:09 +00005837 for (auto &ENT : ExitNotTaken)
5838 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5839 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005840 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005841
Andrew Trick9093e152013-03-26 03:14:53 +00005842 return false;
5843}
5844
Andrew Trick3ca3f982011-07-26 17:19:55 +00005845/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5846/// computable exit into a persistent ExitNotTakenInfo array.
5847ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005848 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5849 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005850 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5851 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005852 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005853 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005854 std::transform(
5855 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005856 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005857 BasicBlock *ExitBB = EEI.first;
5858 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005859 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005860 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005861
5862 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5863 for (auto *Pred : EL.Predicates)
5864 Predicate->add(Pred);
5865
5866 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005867 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005868}
5869
Sanjoy Dasf8570812016-05-29 00:38:22 +00005870/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005871void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005872 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005873}
5874
Sanjoy Dasf8570812016-05-29 00:38:22 +00005875/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005876ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005877ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5878 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005879 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005880 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005881
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005882 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5883
5884 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005885 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005886 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005887 const SCEV *MustExitMaxBECount = nullptr;
5888 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005889 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005890
5891 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5892 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005893 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005894 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005895 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005896 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5897
Sanjoy Dasf0022122016-09-28 17:14:58 +00005898 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005899 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005900
5901 // 1. For each exit that can be computed, add an entry to ExitCounts.
5902 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005903 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005904 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005905 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005906 CouldComputeBECount = false;
5907 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005908 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005909
Andrew Trick839e30b2014-05-23 19:47:13 +00005910 // 2. Derive the loop's MaxBECount from each exit's max number of
5911 // non-exiting iterations. Partition the loop exits into two kinds:
5912 // LoopMustExits and LoopMayExits.
5913 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005914 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5915 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005916 // MaxBECount is the minimum EL.MaxNotTaken of computable
5917 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5918 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5919 // computable EL.MaxNotTaken.
5920 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005921 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005922 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005923 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005924 MustExitMaxOrZero = EL.MaxOrZero;
5925 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005926 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005927 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005928 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005929 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005930 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5931 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005932 else {
5933 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005934 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005935 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005936 }
Dan Gohman96212b62009-06-22 00:31:57 +00005937 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005938 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5939 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00005940 // The loop backedge will be taken the maximum or zero times if there's
5941 // a single exit that must be taken the maximum or zero times.
5942 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005943 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00005944 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00005945}
5946
Andrew Trick3ca3f982011-07-26 17:19:55 +00005947ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005948ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5949 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005950
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005951 // Okay, we've chosen an exiting block. See what condition causes us to exit
5952 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005953 // lead to the loop header.
5954 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005955 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005956 for (auto *SBB : successors(ExitingBlock))
5957 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005958 if (Exit) // Multiple exit successors.
5959 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005960 Exit = SBB;
5961 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005962 MustExecuteLoopHeader = false;
5963 }
Dan Gohmance973df2009-06-24 04:48:43 +00005964
Chris Lattner18954852007-01-07 02:24:26 +00005965 // At this point, we know we have a conditional branch that determines whether
5966 // the loop is exited. However, we don't know if the branch is executed each
5967 // time through the loop. If not, then the execution count of the branch will
5968 // not be equal to the trip count of the loop.
5969 //
5970 // Currently we check for this by checking to see if the Exit branch goes to
5971 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005972 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005973 // loop header. This is common for un-rotated loops.
5974 //
5975 // If both of those tests fail, walk up the unique predecessor chain to the
5976 // header, stopping if there is an edge that doesn't exit the loop. If the
5977 // header is reached, the execution count of the branch will be equal to the
5978 // trip count of the loop.
5979 //
5980 // More extensive analysis could be done to handle more cases here.
5981 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005982 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005983 // The simple checks failed, try climbing the unique predecessor chain
5984 // up to the header.
5985 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005986 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005987 BasicBlock *Pred = BB->getUniquePredecessor();
5988 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005989 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005990 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005991 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005992 if (PredSucc == BB)
5993 continue;
5994 // If the predecessor has a successor that isn't BB and isn't
5995 // outside the loop, assume the worst.
5996 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005997 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005998 }
5999 if (Pred == L->getHeader()) {
6000 Ok = true;
6001 break;
6002 }
6003 BB = Pred;
6004 }
6005 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006006 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006007 }
6008
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006009 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006010 TerminatorInst *Term = ExitingBlock->getTerminator();
6011 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6012 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6013 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006014 return computeExitLimitFromCond(
6015 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6016 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006017 }
6018
6019 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006020 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006021 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006022
6023 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00006024}
6025
Andrew Trick3ca3f982011-07-26 17:19:55 +00006026ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006027ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006028 Value *ExitCond,
6029 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006030 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006031 bool ControlsExit,
6032 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006033 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00006034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6035 if (BO->getOpcode() == Instruction::And) {
6036 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00006037 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006038 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006039 ControlsExit && !EitherMayExit,
6040 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006041 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006042 ControlsExit && !EitherMayExit,
6043 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006044 const SCEV *BECount = getCouldNotCompute();
6045 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006046 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006047 // Both conditions must be true for the loop to continue executing.
6048 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006049 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6050 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006051 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006052 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006053 BECount =
6054 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6055 if (EL0.MaxNotTaken == getCouldNotCompute())
6056 MaxBECount = EL1.MaxNotTaken;
6057 else if (EL1.MaxNotTaken == getCouldNotCompute())
6058 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006059 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006060 MaxBECount =
6061 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006062 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006063 // Both conditions must be true at the same time for the loop to exit.
6064 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006065 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006066 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6067 MaxBECount = EL0.MaxNotTaken;
6068 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6069 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006070 }
6071
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006072 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6073 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006074 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6075 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6076 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00006077 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6078 !isa<SCEVCouldNotCompute>(BECount))
6079 MaxBECount = BECount;
6080
John Brawn84b21832016-10-21 11:08:48 +00006081 return ExitLimit(BECount, MaxBECount, false,
6082 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006083 }
6084 if (BO->getOpcode() == Instruction::Or) {
6085 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00006086 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006087 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006088 ControlsExit && !EitherMayExit,
6089 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006090 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006091 ControlsExit && !EitherMayExit,
6092 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00006093 const SCEV *BECount = getCouldNotCompute();
6094 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00006095 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00006096 // Both conditions must be false for the loop to continue executing.
6097 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006098 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6099 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006100 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006101 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006102 BECount =
6103 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6104 if (EL0.MaxNotTaken == getCouldNotCompute())
6105 MaxBECount = EL1.MaxNotTaken;
6106 else if (EL1.MaxNotTaken == getCouldNotCompute())
6107 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006108 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006109 MaxBECount =
6110 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006111 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006112 // Both conditions must be false at the same time for the loop to exit.
6113 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006114 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006115 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6116 MaxBECount = EL0.MaxNotTaken;
6117 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6118 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006119 }
6120
John Brawn84b21832016-10-21 11:08:48 +00006121 return ExitLimit(BECount, MaxBECount, false,
6122 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006123 }
6124 }
6125
6126 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006127 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006128 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6129 ExitLimit EL =
6130 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6131 if (EL.hasFullInfo() || !AllowPredicates)
6132 return EL;
6133
6134 // Try again, but use SCEV predicates this time.
6135 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6136 /*AllowPredicates=*/true);
6137 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006138
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006139 // Check for a constant condition. These are normally stripped out by
6140 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6141 // preserve the CFG and is temporarily leaving constant conditions
6142 // in place.
6143 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6144 if (L->contains(FBB) == !CI->getZExtValue())
6145 // The backedge is always taken.
6146 return getCouldNotCompute();
6147 else
6148 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006149 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006150 }
6151
Eli Friedmanebf98b02009-05-09 12:32:42 +00006152 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006153 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006154}
6155
Andrew Trick3ca3f982011-07-26 17:19:55 +00006156ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006157ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006158 ICmpInst *ExitCond,
6159 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006160 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006161 bool ControlsExit,
6162 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006163
Reid Spencer266e42b2006-12-23 06:05:41 +00006164 // If the condition was exit on true, convert the condition to exit on false
6165 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006166 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006167 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006168 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006169 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006170
6171 // Handle common loops like: for (X = "string"; *X; ++X)
6172 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6173 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006174 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006175 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006176 if (ItCnt.hasAnyInfo())
6177 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006178 }
6179
Dan Gohmanaf752342009-07-07 17:06:11 +00006180 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6181 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006182
6183 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006184 LHS = getSCEVAtScope(LHS, L);
6185 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006186
Dan Gohmance973df2009-06-24 04:48:43 +00006187 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006188 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006189 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006190 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006191 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006192 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006193 }
6194
Dan Gohman81585c12010-05-03 16:35:17 +00006195 // Simplify the operands before analyzing them.
6196 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6197
Chris Lattnerd934c702004-04-02 20:23:17 +00006198 // If we have a comparison of a chrec against a constant, try to use value
6199 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006200 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6201 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006202 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006203 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006204 ConstantRange CompRange =
6205 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006206
Dan Gohmanaf752342009-07-07 17:06:11 +00006207 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006208 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006209 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006210
Chris Lattnerd934c702004-04-02 20:23:17 +00006211 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006212 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006213 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006214 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006215 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006216 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006217 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006218 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006219 case ICmpInst::ICMP_EQ: { // while (X == Y)
6220 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006221 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006222 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006223 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006224 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006225 case ICmpInst::ICMP_SLT:
6226 case ICmpInst::ICMP_ULT: { // while (X < Y)
6227 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006228 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006229 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006230 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006231 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006232 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006233 case ICmpInst::ICMP_SGT:
6234 case ICmpInst::ICMP_UGT: { // while (X > Y)
6235 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006236 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006237 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006238 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006239 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006240 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006241 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006242 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006243 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006244 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006245
6246 auto *ExhaustiveCount =
6247 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6248
6249 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6250 return ExhaustiveCount;
6251
6252 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6253 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006254}
6255
Benjamin Kramer5a188542014-02-11 15:44:32 +00006256ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006257ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006258 SwitchInst *Switch,
6259 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006260 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006261 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6262
6263 // Give up if the exit is the default dest of a switch.
6264 if (Switch->getDefaultDest() == ExitingBlock)
6265 return getCouldNotCompute();
6266
6267 assert(L->contains(Switch->getDefaultDest()) &&
6268 "Default case must not exit the loop!");
6269 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6270 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6271
6272 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006273 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006274 if (EL.hasAnyInfo())
6275 return EL;
6276
6277 return getCouldNotCompute();
6278}
6279
Chris Lattnerec901cc2004-10-12 01:49:27 +00006280static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006281EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6282 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006283 const SCEV *InVal = SE.getConstant(C);
6284 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006285 assert(isa<SCEVConstant>(Val) &&
6286 "Evaluation of SCEV at constant didn't fold correctly?");
6287 return cast<SCEVConstant>(Val)->getValue();
6288}
6289
Sanjoy Dasf8570812016-05-29 00:38:22 +00006290/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6291/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006292ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006293ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006294 LoadInst *LI,
6295 Constant *RHS,
6296 const Loop *L,
6297 ICmpInst::Predicate predicate) {
6298
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006299 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006300
6301 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006302 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006303 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006304 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006305
6306 // Make sure that it is really a constant global we are gepping, with an
6307 // initializer, and make sure the first IDX is really 0.
6308 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006309 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006310 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6311 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006312 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006313
6314 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006315 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006316 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006317 unsigned VarIdxNum = 0;
6318 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6319 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6320 Indexes.push_back(CI);
6321 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006322 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006323 VarIdx = GEP->getOperand(i);
6324 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006325 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006326 }
6327
Andrew Trick7004e4b2012-03-26 22:33:59 +00006328 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6329 if (!VarIdx)
6330 return getCouldNotCompute();
6331
Chris Lattnerec901cc2004-10-12 01:49:27 +00006332 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6333 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006334 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006335 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006336
6337 // We can only recognize very limited forms of loop index expressions, in
6338 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006339 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006340 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006341 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6342 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006343 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006344
6345 unsigned MaxSteps = MaxBruteForceIterations;
6346 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006347 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006348 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006349 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006350
6351 // Form the GEP offset.
6352 Indexes[VarIdxNum] = Val;
6353
Chris Lattnere166a852012-01-24 05:49:24 +00006354 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6355 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006356 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006357
6358 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006359 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006360 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006361 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006362 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006363 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006364 }
6365 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006366 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006367}
6368
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006369ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6370 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6371 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6372 if (!RHS)
6373 return getCouldNotCompute();
6374
6375 const BasicBlock *Latch = L->getLoopLatch();
6376 if (!Latch)
6377 return getCouldNotCompute();
6378
6379 const BasicBlock *Predecessor = L->getLoopPredecessor();
6380 if (!Predecessor)
6381 return getCouldNotCompute();
6382
6383 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6384 // Return LHS in OutLHS and shift_opt in OutOpCode.
6385 auto MatchPositiveShift =
6386 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6387
6388 using namespace PatternMatch;
6389
6390 ConstantInt *ShiftAmt;
6391 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6392 OutOpCode = Instruction::LShr;
6393 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6394 OutOpCode = Instruction::AShr;
6395 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6396 OutOpCode = Instruction::Shl;
6397 else
6398 return false;
6399
6400 return ShiftAmt->getValue().isStrictlyPositive();
6401 };
6402
6403 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6404 //
6405 // loop:
6406 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6407 // %iv.shifted = lshr i32 %iv, <positive constant>
6408 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006409 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006410 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6411 auto MatchShiftRecurrence =
6412 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6413 Optional<Instruction::BinaryOps> PostShiftOpCode;
6414
6415 {
6416 Instruction::BinaryOps OpC;
6417 Value *V;
6418
6419 // If we encounter a shift instruction, "peel off" the shift operation,
6420 // and remember that we did so. Later when we inspect %iv's backedge
6421 // value, we will make sure that the backedge value uses the same
6422 // operation.
6423 //
6424 // Note: the peeled shift operation does not have to be the same
6425 // instruction as the one feeding into the PHI's backedge value. We only
6426 // really care about it being the same *kind* of shift instruction --
6427 // that's all that is required for our later inferences to hold.
6428 if (MatchPositiveShift(LHS, V, OpC)) {
6429 PostShiftOpCode = OpC;
6430 LHS = V;
6431 }
6432 }
6433
6434 PNOut = dyn_cast<PHINode>(LHS);
6435 if (!PNOut || PNOut->getParent() != L->getHeader())
6436 return false;
6437
6438 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6439 Value *OpLHS;
6440
6441 return
6442 // The backedge value for the PHI node must be a shift by a positive
6443 // amount
6444 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6445
6446 // of the PHI node itself
6447 OpLHS == PNOut &&
6448
6449 // and the kind of shift should be match the kind of shift we peeled
6450 // off, if any.
6451 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6452 };
6453
6454 PHINode *PN;
6455 Instruction::BinaryOps OpCode;
6456 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6457 return getCouldNotCompute();
6458
6459 const DataLayout &DL = getDataLayout();
6460
6461 // The key rationale for this optimization is that for some kinds of shift
6462 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6463 // within a finite number of iterations. If the condition guarding the
6464 // backedge (in the sense that the backedge is taken if the condition is true)
6465 // is false for the value the shift recurrence stabilizes to, then we know
6466 // that the backedge is taken only a finite number of times.
6467
6468 ConstantInt *StableValue = nullptr;
6469 switch (OpCode) {
6470 default:
6471 llvm_unreachable("Impossible case!");
6472
6473 case Instruction::AShr: {
6474 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6475 // bitwidth(K) iterations.
6476 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6477 bool KnownZero, KnownOne;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00006478 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006479 Predecessor->getTerminator(), &DT);
6480 auto *Ty = cast<IntegerType>(RHS->getType());
6481 if (KnownZero)
6482 StableValue = ConstantInt::get(Ty, 0);
6483 else if (KnownOne)
6484 StableValue = ConstantInt::get(Ty, -1, true);
6485 else
6486 return getCouldNotCompute();
6487
6488 break;
6489 }
6490 case Instruction::LShr:
6491 case Instruction::Shl:
6492 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6493 // stabilize to 0 in at most bitwidth(K) iterations.
6494 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6495 break;
6496 }
6497
6498 auto *Result =
6499 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6500 assert(Result->getType()->isIntegerTy(1) &&
6501 "Otherwise cannot be an operand to a branch instruction");
6502
6503 if (Result->isZeroValue()) {
6504 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6505 const SCEV *UpperBound =
6506 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006507 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006508 }
6509
6510 return getCouldNotCompute();
6511}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006512
Sanjoy Dasf8570812016-05-29 00:38:22 +00006513/// Return true if we can constant fold an instruction of the specified type,
6514/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006515static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006516 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006517 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6518 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006519 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006520
Chris Lattnerdd730472004-04-17 22:58:41 +00006521 if (const CallInst *CI = dyn_cast<CallInst>(I))
6522 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006523 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006524 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006525}
6526
Andrew Trick3a86ba72011-10-05 03:25:31 +00006527/// Determine whether this instruction can constant evolve within this loop
6528/// assuming its operands can all constant evolve.
6529static bool canConstantEvolve(Instruction *I, const Loop *L) {
6530 // An instruction outside of the loop can't be derived from a loop PHI.
6531 if (!L->contains(I)) return false;
6532
6533 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006534 // We don't currently keep track of the control flow needed to evaluate
6535 // PHIs, so we cannot handle PHIs inside of loops.
6536 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006537 }
6538
6539 // If we won't be able to constant fold this expression even if the operands
6540 // are constants, bail early.
6541 return CanConstantFold(I);
6542}
6543
6544/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6545/// recursing through each instruction operand until reaching a loop header phi.
6546static PHINode *
6547getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Michael Liao468fb742017-01-13 18:28:30 +00006548 DenseMap<Instruction *, PHINode *> &PHIMap,
6549 unsigned Depth) {
6550 if (Depth > MaxConstantEvolvingDepth)
6551 return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006552
6553 // Otherwise, we can evaluate this instruction if all of its operands are
6554 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006555 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006556 for (Value *Op : UseInst->operands()) {
6557 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006558
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006559 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006560 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006561
6562 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006563 if (!P)
6564 // If this operand is already visited, reuse the prior result.
6565 // We may have P != PHI if this is the deepest point at which the
6566 // inconsistent paths meet.
6567 P = PHIMap.lookup(OpInst);
6568 if (!P) {
6569 // Recurse and memoize the results, whether a phi is found or not.
6570 // This recursive call invalidates pointers into PHIMap.
Michael Liao468fb742017-01-13 18:28:30 +00006571 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006572 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006573 }
Craig Topper9f008862014-04-15 04:59:12 +00006574 if (!P)
6575 return nullptr; // Not evolving from PHI
6576 if (PHI && PHI != P)
6577 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006578 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006579 }
6580 // This is a expression evolving from a constant PHI!
6581 return PHI;
6582}
6583
Chris Lattnerdd730472004-04-17 22:58:41 +00006584/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6585/// in the loop that V is derived from. We allow arbitrary operations along the
6586/// way, but the operands of an operation must either be constants or a value
6587/// derived from a constant PHI. If this expression does not fit with these
6588/// constraints, return null.
6589static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006590 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006591 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006592
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006593 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006594 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006595
Andrew Trick3a86ba72011-10-05 03:25:31 +00006596 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006597 DenseMap<Instruction *, PHINode *> PHIMap;
Michael Liao468fb742017-01-13 18:28:30 +00006598 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
Chris Lattnerdd730472004-04-17 22:58:41 +00006599}
6600
6601/// EvaluateExpression - Given an expression that passes the
6602/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6603/// in the loop has the value PHIVal. If we can't fold this expression for some
6604/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006605static Constant *EvaluateExpression(Value *V, const Loop *L,
6606 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006607 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006608 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006609 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006610 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006611 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006612 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006613
Andrew Trick3a86ba72011-10-05 03:25:31 +00006614 if (Constant *C = Vals.lookup(I)) return C;
6615
Nick Lewyckya6674c72011-10-22 19:58:20 +00006616 // An instruction inside the loop depends on a value outside the loop that we
6617 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006618 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006619
6620 // An unmapped PHI can be due to a branch or another loop inside this loop,
6621 // or due to this not being the initial iteration through a loop where we
6622 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006623 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006624
Dan Gohmanf820bd32010-06-22 13:15:46 +00006625 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006626
6627 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006628 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6629 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006630 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006631 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006632 continue;
6633 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006634 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006635 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006636 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006637 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006638 }
6639
Nick Lewyckya6674c72011-10-22 19:58:20 +00006640 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006641 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006642 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006643 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6644 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006645 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006646 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006647 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006648}
6649
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006650
6651// If every incoming value to PN except the one for BB is a specific Constant,
6652// return that, else return nullptr.
6653static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6654 Constant *IncomingVal = nullptr;
6655
6656 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6657 if (PN->getIncomingBlock(i) == BB)
6658 continue;
6659
6660 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6661 if (!CurrentVal)
6662 return nullptr;
6663
6664 if (IncomingVal != CurrentVal) {
6665 if (IncomingVal)
6666 return nullptr;
6667 IncomingVal = CurrentVal;
6668 }
6669 }
6670
6671 return IncomingVal;
6672}
6673
Chris Lattnerdd730472004-04-17 22:58:41 +00006674/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6675/// in the header of its containing loop, we know the loop executes a
6676/// constant number of times, and the PHI node is just a recurrence
6677/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006678Constant *
6679ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006680 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006681 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006682 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006683 if (I != ConstantEvolutionLoopExitValue.end())
6684 return I->second;
6685
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006686 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006687 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006688
6689 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6690
Andrew Trick3a86ba72011-10-05 03:25:31 +00006691 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006692 BasicBlock *Header = L->getHeader();
6693 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006694
Sanjoy Dasdd709962015-10-08 18:28:36 +00006695 BasicBlock *Latch = L->getLoopLatch();
6696 if (!Latch)
6697 return nullptr;
6698
Sanjoy Das4493b402015-10-07 17:38:25 +00006699 for (auto &I : *Header) {
6700 PHINode *PHI = dyn_cast<PHINode>(&I);
6701 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006702 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006703 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006704 CurrentIterVals[PHI] = StartCST;
6705 }
6706 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006707 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006708
Sanjoy Dasdd709962015-10-08 18:28:36 +00006709 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006710
6711 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006712 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006713 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006714
Dan Gohman0bddac12009-02-24 18:55:53 +00006715 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006716 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006717 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006718 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006719 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006720 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006721
Nick Lewyckya6674c72011-10-22 19:58:20 +00006722 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006723 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006724 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006725 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006726 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006727 if (!NextPHI)
6728 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006729 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006730
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006731 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6732
Nick Lewyckya6674c72011-10-22 19:58:20 +00006733 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6734 // cease to be able to evaluate one of them or if they stop evolving,
6735 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006736 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006737 for (const auto &I : CurrentIterVals) {
6738 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006739 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006740 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006741 }
6742 // We use two distinct loops because EvaluateExpression may invalidate any
6743 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006744 for (const auto &I : PHIsToCompute) {
6745 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006746 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006747 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006748 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006749 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006750 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006751 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006752 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006753 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006754
6755 // If all entries in CurrentIterVals == NextIterVals then we can stop
6756 // iterating, the loop can't continue to change.
6757 if (StoppedEvolving)
6758 return RetVal = CurrentIterVals[PN];
6759
Andrew Trick3a86ba72011-10-05 03:25:31 +00006760 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006761 }
6762}
6763
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006764const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006765 Value *Cond,
6766 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006767 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006768 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006769
Dan Gohman866971e2010-06-19 14:17:24 +00006770 // If the loop is canonicalized, the PHI will have exactly two entries.
6771 // That's the only form we support here.
6772 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6773
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006774 DenseMap<Instruction *, Constant *> CurrentIterVals;
6775 BasicBlock *Header = L->getHeader();
6776 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6777
Sanjoy Dasdd709962015-10-08 18:28:36 +00006778 BasicBlock *Latch = L->getLoopLatch();
6779 assert(Latch && "Should follow from NumIncomingValues == 2!");
6780
Sanjoy Das4493b402015-10-07 17:38:25 +00006781 for (auto &I : *Header) {
6782 PHINode *PHI = dyn_cast<PHINode>(&I);
6783 if (!PHI)
6784 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006785 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006786 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006787 CurrentIterVals[PHI] = StartCST;
6788 }
6789 if (!CurrentIterVals.count(PN))
6790 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006791
6792 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6793 // the loop symbolically to determine when the condition gets a value of
6794 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006795 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006796 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006797 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006798 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006799 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006800
Zhou Sheng75b871f2007-01-11 12:24:14 +00006801 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006802 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006803
Reid Spencer983e3b32007-03-01 07:25:48 +00006804 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006805 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006806 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006807 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006808
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006809 // Update all the PHI nodes for the next iteration.
6810 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006811
6812 // Create a list of which PHIs we need to compute. We want to do this before
6813 // calling EvaluateExpression on them because that may invalidate iterators
6814 // into CurrentIterVals.
6815 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006816 for (const auto &I : CurrentIterVals) {
6817 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006818 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006819 PHIsToCompute.push_back(PHI);
6820 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006821 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006822 Constant *&NextPHI = NextIterVals[PHI];
6823 if (NextPHI) continue; // Already computed!
6824
Sanjoy Dasdd709962015-10-08 18:28:36 +00006825 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006826 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006827 }
6828 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006829 }
6830
6831 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006832 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006833}
6834
Dan Gohmanaf752342009-07-07 17:06:11 +00006835const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006836 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6837 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006838 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006839 for (auto &LS : Values)
6840 if (LS.first == L)
6841 return LS.second ? LS.second : V;
6842
6843 Values.emplace_back(L, nullptr);
6844
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006845 // Otherwise compute it.
6846 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006847 for (auto &LS : reverse(ValuesAtScopes[V]))
6848 if (LS.first == L) {
6849 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006850 break;
6851 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006852 return C;
6853}
6854
Nick Lewyckya6674c72011-10-22 19:58:20 +00006855/// This builds up a Constant using the ConstantExpr interface. That way, we
6856/// will return Constants for objects which aren't represented by a
6857/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6858/// Returns NULL if the SCEV isn't representable as a Constant.
6859static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006860 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006861 case scCouldNotCompute:
6862 case scAddRecExpr:
6863 break;
6864 case scConstant:
6865 return cast<SCEVConstant>(V)->getValue();
6866 case scUnknown:
6867 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6868 case scSignExtend: {
6869 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6870 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6871 return ConstantExpr::getSExt(CastOp, SS->getType());
6872 break;
6873 }
6874 case scZeroExtend: {
6875 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6876 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6877 return ConstantExpr::getZExt(CastOp, SZ->getType());
6878 break;
6879 }
6880 case scTruncate: {
6881 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6882 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6883 return ConstantExpr::getTrunc(CastOp, ST->getType());
6884 break;
6885 }
6886 case scAddExpr: {
6887 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6888 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006889 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6890 unsigned AS = PTy->getAddressSpace();
6891 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6892 C = ConstantExpr::getBitCast(C, DestPtrTy);
6893 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006894 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6895 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006896 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006897
6898 // First pointer!
6899 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006900 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006901 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006902 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006903 // The offsets have been converted to bytes. We can add bytes to an
6904 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006905 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006906 }
6907
6908 // Don't bother trying to sum two pointers. We probably can't
6909 // statically compute a load that results from it anyway.
6910 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006911 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006912
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006913 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6914 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006915 C2 = ConstantExpr::getIntegerCast(
6916 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006917 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006918 } else
6919 C = ConstantExpr::getAdd(C, C2);
6920 }
6921 return C;
6922 }
6923 break;
6924 }
6925 case scMulExpr: {
6926 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6927 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6928 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006929 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006930 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6931 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006932 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006933 C = ConstantExpr::getMul(C, C2);
6934 }
6935 return C;
6936 }
6937 break;
6938 }
6939 case scUDivExpr: {
6940 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6941 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6942 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6943 if (LHS->getType() == RHS->getType())
6944 return ConstantExpr::getUDiv(LHS, RHS);
6945 break;
6946 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006947 case scSMaxExpr:
6948 case scUMaxExpr:
6949 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006950 }
Craig Topper9f008862014-04-15 04:59:12 +00006951 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006952}
6953
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006954const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006955 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006956
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006957 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006958 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006959 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006960 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006961 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006962 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6963 if (PHINode *PN = dyn_cast<PHINode>(I))
6964 if (PN->getParent() == LI->getHeader()) {
6965 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006966 // to see if the loop that contains it has a known backedge-taken
6967 // count. If so, we may be able to force computation of the exit
6968 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006969 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006970 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006971 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006972 // Okay, we know how many times the containing loop executes. If
6973 // this is a constant evolving PHI node, get the final value at
6974 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006975 Constant *RV =
6976 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006977 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006978 }
6979 }
6980
Reid Spencere6328ca2006-12-04 21:33:23 +00006981 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006982 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006983 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006984 // result. This is particularly useful for computing loop exit values.
6985 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006986 SmallVector<Constant *, 4> Operands;
6987 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006988 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006989 if (Constant *C = dyn_cast<Constant>(Op)) {
6990 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006991 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006992 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006993
6994 // If any of the operands is non-constant and if they are
6995 // non-integer and non-pointer, don't even try to analyze them
6996 // with scev techniques.
6997 if (!isSCEVable(Op->getType()))
6998 return V;
6999
7000 const SCEV *OrigV = getSCEV(Op);
7001 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7002 MadeImprovement |= OrigV != OpV;
7003
Nick Lewyckya6674c72011-10-22 19:58:20 +00007004 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007005 if (!C) return V;
7006 if (C->getType() != Op->getType())
7007 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7008 Op->getType(),
7009 false),
7010 C, Op->getType());
7011 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00007012 }
Dan Gohmance973df2009-06-24 04:48:43 +00007013
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007014 // Check to see if getSCEVAtScope actually made an improvement.
7015 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00007016 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00007017 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007018 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00007019 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007020 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007021 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7022 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00007023 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00007024 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00007025 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007026 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00007027 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007028 }
Chris Lattnerdd730472004-04-17 22:58:41 +00007029 }
7030 }
7031
7032 // This is some other type of SCEVUnknown, just return it.
7033 return V;
7034 }
7035
Dan Gohmana30370b2009-05-04 22:02:23 +00007036 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007037 // Avoid performing the look-up in the common case where the specified
7038 // expression has no loop-variant portions.
7039 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007040 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007041 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007042 // Okay, at least one of these operands is loop variant but might be
7043 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00007044 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7045 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00007046 NewOps.push_back(OpAtScope);
7047
7048 for (++i; i != e; ++i) {
7049 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007050 NewOps.push_back(OpAtScope);
7051 }
7052 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007053 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007054 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007055 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00007056 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007057 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00007058 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00007059 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00007060 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007061 }
7062 }
7063 // If we got here, all operands are loop invariant.
7064 return Comm;
7065 }
7066
Dan Gohmana30370b2009-05-04 22:02:23 +00007067 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007068 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7069 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00007070 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7071 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00007072 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00007073 }
7074
7075 // If this is a loop recurrence for a loop that does not contain L, then we
7076 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00007077 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007078 // First, attempt to evaluate each operand.
7079 // Avoid performing the look-up in the common case where the specified
7080 // expression has no loop-variant portions.
7081 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7082 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7083 if (OpAtScope == AddRec->getOperand(i))
7084 continue;
7085
7086 // Okay, at least one of these operands is loop variant but might be
7087 // foldable. Build a new instance of the folded commutative expression.
7088 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7089 AddRec->op_begin()+i);
7090 NewOps.push_back(OpAtScope);
7091 for (++i; i != e; ++i)
7092 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7093
Andrew Trick759ba082011-04-27 01:21:25 +00007094 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00007095 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00007096 AddRec->getNoWrapFlags(SCEV::FlagNW));
7097 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00007098 // The addrec may be folded to a nonrecurrence, for example, if the
7099 // induction variable is multiplied by zero after constant folding. Go
7100 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00007101 if (!AddRec)
7102 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007103 break;
7104 }
7105
7106 // If the scope is outside the addrec's loop, evaluate it by using the
7107 // loop exit value of the addrec.
7108 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007109 // To evaluate this recurrence, we need to know how many times the AddRec
7110 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00007111 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007112 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00007113
Eli Friedman61f67622008-08-04 23:49:06 +00007114 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007115 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007116 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007117
Dan Gohman8ca08852009-05-24 23:25:42 +00007118 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007119 }
7120
Dan Gohmana30370b2009-05-04 22:02:23 +00007121 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007122 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007123 if (Op == Cast->getOperand())
7124 return Cast; // must be loop invariant
7125 return getZeroExtendExpr(Op, Cast->getType());
7126 }
7127
Dan Gohmana30370b2009-05-04 22:02:23 +00007128 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007129 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007130 if (Op == Cast->getOperand())
7131 return Cast; // must be loop invariant
7132 return getSignExtendExpr(Op, Cast->getType());
7133 }
7134
Dan Gohmana30370b2009-05-04 22:02:23 +00007135 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007136 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007137 if (Op == Cast->getOperand())
7138 return Cast; // must be loop invariant
7139 return getTruncateExpr(Op, Cast->getType());
7140 }
7141
Torok Edwinfbcc6632009-07-14 16:55:14 +00007142 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007143}
7144
Dan Gohmanaf752342009-07-07 17:06:11 +00007145const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007146 return getSCEVAtScope(getSCEV(V), L);
7147}
7148
Sanjoy Dasf8570812016-05-29 00:38:22 +00007149/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007150///
7151/// A * X = B (mod N)
7152///
7153/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7154/// A and B isn't important.
7155///
7156/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007157static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007158 ScalarEvolution &SE) {
7159 uint32_t BW = A.getBitWidth();
Eli Friedman10d1ff62017-01-31 00:42:42 +00007160 assert(BW == SE.getTypeSizeInBits(B->getType()));
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007161 assert(A != 0 && "A must be non-zero.");
7162
7163 // 1. D = gcd(A, N)
7164 //
7165 // The gcd of A and N may have only one prime factor: 2. The number of
7166 // trailing zeros in A is its multiplicity
7167 uint32_t Mult2 = A.countTrailingZeros();
7168 // D = 2^Mult2
7169
7170 // 2. Check if B is divisible by D.
7171 //
7172 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7173 // is not less than multiplicity of this prime factor for D.
Eli Friedman10d1ff62017-01-31 00:42:42 +00007174 if (SE.GetMinTrailingZeros(B) < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007175 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007176
7177 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7178 // modulo (N / D).
7179 //
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007180 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7181 // (N / D) in general. The inverse itself always fits into BW bits, though,
7182 // so we immediately truncate it.
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007183 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7184 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007185 Mod.setBit(BW - Mult2); // Mod = N / D
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007186 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007187
7188 // 4. Compute the minimum unsigned root of the equation:
7189 // I * (B / D) mod (N / D)
Eli Friedmanb5c3a0d2017-01-12 20:21:00 +00007190 // To simplify the computation, we factor out the divide by D:
7191 // (I * B mod N) / D
Eli Friedman10d1ff62017-01-31 00:42:42 +00007192 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7193 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007194}
Chris Lattnerd934c702004-04-02 20:23:17 +00007195
Sanjoy Dasf8570812016-05-29 00:38:22 +00007196/// Find the roots of the quadratic equation for the given quadratic chrec
7197/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7198/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007199///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007200static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007201SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007202 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007203 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7204 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7205 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007206
Chris Lattnerd934c702004-04-02 20:23:17 +00007207 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007208 if (!LC || !MC || !NC)
7209 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007210
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007211 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7212 const APInt &L = LC->getAPInt();
7213 const APInt &M = MC->getAPInt();
7214 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007215 APInt Two(BitWidth, 2);
7216 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007217
Dan Gohmance973df2009-06-24 04:48:43 +00007218 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007219 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007220 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007221 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7222 // The B coefficient is M-N/2
7223 APInt B(M);
7224 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007225
Reid Spencer983e3b32007-03-01 07:25:48 +00007226 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007227 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007228
Reid Spencer983e3b32007-03-01 07:25:48 +00007229 // Compute the B^2-4ac term.
7230 APInt SqrtTerm(B);
7231 SqrtTerm *= B;
7232 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007233
Nick Lewyckyfb780832012-08-01 09:14:36 +00007234 if (SqrtTerm.isNegative()) {
7235 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007236 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007237 }
7238
Reid Spencer983e3b32007-03-01 07:25:48 +00007239 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7240 // integer value or else APInt::sqrt() will assert.
7241 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007242
Dan Gohmance973df2009-06-24 04:48:43 +00007243 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007244 // The divisions must be performed as signed divisions.
7245 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007246 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007247 if (TwoA.isMinValue())
7248 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007249
Owen Anderson47db9412009-07-22 00:24:57 +00007250 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007251
7252 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007253 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007254 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007255 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007256
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007257 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7258 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007259 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007260}
7261
Andrew Trick3ca3f982011-07-26 17:19:55 +00007262ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007263ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007264 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007265
7266 // This is only used for loops with a "x != y" exit test. The exit condition
7267 // is now expressed as a single expression, V = x-y. So the exit test is
7268 // effectively V != 0. We know and take advantage of the fact that this
7269 // expression only being used in a comparison by zero context.
7270
Sanjoy Dasf0022122016-09-28 17:14:58 +00007271 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007272 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007273 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007274 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007275 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007276 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007277 }
7278
Dan Gohman48f82222009-05-04 22:30:44 +00007279 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007280 if (!AddRec && AllowPredicates)
7281 // Try to make this an AddRec using runtime tests, in the first X
7282 // iterations of this loop, where X is the SCEV expression found by the
7283 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007284 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007285
Chris Lattnerd934c702004-04-02 20:23:17 +00007286 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007287 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007288
Chris Lattnerdff679f2011-01-09 22:39:48 +00007289 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7290 // the quadratic equation to solve it.
7291 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007292 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7293 const SCEVConstant *R1 = Roots->first;
7294 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007295 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007296 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7297 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007298 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007299 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007300
Chris Lattnerd934c702004-04-02 20:23:17 +00007301 // We can only use this value if the chrec ends up with an exact zero
7302 // value at this index. When solving for "X*X != 5", for example, we
7303 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007304 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007305 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007306 // We found a quadratic root!
7307 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007308 }
7309 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007310 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007311 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007312
Chris Lattnerdff679f2011-01-09 22:39:48 +00007313 // Otherwise we can only handle this if it is affine.
7314 if (!AddRec->isAffine())
7315 return getCouldNotCompute();
7316
7317 // If this is an affine expression, the execution count of this branch is
7318 // the minimum unsigned root of the following equation:
7319 //
7320 // Start + Step*N = 0 (mod 2^BW)
7321 //
7322 // equivalent to:
7323 //
7324 // Step*N = -Start (mod 2^BW)
7325 //
7326 // where BW is the common bit width of Start and Step.
7327
7328 // Get the initial value for the loop.
7329 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7330 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7331
7332 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007333 //
7334 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7335 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7336 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7337 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007338 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007339 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007340 return getCouldNotCompute();
7341
Andrew Trick8b55b732011-03-14 16:50:06 +00007342 // For positive steps (counting up until unsigned overflow):
7343 // N = -Start/Step (as unsigned)
7344 // For negative steps (counting down to zero):
7345 // N = Start/-Step
7346 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007347 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007348 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007349
7350 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007351 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7352 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007353 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
Eli Friedman83962652017-01-11 20:55:48 +00007354 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
Eli Friedmanbd6deda2017-01-11 21:07:15 +00007355
7356 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7357 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7358 // case, and see if we can improve the bound.
7359 //
7360 // Explicitly handling this here is necessary because getUnsignedRange
7361 // isn't context-sensitive; it doesn't know that we only care about the
7362 // range inside the loop.
7363 const SCEV *Zero = getZero(Distance->getType());
7364 const SCEV *One = getOne(Distance->getType());
7365 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7366 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7367 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7368 // as "unsigned_max(Distance + 1) - 1".
7369 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7370 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7371 }
Eli Friedman83962652017-01-11 20:55:48 +00007372 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007373 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007374
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007375 // If the condition controls loop exit (the loop exits only if the expression
7376 // is true) and the addition is no-wrap we can use unsigned divide to
7377 // compute the backedge count. In this case, the step may not divide the
7378 // distance, but we don't care because if the condition is "missed" the loop
7379 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007380 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7381 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007382 const SCEV *Exact =
7383 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007384 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007385 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007386
Eli Friedman10d1ff62017-01-31 00:42:42 +00007387 // Solve the general equation.
7388 const SCEV *E = SolveLinEquationWithOverflow(
7389 StepC->getAPInt(), getNegativeSCEV(Start), *this);
7390 return ExitLimit(E, E, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007391}
7392
Andrew Trick3ca3f982011-07-26 17:19:55 +00007393ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007394ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007395 // Loops that look like: while (X == 0) are very strange indeed. We don't
7396 // handle them yet except for the trivial case. This could be expanded in the
7397 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007398
Chris Lattnerd934c702004-04-02 20:23:17 +00007399 // If the value is a constant, check to see if it is known to be non-zero
7400 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007401 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007402 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007403 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007404 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007405 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007406
Chris Lattnerd934c702004-04-02 20:23:17 +00007407 // We could implement others, but I really doubt anyone writes loops like
7408 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007409 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007410}
7411
Dan Gohman4e3c1132010-04-15 16:19:08 +00007412std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007413ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007414 // If the block has a unique predecessor, then there is no path from the
7415 // predecessor to the block that does not go through the direct edge
7416 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007417 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007418 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007419
7420 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007421 // If the header has a unique predecessor outside the loop, it must be
7422 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007423 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007424 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007425
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007426 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007427}
7428
Sanjoy Dasf8570812016-05-29 00:38:22 +00007429/// SCEV structural equivalence is usually sufficient for testing whether two
7430/// expressions are equal, however for the purposes of looking for a condition
7431/// guarding a loop, it can be useful to be a little more general, since a
7432/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007433///
Dan Gohmanaf752342009-07-07 17:06:11 +00007434static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007435 // Quick check to see if they are the same SCEV.
7436 if (A == B) return true;
7437
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007438 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7439 // Not all instructions that are "identical" compute the same value. For
7440 // instance, two distinct alloca instructions allocating the same type are
7441 // identical and do not read memory; but compute distinct values.
7442 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7443 };
7444
Dan Gohman450f4e02009-06-20 00:35:32 +00007445 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7446 // two different instructions with the same value. Check for this case.
7447 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7448 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7449 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7450 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007451 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007452 return true;
7453
7454 // Otherwise assume they may have a different value.
7455 return false;
7456}
7457
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007458bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007459 const SCEV *&LHS, const SCEV *&RHS,
7460 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007461 bool Changed = false;
7462
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007463 // If we hit the max recursion limit bail out.
7464 if (Depth >= 3)
7465 return false;
7466
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007467 // Canonicalize a constant to the right side.
7468 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7469 // Check for both operands constant.
7470 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7471 if (ConstantExpr::getICmp(Pred,
7472 LHSC->getValue(),
7473 RHSC->getValue())->isNullValue())
7474 goto trivially_false;
7475 else
7476 goto trivially_true;
7477 }
7478 // Otherwise swap the operands to put the constant on the right.
7479 std::swap(LHS, RHS);
7480 Pred = ICmpInst::getSwappedPredicate(Pred);
7481 Changed = true;
7482 }
7483
7484 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007485 // addrec's loop, put the addrec on the left. Also make a dominance check,
7486 // as both operands could be addrecs loop-invariant in each other's loop.
7487 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7488 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007489 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007490 std::swap(LHS, RHS);
7491 Pred = ICmpInst::getSwappedPredicate(Pred);
7492 Changed = true;
7493 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007494 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007495
7496 // If there's a constant operand, canonicalize comparisons with boundary
7497 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7498 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007499 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007500
7501 bool SimplifiedByConstantRange = false;
7502
7503 if (!ICmpInst::isEquality(Pred)) {
7504 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7505 if (ExactCR.isFullSet())
7506 goto trivially_true;
7507 else if (ExactCR.isEmptySet())
7508 goto trivially_false;
7509
7510 APInt NewRHS;
7511 CmpInst::Predicate NewPred;
7512 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7513 ICmpInst::isEquality(NewPred)) {
7514 // We were able to convert an inequality to an equality.
7515 Pred = NewPred;
7516 RHS = getConstant(NewRHS);
7517 Changed = SimplifiedByConstantRange = true;
7518 }
7519 }
7520
7521 if (!SimplifiedByConstantRange) {
7522 switch (Pred) {
7523 default:
7524 break;
7525 case ICmpInst::ICMP_EQ:
7526 case ICmpInst::ICMP_NE:
7527 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7528 if (!RA)
7529 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7530 if (const SCEVMulExpr *ME =
7531 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7532 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7533 ME->getOperand(0)->isAllOnesValue()) {
7534 RHS = AE->getOperand(1);
7535 LHS = ME->getOperand(1);
7536 Changed = true;
7537 }
7538 break;
7539
7540
7541 // The "Should have been caught earlier!" messages refer to the fact
7542 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7543 // should have fired on the corresponding cases, and canonicalized the
7544 // check to trivially_true or trivially_false.
7545
7546 case ICmpInst::ICMP_UGE:
7547 assert(!RA.isMinValue() && "Should have been caught earlier!");
7548 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007549 RHS = getConstant(RA - 1);
7550 Changed = true;
7551 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007552 case ICmpInst::ICMP_ULE:
7553 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7554 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007555 RHS = getConstant(RA + 1);
7556 Changed = true;
7557 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007558 case ICmpInst::ICMP_SGE:
7559 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7560 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007561 RHS = getConstant(RA - 1);
7562 Changed = true;
7563 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007564 case ICmpInst::ICMP_SLE:
7565 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7566 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007567 RHS = getConstant(RA + 1);
7568 Changed = true;
7569 break;
7570 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007571 }
7572 }
7573
7574 // Check for obvious equality.
7575 if (HasSameValue(LHS, RHS)) {
7576 if (ICmpInst::isTrueWhenEqual(Pred))
7577 goto trivially_true;
7578 if (ICmpInst::isFalseWhenEqual(Pred))
7579 goto trivially_false;
7580 }
7581
Dan Gohman81585c12010-05-03 16:35:17 +00007582 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7583 // adding or subtracting 1 from one of the operands.
7584 switch (Pred) {
7585 case ICmpInst::ICMP_SLE:
7586 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7587 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007588 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007589 Pred = ICmpInst::ICMP_SLT;
7590 Changed = true;
7591 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007592 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007593 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007594 Pred = ICmpInst::ICMP_SLT;
7595 Changed = true;
7596 }
7597 break;
7598 case ICmpInst::ICMP_SGE:
7599 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007600 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007601 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007602 Pred = ICmpInst::ICMP_SGT;
7603 Changed = true;
7604 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7605 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007606 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007607 Pred = ICmpInst::ICMP_SGT;
7608 Changed = true;
7609 }
7610 break;
7611 case ICmpInst::ICMP_ULE:
7612 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007613 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007614 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007615 Pred = ICmpInst::ICMP_ULT;
7616 Changed = true;
7617 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007618 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007619 Pred = ICmpInst::ICMP_ULT;
7620 Changed = true;
7621 }
7622 break;
7623 case ICmpInst::ICMP_UGE:
7624 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007625 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007626 Pred = ICmpInst::ICMP_UGT;
7627 Changed = true;
7628 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007629 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007630 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007631 Pred = ICmpInst::ICMP_UGT;
7632 Changed = true;
7633 }
7634 break;
7635 default:
7636 break;
7637 }
7638
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007639 // TODO: More simplifications are possible here.
7640
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007641 // Recursively simplify until we either hit a recursion limit or nothing
7642 // changes.
7643 if (Changed)
7644 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7645
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007646 return Changed;
7647
7648trivially_true:
7649 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007650 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007651 Pred = ICmpInst::ICMP_EQ;
7652 return true;
7653
7654trivially_false:
7655 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007656 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007657 Pred = ICmpInst::ICMP_NE;
7658 return true;
7659}
7660
Dan Gohmane65c9172009-07-13 21:35:55 +00007661bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7662 return getSignedRange(S).getSignedMax().isNegative();
7663}
7664
7665bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7666 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7667}
7668
7669bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7670 return !getSignedRange(S).getSignedMin().isNegative();
7671}
7672
7673bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7674 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7675}
7676
7677bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7678 return isKnownNegative(S) || isKnownPositive(S);
7679}
7680
7681bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7682 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007683 // Canonicalize the inputs first.
7684 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7685
Dan Gohman07591692010-04-11 22:16:48 +00007686 // If LHS or RHS is an addrec, check to see if the condition is true in
7687 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007688 // If LHS and RHS are both addrec, both conditions must be true in
7689 // every iteration of the loop.
7690 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7691 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7692 bool LeftGuarded = false;
7693 bool RightGuarded = false;
7694 if (LAR) {
7695 const Loop *L = LAR->getLoop();
7696 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7697 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7698 if (!RAR) return true;
7699 LeftGuarded = true;
7700 }
7701 }
7702 if (RAR) {
7703 const Loop *L = RAR->getLoop();
7704 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7705 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7706 if (!LAR) return true;
7707 RightGuarded = true;
7708 }
7709 }
7710 if (LeftGuarded && RightGuarded)
7711 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007712
Sanjoy Das7d910f22015-10-02 18:50:30 +00007713 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7714 return true;
7715
Dan Gohman07591692010-04-11 22:16:48 +00007716 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007717 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007718}
7719
Sanjoy Das5dab2052015-07-27 21:42:49 +00007720bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7721 ICmpInst::Predicate Pred,
7722 bool &Increasing) {
7723 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7724
7725#ifndef NDEBUG
7726 // Verify an invariant: inverting the predicate should turn a monotonically
7727 // increasing change to a monotonically decreasing one, and vice versa.
7728 bool IncreasingSwapped;
7729 bool ResultSwapped = isMonotonicPredicateImpl(
7730 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7731
7732 assert(Result == ResultSwapped && "should be able to analyze both!");
7733 if (ResultSwapped)
7734 assert(Increasing == !IncreasingSwapped &&
7735 "monotonicity should flip as we flip the predicate");
7736#endif
7737
7738 return Result;
7739}
7740
7741bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7742 ICmpInst::Predicate Pred,
7743 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007744
7745 // A zero step value for LHS means the induction variable is essentially a
7746 // loop invariant value. We don't really depend on the predicate actually
7747 // flipping from false to true (for increasing predicates, and the other way
7748 // around for decreasing predicates), all we care about is that *if* the
7749 // predicate changes then it only changes from false to true.
7750 //
7751 // A zero step value in itself is not very useful, but there may be places
7752 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7753 // as general as possible.
7754
Sanjoy Das366acc12015-08-06 20:43:41 +00007755 switch (Pred) {
7756 default:
7757 return false; // Conservative answer
7758
7759 case ICmpInst::ICMP_UGT:
7760 case ICmpInst::ICMP_UGE:
7761 case ICmpInst::ICMP_ULT:
7762 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007763 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007764 return false;
7765
7766 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007767 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007768
7769 case ICmpInst::ICMP_SGT:
7770 case ICmpInst::ICMP_SGE:
7771 case ICmpInst::ICMP_SLT:
7772 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007773 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007774 return false;
7775
7776 const SCEV *Step = LHS->getStepRecurrence(*this);
7777
7778 if (isKnownNonNegative(Step)) {
7779 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7780 return true;
7781 }
7782
7783 if (isKnownNonPositive(Step)) {
7784 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7785 return true;
7786 }
7787
7788 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007789 }
7790
Sanjoy Das5dab2052015-07-27 21:42:49 +00007791 }
7792
Sanjoy Das366acc12015-08-06 20:43:41 +00007793 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007794}
7795
7796bool ScalarEvolution::isLoopInvariantPredicate(
7797 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7798 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7799 const SCEV *&InvariantRHS) {
7800
7801 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7802 if (!isLoopInvariant(RHS, L)) {
7803 if (!isLoopInvariant(LHS, L))
7804 return false;
7805
7806 std::swap(LHS, RHS);
7807 Pred = ICmpInst::getSwappedPredicate(Pred);
7808 }
7809
7810 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7811 if (!ArLHS || ArLHS->getLoop() != L)
7812 return false;
7813
7814 bool Increasing;
7815 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7816 return false;
7817
7818 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7819 // true as the loop iterates, and the backedge is control dependent on
7820 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7821 //
7822 // * if the predicate was false in the first iteration then the predicate
7823 // is never evaluated again, since the loop exits without taking the
7824 // backedge.
7825 // * if the predicate was true in the first iteration then it will
7826 // continue to be true for all future iterations since it is
7827 // monotonically increasing.
7828 //
7829 // For both the above possibilities, we can replace the loop varying
7830 // predicate with its value on the first iteration of the loop (which is
7831 // loop invariant).
7832 //
7833 // A similar reasoning applies for a monotonically decreasing predicate, by
7834 // replacing true with false and false with true in the above two bullets.
7835
7836 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7837
7838 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7839 return false;
7840
7841 InvariantPred = Pred;
7842 InvariantLHS = ArLHS->getStart();
7843 InvariantRHS = RHS;
7844 return true;
7845}
7846
Sanjoy Das401e6312016-02-01 20:48:10 +00007847bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7848 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007849 if (HasSameValue(LHS, RHS))
7850 return ICmpInst::isTrueWhenEqual(Pred);
7851
Dan Gohman07591692010-04-11 22:16:48 +00007852 // This code is split out from isKnownPredicate because it is called from
7853 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007854
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007855 auto CheckRanges =
7856 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7857 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7858 .contains(RangeLHS);
7859 };
7860
7861 // The check at the top of the function catches the case where the values are
7862 // known to be equal.
7863 if (Pred == CmpInst::ICMP_EQ)
7864 return false;
7865
7866 if (Pred == CmpInst::ICMP_NE)
7867 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7868 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7869 isKnownNonZero(getMinusSCEV(LHS, RHS));
7870
7871 if (CmpInst::isSigned(Pred))
7872 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7873
7874 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007875}
7876
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007877bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7878 const SCEV *LHS,
7879 const SCEV *RHS) {
7880
7881 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7882 // Return Y via OutY.
7883 auto MatchBinaryAddToConst =
7884 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7885 SCEV::NoWrapFlags ExpectedFlags) {
7886 const SCEV *NonConstOp, *ConstOp;
7887 SCEV::NoWrapFlags FlagsPresent;
7888
7889 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7890 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7891 return false;
7892
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007893 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007894 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7895 };
7896
7897 APInt C;
7898
7899 switch (Pred) {
7900 default:
7901 break;
7902
7903 case ICmpInst::ICMP_SGE:
7904 std::swap(LHS, RHS);
7905 case ICmpInst::ICMP_SLE:
7906 // X s<= (X + C)<nsw> if C >= 0
7907 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7908 return true;
7909
7910 // (X + C)<nsw> s<= X if C <= 0
7911 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7912 !C.isStrictlyPositive())
7913 return true;
7914 break;
7915
7916 case ICmpInst::ICMP_SGT:
7917 std::swap(LHS, RHS);
7918 case ICmpInst::ICMP_SLT:
7919 // X s< (X + C)<nsw> if C > 0
7920 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7921 C.isStrictlyPositive())
7922 return true;
7923
7924 // (X + C)<nsw> s< X if C < 0
7925 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7926 return true;
7927 break;
7928 }
7929
7930 return false;
7931}
7932
Sanjoy Das7d910f22015-10-02 18:50:30 +00007933bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7934 const SCEV *LHS,
7935 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007936 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007937 return false;
7938
7939 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7940 // the stack can result in exponential time complexity.
7941 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7942
7943 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7944 //
7945 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7946 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7947 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7948 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7949 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007950 return isKnownNonNegative(RHS) &&
7951 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7952 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007953}
7954
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007955bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7956 ICmpInst::Predicate Pred,
7957 const SCEV *LHS, const SCEV *RHS) {
7958 // No need to even try if we know the module has no guards.
7959 if (!HasGuards)
7960 return false;
7961
7962 return any_of(*BB, [&](Instruction &I) {
7963 using namespace llvm::PatternMatch;
7964
7965 Value *Condition;
7966 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7967 m_Value(Condition))) &&
7968 isImpliedCond(Pred, LHS, RHS, Condition, false);
7969 });
7970}
7971
Dan Gohmane65c9172009-07-13 21:35:55 +00007972/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7973/// protected by a conditional between LHS and RHS. This is used to
7974/// to eliminate casts.
7975bool
7976ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7977 ICmpInst::Predicate Pred,
7978 const SCEV *LHS, const SCEV *RHS) {
7979 // Interpret a null as meaning no loop, where there is obviously no guard
7980 // (interprocedural conditions notwithstanding).
7981 if (!L) return true;
7982
Sanjoy Das401e6312016-02-01 20:48:10 +00007983 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7984 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007985
Dan Gohmane65c9172009-07-13 21:35:55 +00007986 BasicBlock *Latch = L->getLoopLatch();
7987 if (!Latch)
7988 return false;
7989
7990 BranchInst *LoopContinuePredicate =
7991 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007992 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7993 isImpliedCond(Pred, LHS, RHS,
7994 LoopContinuePredicate->getCondition(),
7995 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7996 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007997
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007998 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007999 // -- that can lead to O(n!) time complexity.
8000 if (WalkingBEDominatingConds)
8001 return false;
8002
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00008003 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008004
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00008005 // See if we can exploit a trip count to prove the predicate.
8006 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8007 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8008 if (LatchBECount != getCouldNotCompute()) {
8009 // We know that Latch branches back to the loop header exactly
8010 // LatchBECount times. This means the backdege condition at Latch is
8011 // equivalent to "{0,+,1} u< LatchBECount".
8012 Type *Ty = LatchBECount->getType();
8013 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8014 const SCEV *LoopCounter =
8015 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8016 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8017 LatchBECount))
8018 return true;
8019 }
8020
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008021 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008022 for (auto &AssumeVH : AC.assumptions()) {
8023 if (!AssumeVH)
8024 continue;
8025 auto *CI = cast<CallInst>(AssumeVH);
8026 if (!DT.dominates(CI, Latch->getTerminator()))
8027 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008028
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008029 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8030 return true;
8031 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008032
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008033 // If the loop is not reachable from the entry block, we risk running into an
8034 // infinite loop as we walk up into the dom tree. These loops do not matter
8035 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008036 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008037 return false;
8038
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008039 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8040 return true;
8041
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008042 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8043 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008044
8045 assert(DTN && "should reach the loop header before reaching the root!");
8046
8047 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008048 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8049 return true;
8050
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008051 BasicBlock *PBB = BB->getSinglePredecessor();
8052 if (!PBB)
8053 continue;
8054
8055 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8056 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8057 continue;
8058
8059 Value *Condition = ContinuePredicate->getCondition();
8060
8061 // If we have an edge `E` within the loop body that dominates the only
8062 // latch, the condition guarding `E` also guards the backedge. This
8063 // reasoning works only for loops with a single latch.
8064
8065 BasicBlockEdge DominatingEdge(PBB, BB);
8066 if (DominatingEdge.isSingleEdge()) {
8067 // We're constructively (and conservatively) enumerating edges within the
8068 // loop body that dominate the latch. The dominator tree better agree
8069 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008070 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008071
8072 if (isImpliedCond(Pred, LHS, RHS, Condition,
8073 BB != ContinuePredicate->getSuccessor(0)))
8074 return true;
8075 }
8076 }
8077
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008078 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008079}
8080
Dan Gohmane65c9172009-07-13 21:35:55 +00008081bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008082ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8083 ICmpInst::Predicate Pred,
8084 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008085 // Interpret a null as meaning no loop, where there is obviously no guard
8086 // (interprocedural conditions notwithstanding).
8087 if (!L) return false;
8088
Sanjoy Das401e6312016-02-01 20:48:10 +00008089 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8090 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008091
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008092 // Starting at the loop predecessor, climb up the predecessor chain, as long
8093 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008094 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008095 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008096 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008097 Pair.first;
8098 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008099
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008100 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8101 return true;
8102
Dan Gohman2a62fd92008-08-12 20:17:31 +00008103 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008104 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008105 if (!LoopEntryPredicate ||
8106 LoopEntryPredicate->isUnconditional())
8107 continue;
8108
Dan Gohmane18c2d62010-08-10 23:46:30 +00008109 if (isImpliedCond(Pred, LHS, RHS,
8110 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008111 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008112 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008113 }
8114
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008115 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008116 for (auto &AssumeVH : AC.assumptions()) {
8117 if (!AssumeVH)
8118 continue;
8119 auto *CI = cast<CallInst>(AssumeVH);
8120 if (!DT.dominates(CI, L->getHeader()))
8121 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008122
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008123 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8124 return true;
8125 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008126
Dan Gohman2a62fd92008-08-12 20:17:31 +00008127 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008128}
8129
Dan Gohmane18c2d62010-08-10 23:46:30 +00008130bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008131 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008132 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008133 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008134 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008135 return false;
8136
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008137 auto ClearOnExit =
8138 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8139
Dan Gohman8b0a4192010-03-01 17:49:51 +00008140 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008142 if (BO->getOpcode() == Instruction::And) {
8143 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008144 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8145 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008146 } else if (BO->getOpcode() == Instruction::Or) {
8147 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008148 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8149 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008150 }
8151 }
8152
Dan Gohmane18c2d62010-08-10 23:46:30 +00008153 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008154 if (!ICI) return false;
8155
Andrew Trickfa594032012-11-29 18:35:13 +00008156 // Now that we found a conditional branch that dominates the loop or controls
8157 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008158 ICmpInst::Predicate FoundPred;
8159 if (Inverse)
8160 FoundPred = ICI->getInversePredicate();
8161 else
8162 FoundPred = ICI->getPredicate();
8163
8164 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8165 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008166
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008167 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8168}
8169
8170bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8171 const SCEV *RHS,
8172 ICmpInst::Predicate FoundPred,
8173 const SCEV *FoundLHS,
8174 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008175 // Balance the types.
8176 if (getTypeSizeInBits(LHS->getType()) <
8177 getTypeSizeInBits(FoundLHS->getType())) {
8178 if (CmpInst::isSigned(Pred)) {
8179 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8180 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8181 } else {
8182 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8183 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8184 }
8185 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008186 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008187 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008188 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8189 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8190 } else {
8191 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8192 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8193 }
8194 }
8195
Dan Gohman430f0cc2009-07-21 23:03:19 +00008196 // Canonicalize the query to match the way instcombine will have
8197 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008198 if (SimplifyICmpOperands(Pred, LHS, RHS))
8199 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008200 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008201 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8202 if (FoundLHS == FoundRHS)
8203 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008204
8205 // Check to see if we can make the LHS or RHS match.
8206 if (LHS == FoundRHS || RHS == FoundLHS) {
8207 if (isa<SCEVConstant>(RHS)) {
8208 std::swap(FoundLHS, FoundRHS);
8209 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8210 } else {
8211 std::swap(LHS, RHS);
8212 Pred = ICmpInst::getSwappedPredicate(Pred);
8213 }
8214 }
8215
8216 // Check whether the found predicate is the same as the desired predicate.
8217 if (FoundPred == Pred)
8218 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8219
8220 // Check whether swapping the found predicate makes it the same as the
8221 // desired predicate.
8222 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8223 if (isa<SCEVConstant>(RHS))
8224 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8225 else
8226 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8227 RHS, LHS, FoundLHS, FoundRHS);
8228 }
8229
Sanjoy Das6e78b172015-10-22 19:57:34 +00008230 // Unsigned comparison is the same as signed comparison when both the operands
8231 // are non-negative.
8232 if (CmpInst::isUnsigned(FoundPred) &&
8233 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8234 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8235 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8236
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008237 // Check if we can make progress by sharpening ranges.
8238 if (FoundPred == ICmpInst::ICMP_NE &&
8239 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8240
8241 const SCEVConstant *C = nullptr;
8242 const SCEV *V = nullptr;
8243
8244 if (isa<SCEVConstant>(FoundLHS)) {
8245 C = cast<SCEVConstant>(FoundLHS);
8246 V = FoundRHS;
8247 } else {
8248 C = cast<SCEVConstant>(FoundRHS);
8249 V = FoundLHS;
8250 }
8251
8252 // The guarding predicate tells us that C != V. If the known range
8253 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8254 // range we consider has to correspond to same signedness as the
8255 // predicate we're interested in folding.
8256
8257 APInt Min = ICmpInst::isSigned(Pred) ?
8258 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8259
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008260 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008261 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8262 // This is true even if (Min + 1) wraps around -- in case of
8263 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8264
8265 APInt SharperMin = Min + 1;
8266
8267 switch (Pred) {
8268 case ICmpInst::ICMP_SGE:
8269 case ICmpInst::ICMP_UGE:
8270 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8271 // RHS, we're done.
8272 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8273 getConstant(SharperMin)))
8274 return true;
8275
8276 case ICmpInst::ICMP_SGT:
8277 case ICmpInst::ICMP_UGT:
8278 // We know from the range information that (V `Pred` Min ||
8279 // V == Min). We know from the guarding condition that !(V
8280 // == Min). This gives us
8281 //
8282 // V `Pred` Min || V == Min && !(V == Min)
8283 // => V `Pred` Min
8284 //
8285 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8286
8287 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8288 return true;
8289
8290 default:
8291 // No change
8292 break;
8293 }
8294 }
8295 }
8296
Dan Gohman430f0cc2009-07-21 23:03:19 +00008297 // Check whether the actual condition is beyond sufficient.
8298 if (FoundPred == ICmpInst::ICMP_EQ)
8299 if (ICmpInst::isTrueWhenEqual(Pred))
8300 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8301 return true;
8302 if (Pred == ICmpInst::ICMP_NE)
8303 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8304 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8305 return true;
8306
8307 // Otherwise assume the worst.
8308 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008309}
8310
Sanjoy Das1ed69102015-10-13 02:53:27 +00008311bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8312 const SCEV *&L, const SCEV *&R,
8313 SCEV::NoWrapFlags &Flags) {
8314 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8315 if (!AE || AE->getNumOperands() != 2)
8316 return false;
8317
8318 L = AE->getOperand(0);
8319 R = AE->getOperand(1);
8320 Flags = AE->getNoWrapFlags();
8321 return true;
8322}
8323
Sanjoy Das0b1af852016-07-23 00:28:56 +00008324Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8325 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008326 // We avoid subtracting expressions here because this function is usually
8327 // fairly deep in the call stack (i.e. is called many times).
8328
Sanjoy Das96709c42015-09-25 23:53:45 +00008329 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8330 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8331 const auto *MAR = cast<SCEVAddRecExpr>(More);
8332
8333 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008334 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008335
8336 // We look at affine expressions only; not for correctness but to keep
8337 // getStepRecurrence cheap.
8338 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008339 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008340
Sanjoy Das1ed69102015-10-13 02:53:27 +00008341 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008342 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008343
8344 Less = LAR->getStart();
8345 More = MAR->getStart();
8346
8347 // fall through
8348 }
8349
8350 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008351 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8352 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008353 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008354 }
8355
8356 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008357 SCEV::NoWrapFlags Flags;
8358 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008359 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008360 if (R == More)
8361 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008362
Sanjoy Das1ed69102015-10-13 02:53:27 +00008363 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008364 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008365 if (R == Less)
8366 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008367
Sanjoy Das0b1af852016-07-23 00:28:56 +00008368 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008369}
8370
8371bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8372 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8373 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8374 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8375 return false;
8376
8377 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8378 if (!AddRecLHS)
8379 return false;
8380
8381 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8382 if (!AddRecFoundLHS)
8383 return false;
8384
8385 // We'd like to let SCEV reason about control dependencies, so we constrain
8386 // both the inequalities to be about add recurrences on the same loop. This
8387 // way we can use isLoopEntryGuardedByCond later.
8388
8389 const Loop *L = AddRecFoundLHS->getLoop();
8390 if (L != AddRecLHS->getLoop())
8391 return false;
8392
8393 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8394 //
8395 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8396 // ... (2)
8397 //
8398 // Informal proof for (2), assuming (1) [*]:
8399 //
8400 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8401 //
8402 // Then
8403 //
8404 // FoundLHS s< FoundRHS s< INT_MIN - C
8405 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8406 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8407 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8408 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8409 // <=> FoundLHS + C s< FoundRHS + C
8410 //
8411 // [*]: (1) can be proved by ruling out overflow.
8412 //
8413 // [**]: This can be proved by analyzing all the four possibilities:
8414 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8415 // (A s>= 0, B s>= 0).
8416 //
8417 // Note:
8418 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8419 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8420 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8421 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8422 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8423 // C)".
8424
Sanjoy Das0b1af852016-07-23 00:28:56 +00008425 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8426 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8427 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008428 return false;
8429
Sanjoy Das0b1af852016-07-23 00:28:56 +00008430 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008431 return true;
8432
Sanjoy Das96709c42015-09-25 23:53:45 +00008433 APInt FoundRHSLimit;
8434
8435 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008436 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008437 } else {
8438 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008439 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008440 }
8441
8442 // Try to prove (1) or (2), as needed.
8443 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8444 getConstant(FoundRHSLimit));
8445}
8446
Dan Gohman430f0cc2009-07-21 23:03:19 +00008447bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8448 const SCEV *LHS, const SCEV *RHS,
8449 const SCEV *FoundLHS,
8450 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008451 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8452 return true;
8453
Sanjoy Das96709c42015-09-25 23:53:45 +00008454 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8455 return true;
8456
Dan Gohman430f0cc2009-07-21 23:03:19 +00008457 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8458 FoundLHS, FoundRHS) ||
8459 // ~x < ~y --> x > y
8460 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8461 getNotSCEV(FoundRHS),
8462 getNotSCEV(FoundLHS));
8463}
8464
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008465
8466/// If Expr computes ~A, return A else return nullptr
8467static const SCEV *MatchNotExpr(const SCEV *Expr) {
8468 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008469 if (!Add || Add->getNumOperands() != 2 ||
8470 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008471 return nullptr;
8472
8473 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008474 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8475 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008476 return nullptr;
8477
8478 return AddRHS->getOperand(1);
8479}
8480
8481
8482/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8483template<typename MaxExprType>
8484static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8485 const SCEV *Candidate) {
8486 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8487 if (!MaxExpr) return false;
8488
Sanjoy Das347d2722015-12-01 07:49:27 +00008489 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008490}
8491
8492
8493/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8494template<typename MaxExprType>
8495static bool IsMinConsistingOf(ScalarEvolution &SE,
8496 const SCEV *MaybeMinExpr,
8497 const SCEV *Candidate) {
8498 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8499 if (!MaybeMaxExpr)
8500 return false;
8501
8502 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8503}
8504
Hal Finkela8d205f2015-08-19 01:51:51 +00008505static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8506 ICmpInst::Predicate Pred,
8507 const SCEV *LHS, const SCEV *RHS) {
8508
8509 // If both sides are affine addrecs for the same loop, with equal
8510 // steps, and we know the recurrences don't wrap, then we only
8511 // need to check the predicate on the starting values.
8512
8513 if (!ICmpInst::isRelational(Pred))
8514 return false;
8515
8516 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8517 if (!LAR)
8518 return false;
8519 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8520 if (!RAR)
8521 return false;
8522 if (LAR->getLoop() != RAR->getLoop())
8523 return false;
8524 if (!LAR->isAffine() || !RAR->isAffine())
8525 return false;
8526
8527 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8528 return false;
8529
Hal Finkelff08a2e2015-08-19 17:26:07 +00008530 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8531 SCEV::FlagNSW : SCEV::FlagNUW;
8532 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008533 return false;
8534
8535 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8536}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008537
8538/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8539/// expression?
8540static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8541 ICmpInst::Predicate Pred,
8542 const SCEV *LHS, const SCEV *RHS) {
8543 switch (Pred) {
8544 default:
8545 return false;
8546
8547 case ICmpInst::ICMP_SGE:
8548 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008549 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008550 case ICmpInst::ICMP_SLE:
8551 return
8552 // min(A, ...) <= A
8553 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8554 // A <= max(A, ...)
8555 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8556
8557 case ICmpInst::ICMP_UGE:
8558 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008559 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008560 case ICmpInst::ICMP_ULE:
8561 return
8562 // min(A, ...) <= A
8563 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8564 // A <= max(A, ...)
8565 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8566 }
8567
8568 llvm_unreachable("covered switch fell through?!");
8569}
8570
Max Kazantsev2e44d292017-03-31 12:05:30 +00008571bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8572 const SCEV *LHS, const SCEV *RHS,
8573 const SCEV *FoundLHS,
8574 const SCEV *FoundRHS,
8575 unsigned Depth) {
8576 assert(getTypeSizeInBits(LHS->getType()) ==
8577 getTypeSizeInBits(RHS->getType()) &&
8578 "LHS and RHS have different sizes?");
8579 assert(getTypeSizeInBits(FoundLHS->getType()) ==
8580 getTypeSizeInBits(FoundRHS->getType()) &&
8581 "FoundLHS and FoundRHS have different sizes?");
8582 // We want to avoid hurting the compile time with analysis of too big trees.
8583 if (Depth > MaxSCEVOperationsImplicationDepth)
8584 return false;
8585 // We only want to work with ICMP_SGT comparison so far.
8586 // TODO: Extend to ICMP_UGT?
8587 if (Pred == ICmpInst::ICMP_SLT) {
8588 Pred = ICmpInst::ICMP_SGT;
8589 std::swap(LHS, RHS);
8590 std::swap(FoundLHS, FoundRHS);
8591 }
8592 if (Pred != ICmpInst::ICMP_SGT)
8593 return false;
8594
8595 auto GetOpFromSExt = [&](const SCEV *S) {
8596 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8597 return Ext->getOperand();
8598 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8599 // the constant in some cases.
8600 return S;
8601 };
8602
8603 // Acquire values from extensions.
8604 auto *OrigFoundLHS = FoundLHS;
8605 LHS = GetOpFromSExt(LHS);
8606 FoundLHS = GetOpFromSExt(FoundLHS);
8607
8608 // Is the SGT predicate can be proved trivially or using the found context.
8609 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8610 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8611 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8612 FoundRHS, Depth + 1);
8613 };
8614
8615 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8616 // We want to avoid creation of any new non-constant SCEV. Since we are
8617 // going to compare the operands to RHS, we should be certain that we don't
8618 // need any size extensions for this. So let's decline all cases when the
8619 // sizes of types of LHS and RHS do not match.
8620 // TODO: Maybe try to get RHS from sext to catch more cases?
8621 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8622 return false;
8623
8624 // Should not overflow.
8625 if (!LHSAddExpr->hasNoSignedWrap())
8626 return false;
8627
8628 auto *LL = LHSAddExpr->getOperand(0);
8629 auto *LR = LHSAddExpr->getOperand(1);
8630 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8631
8632 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8633 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8634 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8635 };
8636 // Try to prove the following rule:
8637 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8638 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8639 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8640 return true;
8641 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8642 Value *LL, *LR;
8643 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8644 using namespace llvm::PatternMatch;
8645 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8646 // Rules for division.
8647 // We are going to perform some comparisons with Denominator and its
8648 // derivative expressions. In general case, creating a SCEV for it may
8649 // lead to a complex analysis of the entire graph, and in particular it
8650 // can request trip count recalculation for the same loop. This would
8651 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8652 // this, we only want to create SCEVs that are constants in this section.
8653 // So we bail if Denominator is not a constant.
8654 if (!isa<ConstantInt>(LR))
8655 return false;
8656
8657 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8658
8659 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8660 // then a SCEV for the numerator already exists and matches with FoundLHS.
8661 auto *Numerator = getExistingSCEV(LL);
8662 if (!Numerator || Numerator->getType() != FoundLHS->getType())
8663 return false;
8664
8665 // Make sure that the numerator matches with FoundLHS and the denominator
8666 // is positive.
8667 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8668 return false;
8669
8670 auto *DTy = Denominator->getType();
8671 auto *FRHSTy = FoundRHS->getType();
8672 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8673 // One of types is a pointer and another one is not. We cannot extend
8674 // them properly to a wider type, so let us just reject this case.
8675 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8676 // to avoid this check.
8677 return false;
8678
8679 // Given that:
8680 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8681 auto *WTy = getWiderType(DTy, FRHSTy);
8682 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8683 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8684
8685 // Try to prove the following rule:
8686 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8687 // For example, given that FoundLHS > 2. It means that FoundLHS is at
8688 // least 3. If we divide it by Denominator < 4, we will have at least 1.
8689 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8690 if (isKnownNonPositive(RHS) &&
8691 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8692 return true;
8693
8694 // Try to prove the following rule:
8695 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8696 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8697 // If we divide it by Denominator > 2, then:
8698 // 1. If FoundLHS is negative, then the result is 0.
8699 // 2. If FoundLHS is non-negative, then the result is non-negative.
8700 // Anyways, the result is non-negative.
8701 auto *MinusOne = getNegativeSCEV(getOne(WTy));
8702 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8703 if (isKnownNegative(RHS) &&
8704 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8705 return true;
8706 }
8707 }
8708
8709 return false;
8710}
8711
8712bool
8713ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8714 const SCEV *LHS, const SCEV *RHS) {
8715 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8716 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8717 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8718 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8719}
8720
Dan Gohmane65c9172009-07-13 21:35:55 +00008721bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008722ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8723 const SCEV *LHS, const SCEV *RHS,
8724 const SCEV *FoundLHS,
8725 const SCEV *FoundRHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008726 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008727 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8728 case ICmpInst::ICMP_EQ:
8729 case ICmpInst::ICMP_NE:
8730 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8731 return true;
8732 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008733 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008734 case ICmpInst::ICMP_SLE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008735 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8736 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008737 return true;
8738 break;
8739 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008740 case ICmpInst::ICMP_SGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008741 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8742 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008743 return true;
8744 break;
8745 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008746 case ICmpInst::ICMP_ULE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008747 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8748 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008749 return true;
8750 break;
8751 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008752 case ICmpInst::ICMP_UGE:
Max Kazantsev2e44d292017-03-31 12:05:30 +00008753 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8754 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008755 return true;
8756 break;
8757 }
8758
Max Kazantsev2e44d292017-03-31 12:05:30 +00008759 // Maybe it can be proved via operations?
8760 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8761 return true;
8762
Dan Gohmane65c9172009-07-13 21:35:55 +00008763 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008764}
8765
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008766bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8767 const SCEV *LHS,
8768 const SCEV *RHS,
8769 const SCEV *FoundLHS,
8770 const SCEV *FoundRHS) {
8771 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8772 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8773 // reduce the compile time impact of this optimization.
8774 return false;
8775
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008776 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008777 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008778 return false;
8779
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008780 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008781
8782 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8783 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8784 ConstantRange FoundLHSRange =
8785 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8786
Sanjoy Das095f5b22016-07-22 20:47:55 +00008787 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8788 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008789
8790 // We can also compute the range of values for `LHS` that satisfy the
8791 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008792 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008793 ConstantRange SatisfyingLHSRange =
8794 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8795
8796 // The antecedent implies the consequent if every value of `LHS` that
8797 // satisfies the antecedent also satisfies the consequent.
8798 return SatisfyingLHSRange.contains(LHSRange);
8799}
8800
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008801bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8802 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008803 assert(isKnownPositive(Stride) && "Positive stride expected!");
8804
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008805 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008806
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008807 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008808 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008809
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008810 if (IsSigned) {
8811 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8812 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8813 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8814 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008815
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008816 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8817 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008818 }
Dan Gohman01048422009-06-21 23:46:38 +00008819
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008820 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8821 APInt MaxValue = APInt::getMaxValue(BitWidth);
8822 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8823 .getUnsignedMax();
8824
8825 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8826 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8827}
8828
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008829bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8830 bool IsSigned, bool NoWrap) {
8831 if (NoWrap) return false;
8832
8833 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008834 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008835
8836 if (IsSigned) {
8837 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8838 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8839 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8840 .getSignedMax();
8841
8842 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8843 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8844 }
8845
8846 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8847 APInt MinValue = APInt::getMinValue(BitWidth);
8848 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8849 .getUnsignedMax();
8850
8851 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8852 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8853}
8854
Johannes Doerfert2683e562015-02-09 12:34:23 +00008855const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008856 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008857 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008858 Delta = Equality ? getAddExpr(Delta, Step)
8859 : getAddExpr(Delta, getMinusSCEV(Step, One));
8860 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008861}
8862
Andrew Trick3ca3f982011-07-26 17:19:55 +00008863ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008864ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008865 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008866 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008867 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008868 // We handle only IV < Invariant
8869 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008870 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008871
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008872 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008873 bool PredicatedIV = false;
8874
8875 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008876 // Try to make this an AddRec using runtime tests, in the first X
8877 // iterations of this loop, where X is the SCEV expression found by the
8878 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008879 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008880 PredicatedIV = true;
8881 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008882
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008883 // Avoid weird loops
8884 if (!IV || IV->getLoop() != L || !IV->isAffine())
8885 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008886
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008887 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008888 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008889
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008890 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008891
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008892 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008893
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008894 // Avoid negative or zero stride values.
8895 if (!PositiveStride) {
8896 // We can compute the correct backedge taken count for loops with unknown
8897 // strides if we can prove that the loop is not an infinite loop with side
8898 // effects. Here's the loop structure we are trying to handle -
8899 //
8900 // i = start
8901 // do {
8902 // A[i] = i;
8903 // i += s;
8904 // } while (i < end);
8905 //
8906 // The backedge taken count for such loops is evaluated as -
8907 // (max(end, start + stride) - start - 1) /u stride
8908 //
8909 // The additional preconditions that we need to check to prove correctness
8910 // of the above formula is as follows -
8911 //
8912 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8913 // NoWrap flag).
8914 // b) loop is single exit with no side effects.
8915 //
8916 //
8917 // Precondition a) implies that if the stride is negative, this is a single
8918 // trip loop. The backedge taken count formula reduces to zero in this case.
8919 //
8920 // Precondition b) implies that the unknown stride cannot be zero otherwise
8921 // we have UB.
8922 //
8923 // The positive stride case is the same as isKnownPositive(Stride) returning
8924 // true (original behavior of the function).
8925 //
8926 // We want to make sure that the stride is truly unknown as there are edge
8927 // cases where ScalarEvolution propagates no wrap flags to the
8928 // post-increment/decrement IV even though the increment/decrement operation
8929 // itself is wrapping. The computed backedge taken count may be wrong in
8930 // such cases. This is prevented by checking that the stride is not known to
8931 // be either positive or non-positive. For example, no wrap flags are
8932 // propagated to the post-increment IV of this loop with a trip count of 2 -
8933 //
8934 // unsigned char i;
8935 // for(i=127; i<128; i+=129)
8936 // A[i] = i;
8937 //
8938 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8939 !loopHasNoSideEffects(L))
8940 return getCouldNotCompute();
8941
8942 } else if (!Stride->isOne() &&
8943 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8944 // Avoid proven overflow cases: this will ensure that the backedge taken
8945 // count will not generate any unsigned overflow. Relaxed no-overflow
8946 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8947 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008948 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008949
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008950 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8951 : ICmpInst::ICMP_ULT;
8952 const SCEV *Start = IV->getStart();
8953 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00008954 // If the backedge is taken at least once, then it will be taken
8955 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8956 // is the LHS value of the less-than comparison the first time it is evaluated
8957 // and End is the RHS.
8958 const SCEV *BECountIfBackedgeTaken =
8959 computeBECount(getMinusSCEV(End, Start), Stride, false);
8960 // If the loop entry is guarded by the result of the backedge test of the
8961 // first loop iteration, then we know the backedge will be taken at least
8962 // once and so the backedge taken count is as above. If not then we use the
8963 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8964 // as if the backedge is taken at least once max(End,Start) is End and so the
8965 // result is as above, and if not max(End,Start) is Start so we get a backedge
8966 // count of zero.
8967 const SCEV *BECount;
8968 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8969 BECount = BECountIfBackedgeTaken;
8970 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008971 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00008972 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8973 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008974
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008975 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00008976 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008977 if (isa<SCEVConstant>(BECount))
8978 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00008979 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00008980 // If we know exactly how many times the backedge will be taken if it's
8981 // taken at least once, then the backedge count will either be that or
8982 // zero.
8983 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00008984 MaxOrZero = true;
8985 } else {
John Brawnecf79302016-10-18 10:10:53 +00008986 // Calculate the maximum backedge count based on the range of values
8987 // permitted by Start, End, and Stride.
8988 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8989 : getUnsignedRange(Start).getUnsignedMin();
8990
8991 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8992
8993 APInt StrideForMaxBECount;
8994
8995 if (PositiveStride)
8996 StrideForMaxBECount =
8997 IsSigned ? getSignedRange(Stride).getSignedMin()
8998 : getUnsignedRange(Stride).getUnsignedMin();
8999 else
9000 // Using a stride of 1 is safe when computing max backedge taken count for
9001 // a loop with unknown stride.
9002 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9003
9004 APInt Limit =
9005 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9006 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9007
9008 // Although End can be a MAX expression we estimate MaxEnd considering only
9009 // the case End = RHS. This is safe because in the other case (End - Start)
9010 // is zero, leading to a zero maximum backedge taken count.
9011 APInt MaxEnd =
9012 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9013 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9014
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009015 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00009016 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00009017 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009018
9019 if (isa<SCEVCouldNotCompute>(MaxBECount))
9020 MaxBECount = BECount;
9021
John Brawn84b21832016-10-21 11:08:48 +00009022 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009023}
9024
9025ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00009026ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009027 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00009028 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00009029 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009030 // We handle only IV > Invariant
9031 if (!isLoopInvariant(RHS, L))
9032 return getCouldNotCompute();
9033
9034 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00009035 if (!IV && AllowPredicates)
9036 // Try to make this an AddRec using runtime tests, in the first X
9037 // iterations of this loop, where X is the SCEV expression found by the
9038 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00009039 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009040
9041 // Avoid weird loops
9042 if (!IV || IV->getLoop() != L || !IV->isAffine())
9043 return getCouldNotCompute();
9044
Mark Heffernan2beab5f2014-10-10 17:39:11 +00009045 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009046 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9047
9048 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9049
9050 // Avoid negative or zero stride values
9051 if (!isKnownPositive(Stride))
9052 return getCouldNotCompute();
9053
9054 // Avoid proven overflow cases: this will ensure that the backedge taken count
9055 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00009056 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009057 // behaviors like the case of C language.
9058 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9059 return getCouldNotCompute();
9060
9061 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9062 : ICmpInst::ICMP_UGT;
9063
9064 const SCEV *Start = IV->getStart();
9065 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00009066 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9067 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009068
9069 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9070
9071 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9072 : getUnsignedRange(Start).getUnsignedMax();
9073
9074 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9075 : getUnsignedRange(Stride).getUnsignedMin();
9076
9077 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9078 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9079 : APInt::getMinValue(BitWidth) + (MinStride - 1);
9080
9081 // Although End can be a MIN expression we estimate MinEnd considering only
9082 // the case End = RHS. This is safe because in the other case (Start - End)
9083 // is zero, leading to a zero maximum backedge taken count.
9084 APInt MinEnd =
9085 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9086 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9087
9088
9089 const SCEV *MaxBECount = getCouldNotCompute();
9090 if (isa<SCEVConstant>(BECount))
9091 MaxBECount = BECount;
9092 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00009093 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00009094 getConstant(MinStride), false);
9095
9096 if (isa<SCEVCouldNotCompute>(MaxBECount))
9097 MaxBECount = BECount;
9098
John Brawn84b21832016-10-21 11:08:48 +00009099 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00009100}
9101
Benjamin Kramerc321e532016-06-08 19:09:22 +00009102const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00009103 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00009104 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00009105 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009106
9107 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00009108 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00009109 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00009110 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009111 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00009112 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00009113 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00009114 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00009115 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009116 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00009117 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00009118 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009119 }
9120
9121 // The only time we can solve this is when we have all constant indices.
9122 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00009123 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00009124 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009125
9126 // Okay at this point we know that all elements of the chrec are constants and
9127 // that the start element is zero.
9128
9129 // First check to see if the range contains zero. If not, the first
9130 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00009131 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00009132 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00009133 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00009134
Chris Lattnerd934c702004-04-02 20:23:17 +00009135 if (isAffine()) {
9136 // If this is an affine expression then we have this situation:
9137 // Solve {0,+,A} in Range === Ax in Range
9138
Nick Lewycky52460262007-07-16 02:08:00 +00009139 // We know that zero is in the range. If A is positive then we know that
9140 // the upper value of the range must be the first possible exit value.
9141 // If A is negative then the lower of the range is the last possible loop
9142 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00009143 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009144 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00009145 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00009146
Nick Lewycky52460262007-07-16 02:08:00 +00009147 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00009148 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00009149 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00009150
9151 // Evaluate at the exit value. If we really did fall out of the valid
9152 // range, then we computed our trip count, otherwise wrap around or other
9153 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00009154 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009155 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00009156 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009157
9158 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00009159 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00009160 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00009161 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00009162 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00009163 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00009164 } else if (isQuadratic()) {
9165 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9166 // quadratic equation to solve it. To do this, we must frame our problem in
9167 // terms of figuring out when zero is crossed, instead of when
9168 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00009169 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00009170 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00009171 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00009172
9173 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00009174 if (auto Roots =
9175 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00009176 const SCEVConstant *R1 = Roots->first;
9177 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00009178 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00009179 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9180 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00009181 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00009182 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00009183
Chris Lattnerd934c702004-04-02 20:23:17 +00009184 // Make sure the root is not off by one. The returned iteration should
9185 // not be in the range, but the previous one should be. When solving
9186 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00009187 ConstantInt *R1Val =
9188 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009189 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009190 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009191 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009192 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009193
Dan Gohmana37eaf22007-10-22 18:31:58 +00009194 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009195 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009196 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00009197 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009198 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009199
Chris Lattnerd934c702004-04-02 20:23:17 +00009200 // If R1 was not in the range, then it is a good return value. Make
9201 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009202 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009203 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009204 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009205 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009206 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00009207 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009208 }
9209 }
9210 }
9211
Dan Gohman31efa302009-04-18 17:58:19 +00009212 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009213}
9214
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009215// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009216static inline bool containsUndefs(const SCEV *S) {
9217 return SCEVExprContains(S, [](const SCEV *S) {
9218 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9219 return isa<UndefValue>(SU->getValue());
9220 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9221 return isa<UndefValue>(SC->getValue());
9222 return false;
9223 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009224}
9225
9226namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009227// Collect all steps of SCEV expressions.
9228struct SCEVCollectStrides {
9229 ScalarEvolution &SE;
9230 SmallVectorImpl<const SCEV *> &Strides;
9231
9232 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9233 : SE(SE), Strides(S) {}
9234
9235 bool follow(const SCEV *S) {
9236 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9237 Strides.push_back(AR->getStepRecurrence(SE));
9238 return true;
9239 }
9240 bool isDone() const { return false; }
9241};
9242
9243// Collect all SCEVUnknown and SCEVMulExpr expressions.
9244struct SCEVCollectTerms {
9245 SmallVectorImpl<const SCEV *> &Terms;
9246
9247 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9248 : Terms(T) {}
9249
9250 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009251 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9252 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009253 if (!containsUndefs(S))
9254 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009255
9256 // Stop recursion: once we collected a term, do not walk its operands.
9257 return false;
9258 }
9259
9260 // Keep looking.
9261 return true;
9262 }
9263 bool isDone() const { return false; }
9264};
Tobias Grosser374bce02015-10-12 08:02:00 +00009265
9266// Check if a SCEV contains an AddRecExpr.
9267struct SCEVHasAddRec {
9268 bool &ContainsAddRec;
9269
9270 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9271 ContainsAddRec = false;
9272 }
9273
9274 bool follow(const SCEV *S) {
9275 if (isa<SCEVAddRecExpr>(S)) {
9276 ContainsAddRec = true;
9277
9278 // Stop recursion: once we collected a term, do not walk its operands.
9279 return false;
9280 }
9281
9282 // Keep looking.
9283 return true;
9284 }
9285 bool isDone() const { return false; }
9286};
9287
9288// Find factors that are multiplied with an expression that (possibly as a
9289// subexpression) contains an AddRecExpr. In the expression:
9290//
9291// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9292//
9293// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9294// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9295// parameters as they form a product with an induction variable.
9296//
9297// This collector expects all array size parameters to be in the same MulExpr.
9298// It might be necessary to later add support for collecting parameters that are
9299// spread over different nested MulExpr.
9300struct SCEVCollectAddRecMultiplies {
9301 SmallVectorImpl<const SCEV *> &Terms;
9302 ScalarEvolution &SE;
9303
9304 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9305 : Terms(T), SE(SE) {}
9306
9307 bool follow(const SCEV *S) {
9308 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9309 bool HasAddRec = false;
9310 SmallVector<const SCEV *, 0> Operands;
9311 for (auto Op : Mul->operands()) {
9312 if (isa<SCEVUnknown>(Op)) {
9313 Operands.push_back(Op);
9314 } else {
9315 bool ContainsAddRec;
9316 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9317 visitAll(Op, ContiansAddRec);
9318 HasAddRec |= ContainsAddRec;
9319 }
9320 }
9321 if (Operands.size() == 0)
9322 return true;
9323
9324 if (!HasAddRec)
9325 return false;
9326
9327 Terms.push_back(SE.getMulExpr(Operands));
9328 // Stop recursion: once we collected a term, do not walk its operands.
9329 return false;
9330 }
9331
9332 // Keep looking.
9333 return true;
9334 }
9335 bool isDone() const { return false; }
9336};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009337}
Sebastian Pop448712b2014-05-07 18:01:20 +00009338
Tobias Grosser374bce02015-10-12 08:02:00 +00009339/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9340/// two places:
9341/// 1) The strides of AddRec expressions.
9342/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009343void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9344 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009345 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009346 SCEVCollectStrides StrideCollector(*this, Strides);
9347 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009348
9349 DEBUG({
9350 dbgs() << "Strides:\n";
9351 for (const SCEV *S : Strides)
9352 dbgs() << *S << "\n";
9353 });
9354
9355 for (const SCEV *S : Strides) {
9356 SCEVCollectTerms TermCollector(Terms);
9357 visitAll(S, TermCollector);
9358 }
9359
9360 DEBUG({
9361 dbgs() << "Terms:\n";
9362 for (const SCEV *T : Terms)
9363 dbgs() << *T << "\n";
9364 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009365
9366 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9367 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009368}
9369
Sebastian Popb1a548f2014-05-12 19:01:53 +00009370static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009371 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009372 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009373 int Last = Terms.size() - 1;
9374 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009375
Sebastian Pop448712b2014-05-07 18:01:20 +00009376 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009377 if (Last == 0) {
9378 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009379 SmallVector<const SCEV *, 2> Qs;
9380 for (const SCEV *Op : M->operands())
9381 if (!isa<SCEVConstant>(Op))
9382 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009383
Sebastian Pope30bd352014-05-27 22:41:56 +00009384 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009385 }
9386
Sebastian Pope30bd352014-05-27 22:41:56 +00009387 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009388 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009389 }
9390
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009391 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009392 // Normalize the terms before the next call to findArrayDimensionsRec.
9393 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009394 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009395
9396 // Bail out when GCD does not evenly divide one of the terms.
9397 if (!R->isZero())
9398 return false;
9399
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009400 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009401 }
9402
Tobias Grosser3080cf12014-05-08 07:55:34 +00009403 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009404 Terms.erase(
9405 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9406 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009407
Sebastian Pop448712b2014-05-07 18:01:20 +00009408 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009409 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9410 return false;
9411
Sebastian Pope30bd352014-05-27 22:41:56 +00009412 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009413 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009414}
Sebastian Popc62c6792013-11-12 22:47:20 +00009415
Sebastian Pop448712b2014-05-07 18:01:20 +00009416
9417// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009418static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009419 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009420 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009421 return true;
9422 return false;
9423}
9424
9425// Return the number of product terms in S.
9426static inline int numberOfTerms(const SCEV *S) {
9427 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9428 return Expr->getNumOperands();
9429 return 1;
9430}
9431
Sebastian Popa6e58602014-05-27 22:41:45 +00009432static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9433 if (isa<SCEVConstant>(T))
9434 return nullptr;
9435
9436 if (isa<SCEVUnknown>(T))
9437 return T;
9438
9439 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9440 SmallVector<const SCEV *, 2> Factors;
9441 for (const SCEV *Op : M->operands())
9442 if (!isa<SCEVConstant>(Op))
9443 Factors.push_back(Op);
9444
9445 return SE.getMulExpr(Factors);
9446 }
9447
9448 return T;
9449}
9450
9451/// Return the size of an element read or written by Inst.
9452const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9453 Type *Ty;
9454 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9455 Ty = Store->getValueOperand()->getType();
9456 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009457 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009458 else
9459 return nullptr;
9460
9461 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9462 return getSizeOfExpr(ETy, Ty);
9463}
9464
Sebastian Popa6e58602014-05-27 22:41:45 +00009465void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9466 SmallVectorImpl<const SCEV *> &Sizes,
9467 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009468 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009469 return;
9470
9471 // Early return when Terms do not contain parameters: we do not delinearize
9472 // non parametric SCEVs.
9473 if (!containsParameters(Terms))
9474 return;
9475
9476 DEBUG({
9477 dbgs() << "Terms:\n";
9478 for (const SCEV *T : Terms)
9479 dbgs() << *T << "\n";
9480 });
9481
9482 // Remove duplicates.
9483 std::sort(Terms.begin(), Terms.end());
9484 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9485
9486 // Put larger terms first.
9487 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9488 return numberOfTerms(LHS) > numberOfTerms(RHS);
9489 });
9490
Sebastian Popa6e58602014-05-27 22:41:45 +00009491 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9492
Tobias Grosser374bce02015-10-12 08:02:00 +00009493 // Try to divide all terms by the element size. If term is not divisible by
9494 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009495 for (const SCEV *&Term : Terms) {
9496 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009497 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009498 if (!Q->isZero())
9499 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009500 }
9501
9502 SmallVector<const SCEV *, 4> NewTerms;
9503
9504 // Remove constant factors.
9505 for (const SCEV *T : Terms)
9506 if (const SCEV *NewT = removeConstantFactors(SE, T))
9507 NewTerms.push_back(NewT);
9508
Sebastian Pop448712b2014-05-07 18:01:20 +00009509 DEBUG({
9510 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009511 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009512 dbgs() << *T << "\n";
9513 });
9514
Sebastian Popa6e58602014-05-27 22:41:45 +00009515 if (NewTerms.empty() ||
9516 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009517 Sizes.clear();
9518 return;
9519 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009520
Sebastian Popa6e58602014-05-27 22:41:45 +00009521 // The last element to be pushed into Sizes is the size of an element.
9522 Sizes.push_back(ElementSize);
9523
Sebastian Pop448712b2014-05-07 18:01:20 +00009524 DEBUG({
9525 dbgs() << "Sizes:\n";
9526 for (const SCEV *S : Sizes)
9527 dbgs() << *S << "\n";
9528 });
9529}
9530
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009531void ScalarEvolution::computeAccessFunctions(
9532 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9533 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009534
Sebastian Popb1a548f2014-05-12 19:01:53 +00009535 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009536 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009537 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009538
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009539 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009540 if (!AR->isAffine())
9541 return;
9542
9543 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009544 int Last = Sizes.size() - 1;
9545 for (int i = Last; i >= 0; i--) {
9546 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009547 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009548
9549 DEBUG({
9550 dbgs() << "Res: " << *Res << "\n";
9551 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9552 dbgs() << "Res divided by Sizes[i]:\n";
9553 dbgs() << "Quotient: " << *Q << "\n";
9554 dbgs() << "Remainder: " << *R << "\n";
9555 });
9556
9557 Res = Q;
9558
Sebastian Popa6e58602014-05-27 22:41:45 +00009559 // Do not record the last subscript corresponding to the size of elements in
9560 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009561 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009562
9563 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009564 if (isa<SCEVAddRecExpr>(R)) {
9565 Subscripts.clear();
9566 Sizes.clear();
9567 return;
9568 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009569
Sebastian Pop448712b2014-05-07 18:01:20 +00009570 continue;
9571 }
9572
9573 // Record the access function for the current subscript.
9574 Subscripts.push_back(R);
9575 }
9576
9577 // Also push in last position the remainder of the last division: it will be
9578 // the access function of the innermost dimension.
9579 Subscripts.push_back(Res);
9580
9581 std::reverse(Subscripts.begin(), Subscripts.end());
9582
9583 DEBUG({
9584 dbgs() << "Subscripts:\n";
9585 for (const SCEV *S : Subscripts)
9586 dbgs() << *S << "\n";
9587 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009588}
9589
Sebastian Popc62c6792013-11-12 22:47:20 +00009590/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9591/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009592/// is the offset start of the array. The SCEV->delinearize algorithm computes
9593/// the multiples of SCEV coefficients: that is a pattern matching of sub
9594/// expressions in the stride and base of a SCEV corresponding to the
9595/// computation of a GCD (greatest common divisor) of base and stride. When
9596/// SCEV->delinearize fails, it returns the SCEV unchanged.
9597///
9598/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9599///
9600/// void foo(long n, long m, long o, double A[n][m][o]) {
9601///
9602/// for (long i = 0; i < n; i++)
9603/// for (long j = 0; j < m; j++)
9604/// for (long k = 0; k < o; k++)
9605/// A[i][j][k] = 1.0;
9606/// }
9607///
9608/// the delinearization input is the following AddRec SCEV:
9609///
9610/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9611///
9612/// From this SCEV, we are able to say that the base offset of the access is %A
9613/// because it appears as an offset that does not divide any of the strides in
9614/// the loops:
9615///
9616/// CHECK: Base offset: %A
9617///
9618/// and then SCEV->delinearize determines the size of some of the dimensions of
9619/// the array as these are the multiples by which the strides are happening:
9620///
9621/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9622///
9623/// Note that the outermost dimension remains of UnknownSize because there are
9624/// no strides that would help identifying the size of the last dimension: when
9625/// the array has been statically allocated, one could compute the size of that
9626/// dimension by dividing the overall size of the array by the size of the known
9627/// dimensions: %m * %o * 8.
9628///
9629/// Finally delinearize provides the access functions for the array reference
9630/// that does correspond to A[i][j][k] of the above C testcase:
9631///
9632/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9633///
9634/// The testcases are checking the output of a function pass:
9635/// DelinearizationPass that walks through all loads and stores of a function
9636/// asking for the SCEV of the memory access with respect to all enclosing
9637/// loops, calling SCEV->delinearize on that and printing the results.
9638
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009639void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009640 SmallVectorImpl<const SCEV *> &Subscripts,
9641 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009642 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009643 // First step: collect parametric terms.
9644 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009645 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009646
Sebastian Popb1a548f2014-05-12 19:01:53 +00009647 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009648 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009649
Sebastian Pop448712b2014-05-07 18:01:20 +00009650 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009651 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009652
Sebastian Popb1a548f2014-05-12 19:01:53 +00009653 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009654 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009655
Sebastian Pop448712b2014-05-07 18:01:20 +00009656 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009657 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009658
Sebastian Pop28e6b972014-05-27 22:41:51 +00009659 if (Subscripts.empty())
9660 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009661
Sebastian Pop448712b2014-05-07 18:01:20 +00009662 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009663 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009664 dbgs() << "ArrayDecl[UnknownSize]";
9665 for (const SCEV *S : Sizes)
9666 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009667
Sebastian Pop444621a2014-05-09 22:45:02 +00009668 dbgs() << "\nArrayRef";
9669 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009670 dbgs() << "[" << *S << "]";
9671 dbgs() << "\n";
9672 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009673}
Chris Lattnerd934c702004-04-02 20:23:17 +00009674
9675//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009676// SCEVCallbackVH Class Implementation
9677//===----------------------------------------------------------------------===//
9678
Dan Gohmand33a0902009-05-19 19:22:47 +00009679void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009680 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009681 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9682 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009683 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009684 // this now dangles!
9685}
9686
Dan Gohman7a066722010-07-28 01:09:07 +00009687void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009688 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009689
Dan Gohman48f82222009-05-04 22:30:44 +00009690 // Forget all the expressions associated with users of the old value,
9691 // so that future queries will recompute the expressions using the new
9692 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009693 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009694 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009695 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009696 while (!Worklist.empty()) {
9697 User *U = Worklist.pop_back_val();
9698 // Deleting the Old value will cause this to dangle. Postpone
9699 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009700 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009701 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009702 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009703 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009704 if (PHINode *PN = dyn_cast<PHINode>(U))
9705 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009706 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009707 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009708 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009709 // Delete the Old value.
9710 if (PHINode *PN = dyn_cast<PHINode>(Old))
9711 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009712 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009713 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009714}
9715
Dan Gohmand33a0902009-05-19 19:22:47 +00009716ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009717 : CallbackVH(V), SE(se) {}
9718
9719//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009720// ScalarEvolution Class Implementation
9721//===----------------------------------------------------------------------===//
9722
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009723ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009724 AssumptionCache &AC, DominatorTree &DT,
9725 LoopInfo &LI)
9726 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009727 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009728 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9729 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009730 FirstUnknown(nullptr) {
9731
9732 // To use guards for proving predicates, we need to scan every instruction in
9733 // relevant basic blocks, and not just terminators. Doing this is a waste of
9734 // time if the IR does not actually contain any calls to
9735 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9736 //
9737 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9738 // to _add_ guards to the module when there weren't any before, and wants
9739 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9740 // efficient in lieu of being smart in that rather obscure case.
9741
9742 auto *GuardDecl = F.getParent()->getFunction(
9743 Intrinsic::getName(Intrinsic::experimental_guard));
9744 HasGuards = GuardDecl && !GuardDecl->use_empty();
9745}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009746
9747ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009748 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009749 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009750 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009751 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009752 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Igor Laevskyc11c1ed2017-02-14 15:53:12 +00009753 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009754 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009755 PredicatedBackedgeTakenCounts(
9756 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009757 ConstantEvolutionLoopExitValue(
9758 std::move(Arg.ConstantEvolutionLoopExitValue)),
9759 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9760 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009761 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009762 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009763 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9764 SignedRanges(std::move(Arg.SignedRanges)),
9765 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009766 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009767 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9768 FirstUnknown(Arg.FirstUnknown) {
9769 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009770}
9771
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009772ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009773 // Iterate through all the SCEVUnknown instances and call their
9774 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009775 for (SCEVUnknown *U = FirstUnknown; U;) {
9776 SCEVUnknown *Tmp = U;
9777 U = U->Next;
9778 Tmp->~SCEVUnknown();
9779 }
Craig Topper9f008862014-04-15 04:59:12 +00009780 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009781
Wei Mia49559b2016-02-04 01:27:38 +00009782 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009783 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009784 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009785
9786 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9787 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009788 for (auto &BTCI : BackedgeTakenCounts)
9789 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009790 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9791 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009792
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009793 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009794 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009795 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009796}
9797
Dan Gohmanc8e23622009-04-21 23:15:49 +00009798bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009799 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009800}
9801
Dan Gohmanc8e23622009-04-21 23:15:49 +00009802static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009803 const Loop *L) {
9804 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009805 for (Loop *I : *L)
9806 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009807
Dan Gohmanbc694912010-01-09 18:17:45 +00009808 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009809 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009810 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009811
Dan Gohmancb0efec2009-12-18 01:14:11 +00009812 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009813 L->getExitBlocks(ExitBlocks);
9814 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009815 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009816
Dan Gohman0bddac12009-02-24 18:55:53 +00009817 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9818 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009819 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009820 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009821 }
9822
Dan Gohmanbc694912010-01-09 18:17:45 +00009823 OS << "\n"
9824 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009825 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009826 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009827
9828 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9829 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009830 if (SE->isBackedgeTakenCountMaxOrZero(L))
9831 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009832 } else {
9833 OS << "Unpredictable max backedge-taken count. ";
9834 }
9835
Silviu Baranga6f444df2016-04-08 14:29:09 +00009836 OS << "\n"
9837 "Loop ";
9838 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9839 OS << ": ";
9840
9841 SCEVUnionPredicate Pred;
9842 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9843 if (!isa<SCEVCouldNotCompute>(PBT)) {
9844 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9845 OS << " Predicates:\n";
9846 Pred.print(OS, 4);
9847 } else {
9848 OS << "Unpredictable predicated backedge-taken count. ";
9849 }
Dan Gohman69942932009-06-24 00:33:16 +00009850 OS << "\n";
Eli Friedmanb1578d32017-03-20 20:25:46 +00009851
9852 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9853 OS << "Loop ";
9854 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9855 OS << ": ";
9856 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
9857 }
Chris Lattnerd934c702004-04-02 20:23:17 +00009858}
9859
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009860static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9861 switch (LD) {
9862 case ScalarEvolution::LoopVariant:
9863 return "Variant";
9864 case ScalarEvolution::LoopInvariant:
9865 return "Invariant";
9866 case ScalarEvolution::LoopComputable:
9867 return "Computable";
9868 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009869 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009870}
9871
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009872void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009873 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009874 // out SCEV values of all instructions that are interesting. Doing
9875 // this potentially causes it to create new SCEV objects though,
9876 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009877 // observable from outside the class though, so casting away the
9878 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009879 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009880
Dan Gohmanbc694912010-01-09 18:17:45 +00009881 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009882 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009883 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009884 for (Instruction &I : instructions(F))
9885 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9886 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009887 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009888 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009889 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009890 if (!isa<SCEVCouldNotCompute>(SV)) {
9891 OS << " U: ";
9892 SE.getUnsignedRange(SV).print(OS);
9893 OS << " S: ";
9894 SE.getSignedRange(SV).print(OS);
9895 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009896
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009897 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009898
Dan Gohmanaf752342009-07-07 17:06:11 +00009899 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009900 if (AtUse != SV) {
9901 OS << " --> ";
9902 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009903 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9904 OS << " U: ";
9905 SE.getUnsignedRange(AtUse).print(OS);
9906 OS << " S: ";
9907 SE.getSignedRange(AtUse).print(OS);
9908 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009909 }
9910
9911 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009912 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009913 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009914 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009915 OS << "<<Unknown>>";
9916 } else {
9917 OS << *ExitValue;
9918 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009919
9920 bool First = true;
9921 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9922 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009923 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009924 First = false;
9925 } else {
9926 OS << ", ";
9927 }
9928
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009929 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9930 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009931 }
9932
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009933 for (auto *InnerL : depth_first(L)) {
9934 if (InnerL == L)
9935 continue;
9936 if (First) {
9937 OS << "\t\t" "LoopDispositions: { ";
9938 First = false;
9939 } else {
9940 OS << ", ";
9941 }
9942
9943 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9944 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9945 }
9946
9947 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009948 }
9949
Chris Lattnerd934c702004-04-02 20:23:17 +00009950 OS << "\n";
9951 }
9952
Dan Gohmanbc694912010-01-09 18:17:45 +00009953 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009954 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009955 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009956 for (Loop *I : LI)
9957 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009958}
Dan Gohmane20f8242009-04-21 00:47:46 +00009959
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009960ScalarEvolution::LoopDisposition
9961ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009962 auto &Values = LoopDispositions[S];
9963 for (auto &V : Values) {
9964 if (V.getPointer() == L)
9965 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009966 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009967 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009968 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009969 auto &Values2 = LoopDispositions[S];
9970 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9971 if (V.getPointer() == L) {
9972 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009973 break;
9974 }
9975 }
9976 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009977}
9978
9979ScalarEvolution::LoopDisposition
9980ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009981 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009982 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009983 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009984 case scTruncate:
9985 case scZeroExtend:
9986 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009987 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009988 case scAddRecExpr: {
9989 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9990
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009991 // If L is the addrec's loop, it's computable.
9992 if (AR->getLoop() == L)
9993 return LoopComputable;
9994
Dan Gohmanafd6db92010-11-17 21:23:15 +00009995 // Add recurrences are never invariant in the function-body (null loop).
9996 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009997 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009998
9999 // This recurrence is variant w.r.t. L if L contains AR's loop.
10000 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010001 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010002
10003 // This recurrence is invariant w.r.t. L if AR's loop contains L.
10004 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010005 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010006
10007 // This recurrence is variant w.r.t. L if any of its operands
10008 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +000010009 for (auto *Op : AR->operands())
10010 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010011 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010012
10013 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010014 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010015 }
10016 case scAddExpr:
10017 case scMulExpr:
10018 case scUMaxExpr:
10019 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +000010020 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +000010021 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10022 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010023 if (D == LoopVariant)
10024 return LoopVariant;
10025 if (D == LoopComputable)
10026 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010027 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010028 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010029 }
10030 case scUDivExpr: {
10031 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010032 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10033 if (LD == LoopVariant)
10034 return LoopVariant;
10035 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10036 if (RD == LoopVariant)
10037 return LoopVariant;
10038 return (LD == LoopInvariant && RD == LoopInvariant) ?
10039 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010040 }
10041 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010042 // All non-instruction values are loop invariant. All instructions are loop
10043 // invariant if they are not contained in the specified loop.
10044 // Instructions are never considered invariant in the function body
10045 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +000010046 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010047 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10048 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010049 case scCouldNotCompute:
10050 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +000010051 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010052 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +000010053}
10054
10055bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10056 return getLoopDisposition(S, L) == LoopInvariant;
10057}
10058
10059bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10060 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +000010061}
Dan Gohman20d9ce22010-11-17 21:41:58 +000010062
Dan Gohman8ea83d82010-11-18 00:34:22 +000010063ScalarEvolution::BlockDisposition
10064ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010065 auto &Values = BlockDispositions[S];
10066 for (auto &V : Values) {
10067 if (V.getPointer() == BB)
10068 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010069 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010070 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010071 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +000010072 auto &Values2 = BlockDispositions[S];
10073 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10074 if (V.getPointer() == BB) {
10075 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +000010076 break;
10077 }
10078 }
10079 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010080}
10081
Dan Gohman8ea83d82010-11-18 00:34:22 +000010082ScalarEvolution::BlockDisposition
10083ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +000010084 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +000010085 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010086 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010087 case scTruncate:
10088 case scZeroExtend:
10089 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +000010090 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +000010091 case scAddRecExpr: {
10092 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +000010093 // to test for proper dominance too, because the instruction which
10094 // produces the addrec's value is a PHI, and a PHI effectively properly
10095 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +000010096 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010097 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010098 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +000010099
10100 // Fall through into SCEVNAryExpr handling.
10101 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010102 }
Dan Gohman20d9ce22010-11-17 21:41:58 +000010103 case scAddExpr:
10104 case scMulExpr:
10105 case scUMaxExpr:
10106 case scSMaxExpr: {
10107 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010108 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +000010109 for (const SCEV *NAryOp : NAry->operands()) {
10110 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010111 if (D == DoesNotDominateBlock)
10112 return DoesNotDominateBlock;
10113 if (D == DominatesBlock)
10114 Proper = false;
10115 }
10116 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010117 }
10118 case scUDivExpr: {
10119 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010120 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10121 BlockDisposition LD = getBlockDisposition(LHS, BB);
10122 if (LD == DoesNotDominateBlock)
10123 return DoesNotDominateBlock;
10124 BlockDisposition RD = getBlockDisposition(RHS, BB);
10125 if (RD == DoesNotDominateBlock)
10126 return DoesNotDominateBlock;
10127 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10128 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010129 }
10130 case scUnknown:
10131 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +000010132 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10133 if (I->getParent() == BB)
10134 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010135 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010136 return ProperlyDominatesBlock;
10137 return DoesNotDominateBlock;
10138 }
10139 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010140 case scCouldNotCompute:
10141 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +000010142 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010143 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +000010144}
10145
10146bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10147 return getBlockDisposition(S, BB) >= DominatesBlock;
10148}
10149
10150bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10151 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010152}
Dan Gohman534749b2010-11-17 22:27:42 +000010153
10154bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +000010155 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +000010156}
Dan Gohman7e6b3932010-11-17 23:28:48 +000010157
10158void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10159 ValuesAtScopes.erase(S);
10160 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010161 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010162 UnsignedRanges.erase(S);
10163 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +000010164 ExprValueMap.erase(S);
10165 HasRecMap.erase(S);
Igor Laevskyc11c1ed2017-02-14 15:53:12 +000010166 MinTrailingZerosCache.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +000010167
Silviu Baranga6f444df2016-04-08 14:29:09 +000010168 auto RemoveSCEVFromBackedgeMap =
10169 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10170 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10171 BackedgeTakenInfo &BEInfo = I->second;
10172 if (BEInfo.hasOperand(S, this)) {
10173 BEInfo.clear();
10174 Map.erase(I++);
10175 } else
10176 ++I;
10177 }
10178 };
10179
10180 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10181 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010182}
Benjamin Kramer214935e2012-10-26 17:31:32 +000010183
10184typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010185
Alp Tokercb402912014-01-24 17:20:08 +000010186/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010187static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10188 size_t Pos = 0;
10189 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10190 Str.replace(Pos, From.size(), To.data(), To.size());
10191 Pos += To.size();
10192 }
10193}
10194
Benjamin Kramer214935e2012-10-26 17:31:32 +000010195/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10196static void
10197getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010198 std::string &S = Map[L];
10199 if (S.empty()) {
10200 raw_string_ostream OS(S);
10201 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010202
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010203 // false and 0 are semantically equivalent. This can happen in dead loops.
10204 replaceSubString(OS.str(), "false", "0");
10205 // Remove wrap flags, their use in SCEV is highly fragile.
10206 // FIXME: Remove this when SCEV gets smarter about them.
10207 replaceSubString(OS.str(), "<nw>", "");
10208 replaceSubString(OS.str(), "<nsw>", "");
10209 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010210 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010211
JF Bastien61ad8b32015-12-23 18:18:53 +000010212 for (auto *R : reverse(*L))
10213 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010214}
10215
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010216void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010217 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10218
10219 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10220 // FIXME: It would be much better to store actual values instead of strings,
10221 // but SCEV pointers will change if we drop the caches.
10222 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010223 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010224 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10225
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010226 // Gather stringified backedge taken counts for all loops using a fresh
10227 // ScalarEvolution object.
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010228 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010229 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10230 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010231
10232 // Now compare whether they're the same with and without caches. This allows
10233 // verifying that no pass changed the cache.
10234 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10235 "New loops suddenly appeared!");
10236
10237 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10238 OldE = BackedgeDumpsOld.end(),
10239 NewI = BackedgeDumpsNew.begin();
10240 OldI != OldE; ++OldI, ++NewI) {
10241 assert(OldI->first == NewI->first && "Loop order changed!");
10242
10243 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10244 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010245 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010246 // means that a pass is buggy or SCEV has to learn a new pattern but is
10247 // usually not harmful.
10248 if (OldI->second != NewI->second &&
10249 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010250 NewI->second.find("undef") == std::string::npos &&
10251 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010252 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010253 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010254 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010255 << "' changed from '" << OldI->second
10256 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010257 std::abort();
10258 }
10259 }
10260
10261 // TODO: Verify more things.
10262}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010263
Chandler Carruth082c1832017-01-09 07:44:34 +000010264bool ScalarEvolution::invalidate(
10265 Function &F, const PreservedAnalyses &PA,
10266 FunctionAnalysisManager::Invalidator &Inv) {
10267 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10268 // of its dependencies is invalidated.
10269 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10270 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10271 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10272 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10273 Inv.invalidate<LoopAnalysis>(F, PA);
10274}
10275
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010276AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010277
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010278ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010279 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010280 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010281 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010282 AM.getResult<DominatorTreeAnalysis>(F),
10283 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010284}
10285
10286PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010287ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010288 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010289 return PreservedAnalyses::all();
10290}
10291
10292INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10293 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010294INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010295INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10296INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10297INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10298INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10299 "Scalar Evolution Analysis", false, true)
10300char ScalarEvolutionWrapperPass::ID = 0;
10301
10302ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10303 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10304}
10305
10306bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10307 SE.reset(new ScalarEvolution(
10308 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010309 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010310 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10311 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10312 return false;
10313}
10314
10315void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10316
10317void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10318 SE->print(OS);
10319}
10320
10321void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10322 if (!VerifySCEV)
10323 return;
10324
10325 SE->verify();
10326}
10327
10328void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10329 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010330 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010331 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10332 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10333 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10334}
Silviu Barangae3c05342015-11-02 14:41:02 +000010335
10336const SCEVPredicate *
10337ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10338 const SCEVConstant *RHS) {
10339 FoldingSetNodeID ID;
10340 // Unique this node based on the arguments
10341 ID.AddInteger(SCEVPredicate::P_Equal);
10342 ID.AddPointer(LHS);
10343 ID.AddPointer(RHS);
10344 void *IP = nullptr;
10345 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10346 return S;
10347 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10348 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10349 UniquePreds.InsertNode(Eq, IP);
10350 return Eq;
10351}
10352
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010353const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10354 const SCEVAddRecExpr *AR,
10355 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10356 FoldingSetNodeID ID;
10357 // Unique this node based on the arguments
10358 ID.AddInteger(SCEVPredicate::P_Wrap);
10359 ID.AddPointer(AR);
10360 ID.AddInteger(AddedFlags);
10361 void *IP = nullptr;
10362 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10363 return S;
10364 auto *OF = new (SCEVAllocator)
10365 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10366 UniquePreds.InsertNode(OF, IP);
10367 return OF;
10368}
10369
Benjamin Kramer83709b12015-11-16 09:01:28 +000010370namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010371
Silviu Barangae3c05342015-11-02 14:41:02 +000010372class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10373public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010374 /// Rewrites \p S in the context of a loop L and the SCEV predication
10375 /// infrastructure.
10376 ///
10377 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10378 /// equivalences present in \p Pred.
10379 ///
10380 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10381 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010382 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010383 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10384 SCEVUnionPredicate *Pred) {
10385 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010386 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010387 }
10388
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010389 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010390 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10391 SCEVUnionPredicate *Pred)
10392 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010393
10394 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010395 if (Pred) {
10396 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10397 for (auto *Pred : ExprPreds)
10398 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10399 if (IPred->getLHS() == Expr)
10400 return IPred->getRHS();
10401 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010402
10403 return Expr;
10404 }
10405
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010406 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10407 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010408 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010409 if (AR && AR->getLoop() == L && AR->isAffine()) {
10410 // This couldn't be folded because the operand didn't have the nuw
10411 // flag. Add the nusw flag as an assumption that we could make.
10412 const SCEV *Step = AR->getStepRecurrence(SE);
10413 Type *Ty = Expr->getType();
10414 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10415 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10416 SE.getSignExtendExpr(Step, Ty), L,
10417 AR->getNoWrapFlags());
10418 }
10419 return SE.getZeroExtendExpr(Operand, Expr->getType());
10420 }
10421
10422 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10423 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010424 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010425 if (AR && AR->getLoop() == L && AR->isAffine()) {
10426 // This couldn't be folded because the operand didn't have the nsw
10427 // flag. Add the nssw flag as an assumption that we could make.
10428 const SCEV *Step = AR->getStepRecurrence(SE);
10429 Type *Ty = Expr->getType();
10430 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10431 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10432 SE.getSignExtendExpr(Step, Ty), L,
10433 AR->getNoWrapFlags());
10434 }
10435 return SE.getSignExtendExpr(Operand, Expr->getType());
10436 }
10437
Silviu Barangae3c05342015-11-02 14:41:02 +000010438private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010439 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10440 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10441 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010442 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010443 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010444 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010445 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010446 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010447 return true;
10448 }
10449
Sanjoy Dasf0022122016-09-28 17:14:58 +000010450 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10451 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010452 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010453};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010454} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010455
Sanjoy Das807d33d2016-02-20 01:44:10 +000010456const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010457 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010458 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010459}
10460
Sanjoy Dasf0022122016-09-28 17:14:58 +000010461const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10462 const SCEV *S, const Loop *L,
10463 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10464
10465 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10466 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010467 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10468
10469 if (!AddRec)
10470 return nullptr;
10471
10472 // Since the transformation was successful, we can now transfer the SCEV
10473 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010474 for (auto *P : TransformPreds)
10475 Preds.insert(P);
10476
Silviu Barangad68ed852016-03-23 15:29:30 +000010477 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010478}
10479
10480/// SCEV predicates
10481SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10482 SCEVPredicateKind Kind)
10483 : FastID(ID), Kind(Kind) {}
10484
10485SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10486 const SCEVUnknown *LHS,
10487 const SCEVConstant *RHS)
10488 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10489
10490bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010491 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010492
10493 if (!Op)
10494 return false;
10495
10496 return Op->LHS == LHS && Op->RHS == RHS;
10497}
10498
10499bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10500
10501const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10502
10503void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10504 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10505}
10506
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010507SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10508 const SCEVAddRecExpr *AR,
10509 IncrementWrapFlags Flags)
10510 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10511
10512const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10513
10514bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10515 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10516
10517 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10518}
10519
10520bool SCEVWrapPredicate::isAlwaysTrue() const {
10521 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10522 IncrementWrapFlags IFlags = Flags;
10523
10524 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10525 IFlags = clearFlags(IFlags, IncrementNSSW);
10526
10527 return IFlags == IncrementAnyWrap;
10528}
10529
10530void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10531 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10532 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10533 OS << "<nusw>";
10534 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10535 OS << "<nssw>";
10536 OS << "\n";
10537}
10538
10539SCEVWrapPredicate::IncrementWrapFlags
10540SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10541 ScalarEvolution &SE) {
10542 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10543 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10544
10545 // We can safely transfer the NSW flag as NSSW.
10546 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10547 ImpliedFlags = IncrementNSSW;
10548
10549 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10550 // If the increment is positive, the SCEV NUW flag will also imply the
10551 // WrapPredicate NUSW flag.
10552 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10553 if (Step->getValue()->getValue().isNonNegative())
10554 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10555 }
10556
10557 return ImpliedFlags;
10558}
10559
Silviu Barangae3c05342015-11-02 14:41:02 +000010560/// Union predicates don't get cached so create a dummy set ID for it.
10561SCEVUnionPredicate::SCEVUnionPredicate()
10562 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10563
10564bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010565 return all_of(Preds,
10566 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010567}
10568
10569ArrayRef<const SCEVPredicate *>
10570SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10571 auto I = SCEVToPreds.find(Expr);
10572 if (I == SCEVToPreds.end())
10573 return ArrayRef<const SCEVPredicate *>();
10574 return I->second;
10575}
10576
10577bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010578 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010579 return all_of(Set->Preds,
10580 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010581
10582 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10583 if (ScevPredsIt == SCEVToPreds.end())
10584 return false;
10585 auto &SCEVPreds = ScevPredsIt->second;
10586
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010587 return any_of(SCEVPreds,
10588 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010589}
10590
10591const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10592
10593void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10594 for (auto Pred : Preds)
10595 Pred->print(OS, Depth);
10596}
10597
10598void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010599 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010600 for (auto Pred : Set->Preds)
10601 add(Pred);
10602 return;
10603 }
10604
10605 if (implies(N))
10606 return;
10607
10608 const SCEV *Key = N->getExpr();
10609 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10610 " associated expression!");
10611
10612 SCEVToPreds[Key].push_back(N);
10613 Preds.push_back(N);
10614}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010615
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010616PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10617 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010618 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010619
10620const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10621 const SCEV *Expr = SE.getSCEV(V);
10622 RewriteEntry &Entry = RewriteMap[Expr];
10623
10624 // If we already have an entry and the version matches, return it.
10625 if (Entry.second && Generation == Entry.first)
10626 return Entry.second;
10627
10628 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010629 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010630 if (Entry.second)
10631 Expr = Entry.second;
10632
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010633 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010634 Entry = {Generation, NewSCEV};
10635
10636 return NewSCEV;
10637}
10638
Silviu Baranga6f444df2016-04-08 14:29:09 +000010639const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10640 if (!BackedgeCount) {
10641 SCEVUnionPredicate BackedgePred;
10642 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10643 addPredicate(BackedgePred);
10644 }
10645 return BackedgeCount;
10646}
10647
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010648void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10649 if (Preds.implies(&Pred))
10650 return;
10651 Preds.add(&Pred);
10652 updateGeneration();
10653}
10654
10655const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10656 return Preds;
10657}
10658
10659void PredicatedScalarEvolution::updateGeneration() {
10660 // If the generation number wrapped recompute everything.
10661 if (++Generation == 0) {
10662 for (auto &II : RewriteMap) {
10663 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010664 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010665 }
10666 }
10667}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010668
10669void PredicatedScalarEvolution::setNoOverflow(
10670 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10671 const SCEV *Expr = getSCEV(V);
10672 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10673
10674 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10675
10676 // Clear the statically implied flags.
10677 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10678 addPredicate(*SE.getWrapPredicate(AR, Flags));
10679
10680 auto II = FlagsMap.insert({V, Flags});
10681 if (!II.second)
10682 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10683}
10684
10685bool PredicatedScalarEvolution::hasNoOverflow(
10686 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10687 const SCEV *Expr = getSCEV(V);
10688 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10689
10690 Flags = SCEVWrapPredicate::clearFlags(
10691 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10692
10693 auto II = FlagsMap.find(V);
10694
10695 if (II != FlagsMap.end())
10696 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10697
10698 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10699}
10700
Silviu Barangad68ed852016-03-23 15:29:30 +000010701const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010702 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010703 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10704 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010705
10706 if (!New)
10707 return nullptr;
10708
Sanjoy Dasf0022122016-09-28 17:14:58 +000010709 for (auto *P : NewPreds)
10710 Preds.add(P);
10711
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010712 updateGeneration();
10713 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10714 return New;
10715}
10716
Silviu Baranga6f444df2016-04-08 14:29:09 +000010717PredicatedScalarEvolution::PredicatedScalarEvolution(
10718 const PredicatedScalarEvolution &Init)
10719 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10720 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010721 for (const auto &I : Init.FlagsMap)
10722 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010723}
Silviu Barangab77365b2016-04-14 16:08:45 +000010724
10725void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10726 // For each block.
10727 for (auto *BB : L.getBlocks())
10728 for (auto &I : *BB) {
10729 if (!SE.isSCEVable(I.getType()))
10730 continue;
10731
10732 auto *Expr = SE.getSCEV(&I);
10733 auto II = RewriteMap.find(Expr);
10734
10735 if (II == RewriteMap.end())
10736 continue;
10737
10738 // Don't print things that are not interesting.
10739 if (II->second.second == Expr)
10740 continue;
10741
10742 OS.indent(Depth) << "[PSE]" << I << ":\n";
10743 OS.indent(Depth + 2) << *Expr << "\n";
10744 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10745 }
10746}