blob: 3a99f2a2157d5e708a54b94e3b8dd675e16bb904 [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"
Hal Finkel3ca4a6b2016-12-15 03:02:15 +000067#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000068#include "llvm/ADT/Statistic.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 Fukalov4c3322c2016-11-17 16:07:52 +0000130static cl::opt<unsigned>
131 MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden,
132 cl::desc("Maximum depth of recursive compare complexity"),
133 cl::init(32));
134
Chris Lattnerd934c702004-04-02 20:23:17 +0000135//===----------------------------------------------------------------------===//
136// SCEV class definitions
137//===----------------------------------------------------------------------===//
138
139//===----------------------------------------------------------------------===//
140// Implementation of the SCEV class.
141//
Dan Gohman3423e722009-06-30 20:13:32 +0000142
Davide Italiano2071f4c2015-10-25 19:55:24 +0000143LLVM_DUMP_METHOD
144void SCEV::dump() const {
145 print(dbgs());
146 dbgs() << '\n';
147}
148
Dan Gohman534749b2010-11-17 22:27:42 +0000149void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000150 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000151 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000152 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000153 return;
154 case scTruncate: {
155 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
156 const SCEV *Op = Trunc->getOperand();
157 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
158 << *Trunc->getType() << ")";
159 return;
160 }
161 case scZeroExtend: {
162 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
163 const SCEV *Op = ZExt->getOperand();
164 OS << "(zext " << *Op->getType() << " " << *Op << " to "
165 << *ZExt->getType() << ")";
166 return;
167 }
168 case scSignExtend: {
169 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
170 const SCEV *Op = SExt->getOperand();
171 OS << "(sext " << *Op->getType() << " " << *Op << " to "
172 << *SExt->getType() << ")";
173 return;
174 }
175 case scAddRecExpr: {
176 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
177 OS << "{" << *AR->getOperand(0);
178 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
179 OS << ",+," << *AR->getOperand(i);
180 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000181 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000182 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000183 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000184 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000185 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000186 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
187 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000188 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000189 OS << ">";
190 return;
191 }
192 case scAddExpr:
193 case scMulExpr:
194 case scUMaxExpr:
195 case scSMaxExpr: {
196 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000197 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000198 switch (NAry->getSCEVType()) {
199 case scAddExpr: OpStr = " + "; break;
200 case scMulExpr: OpStr = " * "; break;
201 case scUMaxExpr: OpStr = " umax "; break;
202 case scSMaxExpr: OpStr = " smax "; break;
203 }
204 OS << "(";
205 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
206 I != E; ++I) {
207 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000208 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000209 OS << OpStr;
210 }
211 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000212 switch (NAry->getSCEVType()) {
213 case scAddExpr:
214 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000215 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000216 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000217 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000218 OS << "<nsw>";
219 }
Dan Gohman534749b2010-11-17 22:27:42 +0000220 return;
221 }
222 case scUDivExpr: {
223 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
224 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
225 return;
226 }
227 case scUnknown: {
228 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000229 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000230 if (U->isSizeOf(AllocTy)) {
231 OS << "sizeof(" << *AllocTy << ")";
232 return;
233 }
234 if (U->isAlignOf(AllocTy)) {
235 OS << "alignof(" << *AllocTy << ")";
236 return;
237 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000238
Chris Lattner229907c2011-07-18 04:54:35 +0000239 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000240 Constant *FieldNo;
241 if (U->isOffsetOf(CTy, FieldNo)) {
242 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000243 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000244 OS << ")";
245 return;
246 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000247
Dan Gohman534749b2010-11-17 22:27:42 +0000248 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000249 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000250 return;
251 }
252 case scCouldNotCompute:
253 OS << "***COULDNOTCOMPUTE***";
254 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000255 }
256 llvm_unreachable("Unknown SCEV kind!");
257}
258
Chris Lattner229907c2011-07-18 04:54:35 +0000259Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000260 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000261 case scConstant:
262 return cast<SCEVConstant>(this)->getType();
263 case scTruncate:
264 case scZeroExtend:
265 case scSignExtend:
266 return cast<SCEVCastExpr>(this)->getType();
267 case scAddRecExpr:
268 case scMulExpr:
269 case scUMaxExpr:
270 case scSMaxExpr:
271 return cast<SCEVNAryExpr>(this)->getType();
272 case scAddExpr:
273 return cast<SCEVAddExpr>(this)->getType();
274 case scUDivExpr:
275 return cast<SCEVUDivExpr>(this)->getType();
276 case scUnknown:
277 return cast<SCEVUnknown>(this)->getType();
278 case scCouldNotCompute:
279 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000280 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000281 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000282}
283
Dan Gohmanbe928e32008-06-18 16:23:07 +0000284bool SCEV::isZero() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isZero();
287 return false;
288}
289
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000290bool SCEV::isOne() const {
291 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
292 return SC->getValue()->isOne();
293 return false;
294}
Chris Lattnerd934c702004-04-02 20:23:17 +0000295
Dan Gohman18a96bb2009-06-24 00:30:26 +0000296bool SCEV::isAllOnesValue() const {
297 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
298 return SC->getValue()->isAllOnesValue();
299 return false;
300}
301
Andrew Trick881a7762012-01-07 00:27:31 +0000302bool SCEV::isNonConstantNegative() const {
303 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
304 if (!Mul) return false;
305
306 // If there is a constant factor, it will be first.
307 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
308 if (!SC) return false;
309
310 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000311 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000312}
313
Owen Anderson04052ec2009-06-22 21:57:23 +0000314SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000315 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316
Chris Lattnerd934c702004-04-02 20:23:17 +0000317bool SCEVCouldNotCompute::classof(const SCEV *S) {
318 return S->getSCEVType() == scCouldNotCompute;
319}
320
Dan Gohmanaf752342009-07-07 17:06:11 +0000321const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000322 FoldingSetNodeID ID;
323 ID.AddInteger(scConstant);
324 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000325 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000326 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000327 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000328 UniqueSCEVs.InsertNode(S, IP);
329 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000330}
Chris Lattnerd934c702004-04-02 20:23:17 +0000331
Nick Lewycky31eaca52014-01-27 10:04:03 +0000332const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000333 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000334}
335
Dan Gohmanaf752342009-07-07 17:06:11 +0000336const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000337ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
338 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000339 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000340}
341
Dan Gohman24ceda82010-06-18 19:54:20 +0000342SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000343 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000344 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000345
Dan Gohman24ceda82010-06-18 19:54:20 +0000346SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000347 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000348 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000349 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
350 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000351 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000352}
Chris Lattnerd934c702004-04-02 20:23:17 +0000353
Dan Gohman24ceda82010-06-18 19:54:20 +0000354SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000355 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000356 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000357 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
358 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000359 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000360}
361
Dan Gohman24ceda82010-06-18 19:54:20 +0000362SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000363 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000364 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000365 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
366 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000367 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000368}
369
Dan Gohman7cac9572010-08-02 23:49:30 +0000370void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000371 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000372 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000373
374 // Remove this SCEVUnknown from the uniquing map.
375 SE->UniqueSCEVs.RemoveNode(this);
376
377 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000378 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000379}
380
381void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000382 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000383 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000384
385 // Remove this SCEVUnknown from the uniquing map.
386 SE->UniqueSCEVs.RemoveNode(this);
387
388 // Update this SCEVUnknown to point to the new value. This is needed
389 // because there may still be outstanding SCEVs which still point to
390 // this SCEVUnknown.
391 setValPtr(New);
392}
393
Chris Lattner229907c2011-07-18 04:54:35 +0000394bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
402 if (CI->isOne()) {
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 ->getElementType();
405 return true;
406 }
Dan Gohmancf913832010-01-28 02:15:55 +0000407
408 return false;
409}
410
Chris Lattner229907c2011-07-18 04:54:35 +0000411bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000417 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000419 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
424 if (CI->isOne() &&
425 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000426 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000427 AllocTy = STy->getElementType(1);
428 return true;
429 }
430 }
431 }
Dan Gohmancf913832010-01-28 02:15:55 +0000432
433 return false;
434}
435
Chris Lattner229907c2011-07-18 04:54:35 +0000436bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000444 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000448 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000449 CTy = Ty;
450 FieldNo = CE->getOperand(2);
451 return true;
452 }
453 }
454
455 return false;
456}
457
Chris Lattnereb3e8402004-06-20 06:23:15 +0000458//===----------------------------------------------------------------------===//
459// SCEV Utilities
460//===----------------------------------------------------------------------===//
461
Sanjoy Das17078692016-10-31 03:32:43 +0000462/// Compare the two values \p LV and \p RV in terms of their "complexity" where
463/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
464/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
465/// have been previously deemed to be "equally complex" by this routine. It is
466/// intended to avoid exponential time complexity in cases like:
467///
468/// %a = f(%x, %y)
469/// %b = f(%a, %a)
470/// %c = f(%b, %b)
471///
472/// %d = f(%x, %y)
473/// %e = f(%d, %d)
474/// %f = f(%e, %e)
475///
476/// CompareValueComplexity(%f, %c)
477///
478/// Since we do not continue running this routine on expression trees once we
479/// have seen unequal values, there is no need to track them in the cache.
480static int
481CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
482 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000483 unsigned Depth) {
484 if (Depth > MaxCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000485 return 0;
486
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000487 // Order pointer values after integer values. This helps SCEVExpander form
488 // GEPs.
489 bool LIsPointer = LV->getType()->isPointerTy(),
490 RIsPointer = RV->getType()->isPointerTy();
491 if (LIsPointer != RIsPointer)
492 return (int)LIsPointer - (int)RIsPointer;
493
494 // Compare getValueID values.
495 unsigned LID = LV->getValueID(), RID = RV->getValueID();
496 if (LID != RID)
497 return (int)LID - (int)RID;
498
499 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000500 if (const auto *LA = dyn_cast<Argument>(LV)) {
501 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000502 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
503 return (int)LArgNo - (int)RArgNo;
504 }
505
Sanjoy Das299e6722016-10-30 23:52:56 +0000506 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
507 const auto *RGV = cast<GlobalValue>(RV);
508
509 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
510 auto LT = GV->getLinkage();
511 return !(GlobalValue::isPrivateLinkage(LT) ||
512 GlobalValue::isInternalLinkage(LT));
513 };
514
515 // Use the names to distinguish the two values, but only if the
516 // names are semantically important.
517 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
518 return LGV->getName().compare(RGV->getName());
519 }
520
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000521 // For instructions, compare their loop depth, and their operand count. This
522 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000523 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
524 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000525
526 // Compare loop depths.
527 const BasicBlock *LParent = LInst->getParent(),
528 *RParent = RInst->getParent();
529 if (LParent != RParent) {
530 unsigned LDepth = LI->getLoopDepth(LParent),
531 RDepth = LI->getLoopDepth(RParent);
532 if (LDepth != RDepth)
533 return (int)LDepth - (int)RDepth;
534 }
535
536 // Compare the number of operands.
537 unsigned LNumOps = LInst->getNumOperands(),
538 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000539 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000540 return (int)LNumOps - (int)RNumOps;
541
Sanjoy Das17078692016-10-31 03:32:43 +0000542 for (unsigned Idx : seq(0u, LNumOps)) {
543 int Result =
544 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000545 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000546 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000547 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000548 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000549 }
550
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000551 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000552 return 0;
553}
554
Sanjoy Das237c8452016-09-27 18:01:48 +0000555// Return negative, zero, or positive, if LHS is less than, equal to, or greater
556// than RHS, respectively. A three-way result allows recursive comparisons to be
557// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000558static int CompareSCEVComplexity(
559 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
560 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
561 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000562 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
563 if (LHS == RHS)
564 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000565
Sanjoy Das237c8452016-09-27 18:01:48 +0000566 // Primarily, sort the SCEVs by their getSCEVType().
567 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
568 if (LType != RType)
569 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000570
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000571 if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS}))
572 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000573 // Aside from the getSCEVType() ordering, the particular ordering
574 // isn't very important except that it's beneficial to be consistent,
575 // so that (a + b) and (b + a) don't end up as different expressions.
576 switch (static_cast<SCEVTypes>(LType)) {
577 case scUnknown: {
578 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
579 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000580
Sanjoy Das17078692016-10-31 03:32:43 +0000581 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000582 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
583 Depth + 1);
584 if (X == 0)
585 EqCacheSCEV.insert({LHS, RHS});
586 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000587 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000588
Sanjoy Das237c8452016-09-27 18:01:48 +0000589 case scConstant: {
590 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
591 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
592
593 // Compare constant values.
594 const APInt &LA = LC->getAPInt();
595 const APInt &RA = RC->getAPInt();
596 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
597 if (LBitWidth != RBitWidth)
598 return (int)LBitWidth - (int)RBitWidth;
599 return LA.ult(RA) ? -1 : 1;
600 }
601
602 case scAddRecExpr: {
603 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
604 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
605
606 // Compare addrec loop depths.
607 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
608 if (LLoop != RLoop) {
609 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
610 if (LDepth != RDepth)
611 return (int)LDepth - (int)RDepth;
612 }
613
614 // Addrec complexity grows with operand count.
615 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
616 if (LNumOps != RNumOps)
617 return (int)LNumOps - (int)RNumOps;
618
619 // Lexicographically compare.
620 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000621 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
622 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000623 if (X != 0)
624 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000625 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000626 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000627 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000628 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000629
630 case scAddExpr:
631 case scMulExpr:
632 case scSMaxExpr:
633 case scUMaxExpr: {
634 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
635 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
636
637 // Lexicographically compare n-ary expressions.
638 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
639 if (LNumOps != RNumOps)
640 return (int)LNumOps - (int)RNumOps;
641
642 for (unsigned i = 0; i != LNumOps; ++i) {
643 if (i >= RNumOps)
644 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000645 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
646 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000647 if (X != 0)
648 return X;
649 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000650 EqCacheSCEV.insert({LHS, RHS});
651 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000652 }
653
654 case scUDivExpr: {
655 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
656 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
657
658 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000659 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
660 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000661 if (X != 0)
662 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000663 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
664 Depth + 1);
665 if (X == 0)
666 EqCacheSCEV.insert({LHS, RHS});
667 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000668 }
669
670 case scTruncate:
671 case scZeroExtend:
672 case scSignExtend: {
673 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
674 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
675
676 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000677 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
678 RC->getOperand(), Depth + 1);
679 if (X == 0)
680 EqCacheSCEV.insert({LHS, RHS});
681 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000682 }
683
684 case scCouldNotCompute:
685 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
686 }
687 llvm_unreachable("Unknown SCEV kind!");
688}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000689
Sanjoy Dasf8570812016-05-29 00:38:22 +0000690/// Given a list of SCEV objects, order them by their complexity, and group
691/// objects of the same complexity together by value. When this routine is
692/// finished, we know that any duplicates in the vector are consecutive and that
693/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000694///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000695/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000696/// results from this routine. In other words, we don't want the results of
697/// this to depend on where the addresses of various SCEV objects happened to
698/// land in memory.
699///
Dan Gohmanaf752342009-07-07 17:06:11 +0000700static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000701 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000702 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000703
704 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000705 if (Ops.size() == 2) {
706 // This is the common case, which also happens to be trivially simple.
707 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000708 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000709 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000710 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000711 return;
712 }
713
Dan Gohman24ceda82010-06-18 19:54:20 +0000714 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000715 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000716 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
717 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000718 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000719
720 // Now that we are sorted by complexity, group elements of the same
721 // complexity. Note that this is, at worst, N^2, but the vector is likely to
722 // be extremely short in practice. Note that we take this approach because we
723 // do not want to depend on the addresses of the objects we are grouping.
724 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
725 const SCEV *S = Ops[i];
726 unsigned Complexity = S->getSCEVType();
727
728 // If there are any objects of the same complexity and same value as this
729 // one, group them.
730 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
731 if (Ops[j] == S) { // Found a duplicate.
732 // Move it to immediately after i'th element.
733 std::swap(Ops[i+1], Ops[j]);
734 ++i; // no need to rescan it.
735 if (i == e-2) return; // Done!
736 }
737 }
738 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000739}
740
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000741// Returns the size of the SCEV S.
742static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000743 struct FindSCEVSize {
744 int Size;
745 FindSCEVSize() : Size(0) {}
746
747 bool follow(const SCEV *S) {
748 ++Size;
749 // Keep looking at all operands of S.
750 return true;
751 }
752 bool isDone() const {
753 return false;
754 }
755 };
756
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000757 FindSCEVSize F;
758 SCEVTraversal<FindSCEVSize> ST(F);
759 ST.visitAll(S);
760 return F.Size;
761}
762
763namespace {
764
David Majnemer4e879362014-12-14 09:12:33 +0000765struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000766public:
767 // Computes the Quotient and Remainder of the division of Numerator by
768 // Denominator.
769 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
770 const SCEV *Denominator, const SCEV **Quotient,
771 const SCEV **Remainder) {
772 assert(Numerator && Denominator && "Uninitialized SCEV");
773
David Majnemer4e879362014-12-14 09:12:33 +0000774 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000775
776 // Check for the trivial case here to avoid having to check for it in the
777 // rest of the code.
778 if (Numerator == Denominator) {
779 *Quotient = D.One;
780 *Remainder = D.Zero;
781 return;
782 }
783
784 if (Numerator->isZero()) {
785 *Quotient = D.Zero;
786 *Remainder = D.Zero;
787 return;
788 }
789
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000790 // A simple case when N/1. The quotient is N.
791 if (Denominator->isOne()) {
792 *Quotient = Numerator;
793 *Remainder = D.Zero;
794 return;
795 }
796
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000798 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000799 const SCEV *Q, *R;
800 *Quotient = Numerator;
801 for (const SCEV *Op : T->operands()) {
802 divide(SE, *Quotient, Op, &Q, &R);
803 *Quotient = Q;
804
805 // Bail out when the Numerator is not divisible by one of the terms of
806 // the Denominator.
807 if (!R->isZero()) {
808 *Quotient = D.Zero;
809 *Remainder = Numerator;
810 return;
811 }
812 }
813 *Remainder = D.Zero;
814 return;
815 }
816
817 D.visit(Numerator);
818 *Quotient = D.Quotient;
819 *Remainder = D.Remainder;
820 }
821
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000822 // Except in the trivial case described above, we do not know how to divide
823 // Expr by Denominator for the following functions with empty implementation.
824 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
825 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
826 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
827 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
828 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
829 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
830 void visitUnknown(const SCEVUnknown *Numerator) {}
831 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
832
David Majnemer4e879362014-12-14 09:12:33 +0000833 void visitConstant(const SCEVConstant *Numerator) {
834 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000835 APInt NumeratorVal = Numerator->getAPInt();
836 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000837 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
838 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
839
840 if (NumeratorBW > DenominatorBW)
841 DenominatorVal = DenominatorVal.sext(NumeratorBW);
842 else if (NumeratorBW < DenominatorBW)
843 NumeratorVal = NumeratorVal.sext(DenominatorBW);
844
845 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
846 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
847 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
848 Quotient = SE.getConstant(QuotientVal);
849 Remainder = SE.getConstant(RemainderVal);
850 return;
851 }
852 }
853
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000854 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
855 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000856 if (!Numerator->isAffine())
857 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000858 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
859 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000860 // Bail out if the types do not match.
861 Type *Ty = Denominator->getType();
862 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000863 Ty != StepQ->getType() || Ty != StepR->getType())
864 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000865 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
866 Numerator->getNoWrapFlags());
867 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
868 Numerator->getNoWrapFlags());
869 }
870
871 void visitAddExpr(const SCEVAddExpr *Numerator) {
872 SmallVector<const SCEV *, 2> Qs, Rs;
873 Type *Ty = Denominator->getType();
874
875 for (const SCEV *Op : Numerator->operands()) {
876 const SCEV *Q, *R;
877 divide(SE, Op, Denominator, &Q, &R);
878
879 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000880 if (Ty != Q->getType() || Ty != R->getType())
881 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000882
883 Qs.push_back(Q);
884 Rs.push_back(R);
885 }
886
887 if (Qs.size() == 1) {
888 Quotient = Qs[0];
889 Remainder = Rs[0];
890 return;
891 }
892
893 Quotient = SE.getAddExpr(Qs);
894 Remainder = SE.getAddExpr(Rs);
895 }
896
897 void visitMulExpr(const SCEVMulExpr *Numerator) {
898 SmallVector<const SCEV *, 2> Qs;
899 Type *Ty = Denominator->getType();
900
901 bool FoundDenominatorTerm = false;
902 for (const SCEV *Op : Numerator->operands()) {
903 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000904 if (Ty != Op->getType())
905 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000906
907 if (FoundDenominatorTerm) {
908 Qs.push_back(Op);
909 continue;
910 }
911
912 // Check whether Denominator divides one of the product operands.
913 const SCEV *Q, *R;
914 divide(SE, Op, Denominator, &Q, &R);
915 if (!R->isZero()) {
916 Qs.push_back(Op);
917 continue;
918 }
919
920 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000921 if (Ty != Q->getType())
922 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000923
924 FoundDenominatorTerm = true;
925 Qs.push_back(Q);
926 }
927
928 if (FoundDenominatorTerm) {
929 Remainder = Zero;
930 if (Qs.size() == 1)
931 Quotient = Qs[0];
932 else
933 Quotient = SE.getMulExpr(Qs);
934 return;
935 }
936
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000937 if (!isa<SCEVUnknown>(Denominator))
938 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000939
940 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
941 ValueToValueMap RewriteMap;
942 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
943 cast<SCEVConstant>(Zero)->getValue();
944 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
945
946 if (Remainder->isZero()) {
947 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
948 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
949 cast<SCEVConstant>(One)->getValue();
950 Quotient =
951 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
952 return;
953 }
954
955 // Quotient is (Numerator - Remainder) divided by Denominator.
956 const SCEV *Q, *R;
957 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000958 // This SCEV does not seem to simplify: fail the division here.
959 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
960 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000961 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000962 if (R != Zero)
963 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000964 Quotient = Q;
965 }
966
967private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000968 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
969 const SCEV *Denominator)
970 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000971 Zero = SE.getZero(Denominator->getType());
972 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000973
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000974 // We generally do not know how to divide Expr by Denominator. We
975 // initialize the division to a "cannot divide" state to simplify the rest
976 // of the code.
977 cannotDivide(Numerator);
978 }
979
980 // Convenience function for giving up on the division. We set the quotient to
981 // be equal to zero and the remainder to be equal to the numerator.
982 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000983 Quotient = Zero;
984 Remainder = Numerator;
985 }
986
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000987 ScalarEvolution &SE;
988 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000989};
990
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000991}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000992
Chris Lattnerd934c702004-04-02 20:23:17 +0000993//===----------------------------------------------------------------------===//
994// Simple SCEV method implementations
995//===----------------------------------------------------------------------===//
996
Sanjoy Dasf8570812016-05-29 00:38:22 +0000997/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000998static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000999 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001000 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001001 // Handle the simplest case efficiently.
1002 if (K == 1)
1003 return SE.getTruncateOrZeroExtend(It, ResultTy);
1004
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001005 // We are using the following formula for BC(It, K):
1006 //
1007 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1008 //
Eli Friedman61f67622008-08-04 23:49:06 +00001009 // Suppose, W is the bitwidth of the return value. We must be prepared for
1010 // overflow. Hence, we must assure that the result of our computation is
1011 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1012 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001013 //
Eli Friedman61f67622008-08-04 23:49:06 +00001014 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001015 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001016 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1017 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001018 //
Eli Friedman61f67622008-08-04 23:49:06 +00001019 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001020 //
Eli Friedman61f67622008-08-04 23:49:06 +00001021 // This formula is trivially equivalent to the previous formula. However,
1022 // this formula can be implemented much more efficiently. The trick is that
1023 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1024 // arithmetic. To do exact division in modular arithmetic, all we have
1025 // to do is multiply by the inverse. Therefore, this step can be done at
1026 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001027 //
Eli Friedman61f67622008-08-04 23:49:06 +00001028 // The next issue is how to safely do the division by 2^T. The way this
1029 // is done is by doing the multiplication step at a width of at least W + T
1030 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1031 // when we perform the division by 2^T (which is equivalent to a right shift
1032 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1033 // truncated out after the division by 2^T.
1034 //
1035 // In comparison to just directly using the first formula, this technique
1036 // is much more efficient; using the first formula requires W * K bits,
1037 // but this formula less than W + K bits. Also, the first formula requires
1038 // a division step, whereas this formula only requires multiplies and shifts.
1039 //
1040 // It doesn't matter whether the subtraction step is done in the calculation
1041 // width or the input iteration count's width; if the subtraction overflows,
1042 // the result must be zero anyway. We prefer here to do it in the width of
1043 // the induction variable because it helps a lot for certain cases; CodeGen
1044 // isn't smart enough to ignore the overflow, which leads to much less
1045 // efficient code if the width of the subtraction is wider than the native
1046 // register width.
1047 //
1048 // (It's possible to not widen at all by pulling out factors of 2 before
1049 // the multiplication; for example, K=2 can be calculated as
1050 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1051 // extra arithmetic, so it's not an obvious win, and it gets
1052 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001053
Eli Friedman61f67622008-08-04 23:49:06 +00001054 // Protection from insane SCEVs; this bound is conservative,
1055 // but it probably doesn't matter.
1056 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001057 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001058
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001059 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001060
Eli Friedman61f67622008-08-04 23:49:06 +00001061 // Calculate K! / 2^T and T; we divide out the factors of two before
1062 // multiplying for calculating K! / 2^T to avoid overflow.
1063 // Other overflow doesn't matter because we only care about the bottom
1064 // W bits of the result.
1065 APInt OddFactorial(W, 1);
1066 unsigned T = 1;
1067 for (unsigned i = 3; i <= K; ++i) {
1068 APInt Mult(W, i);
1069 unsigned TwoFactors = Mult.countTrailingZeros();
1070 T += TwoFactors;
1071 Mult = Mult.lshr(TwoFactors);
1072 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001073 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001074
Eli Friedman61f67622008-08-04 23:49:06 +00001075 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001076 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001077
Dan Gohman8b0a4192010-03-01 17:49:51 +00001078 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001079 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001080
1081 // Calculate the multiplicative inverse of K! / 2^T;
1082 // this multiplication factor will perform the exact division by
1083 // K! / 2^T.
1084 APInt Mod = APInt::getSignedMinValue(W+1);
1085 APInt MultiplyFactor = OddFactorial.zext(W+1);
1086 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1087 MultiplyFactor = MultiplyFactor.trunc(W);
1088
1089 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001090 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001091 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001092 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001093 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001094 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001095 Dividend = SE.getMulExpr(Dividend,
1096 SE.getTruncateOrZeroExtend(S, CalculationTy));
1097 }
1098
1099 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001100 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001101
1102 // Truncate the result, and divide by K! / 2^T.
1103
1104 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1105 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001106}
1107
Sanjoy Dasf8570812016-05-29 00:38:22 +00001108/// Return the value of this chain of recurrences at the specified iteration
1109/// number. We can evaluate this recurrence by multiplying each element in the
1110/// chain by the binomial coefficient corresponding to it. In other words, we
1111/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001112///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001113/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001114///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001115/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001116///
Dan Gohmanaf752342009-07-07 17:06:11 +00001117const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001118 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001119 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001121 // The computation is correct in the face of overflow provided that the
1122 // multiplication is performed _after_ the evaluation of the binomial
1123 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001124 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001125 if (isa<SCEVCouldNotCompute>(Coeff))
1126 return Coeff;
1127
1128 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001129 }
1130 return Result;
1131}
1132
Chris Lattnerd934c702004-04-02 20:23:17 +00001133//===----------------------------------------------------------------------===//
1134// SCEV Expression folder implementations
1135//===----------------------------------------------------------------------===//
1136
Dan Gohmanaf752342009-07-07 17:06:11 +00001137const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001138 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001139 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001140 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001141 assert(isSCEVable(Ty) &&
1142 "This is not a conversion to a SCEVable type!");
1143 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001144
Dan Gohman3a302cb2009-07-13 20:50:19 +00001145 FoldingSetNodeID ID;
1146 ID.AddInteger(scTruncate);
1147 ID.AddPointer(Op);
1148 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001149 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001150 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1151
Dan Gohman3423e722009-06-30 20:13:32 +00001152 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001154 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001156
Dan Gohman79af8542009-04-22 16:20:48 +00001157 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001158 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001159 return getTruncateExpr(ST->getOperand(), Ty);
1160
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001162 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001163 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1164
1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001166 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1168
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001169 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001170 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001171 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1172 SmallVector<const SCEV *, 4> Operands;
1173 bool hasTrunc = false;
1174 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1175 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001176 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1177 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001178 Operands.push_back(S);
1179 }
1180 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001181 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001182 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001183 }
1184
Nick Lewycky5c901f32011-01-19 18:56:00 +00001185 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001186 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001187 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1188 SmallVector<const SCEV *, 4> Operands;
1189 bool hasTrunc = false;
1190 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1191 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001192 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1193 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001194 Operands.push_back(S);
1195 }
1196 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001197 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001198 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001199 }
1200
Dan Gohman5a728c92009-06-18 16:24:47 +00001201 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001202 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001203 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001204 for (const SCEV *Op : AddRec->operands())
1205 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001206 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001207 }
1208
Dan Gohman89dd42a2010-06-25 18:47:08 +00001209 // The cast wasn't folded; create an explicit cast node. We can reuse
1210 // the existing insert position since if we get here, we won't have
1211 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001212 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1213 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001214 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00001215 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001216 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001217}
1218
Sanjoy Das4153f472015-02-18 01:47:07 +00001219// Get the limit of a recurrence such that incrementing by Step cannot cause
1220// signed overflow as long as the value of the recurrence within the
1221// loop does not exceed this limit before incrementing.
1222static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1223 ICmpInst::Predicate *Pred,
1224 ScalarEvolution *SE) {
1225 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1226 if (SE->isKnownPositive(Step)) {
1227 *Pred = ICmpInst::ICMP_SLT;
1228 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1229 SE->getSignedRange(Step).getSignedMax());
1230 }
1231 if (SE->isKnownNegative(Step)) {
1232 *Pred = ICmpInst::ICMP_SGT;
1233 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1234 SE->getSignedRange(Step).getSignedMin());
1235 }
1236 return nullptr;
1237}
1238
1239// Get the limit of a recurrence such that incrementing by Step cannot cause
1240// unsigned overflow as long as the value of the recurrence within the loop does
1241// not exceed this limit before incrementing.
1242static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1243 ICmpInst::Predicate *Pred,
1244 ScalarEvolution *SE) {
1245 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1246 *Pred = ICmpInst::ICMP_ULT;
1247
1248 return SE->getConstant(APInt::getMinValue(BitWidth) -
1249 SE->getUnsignedRange(Step).getUnsignedMax());
1250}
1251
1252namespace {
1253
1254struct ExtendOpTraitsBase {
1255 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1256};
1257
1258// Used to make code generic over signed and unsigned overflow.
1259template <typename ExtendOp> struct ExtendOpTraits {
1260 // Members present:
1261 //
1262 // static const SCEV::NoWrapFlags WrapType;
1263 //
1264 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1265 //
1266 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1267 // ICmpInst::Predicate *Pred,
1268 // ScalarEvolution *SE);
1269};
1270
1271template <>
1272struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1273 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1274
1275 static const GetExtendExprTy GetExtendExpr;
1276
1277 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1278 ICmpInst::Predicate *Pred,
1279 ScalarEvolution *SE) {
1280 return getSignedOverflowLimitForStep(Step, Pred, SE);
1281 }
1282};
1283
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001284const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001285 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1286
1287template <>
1288struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1289 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1290
1291 static const GetExtendExprTy GetExtendExpr;
1292
1293 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1294 ICmpInst::Predicate *Pred,
1295 ScalarEvolution *SE) {
1296 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1297 }
1298};
1299
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001300const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001301 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001302}
Sanjoy Das4153f472015-02-18 01:47:07 +00001303
1304// The recurrence AR has been shown to have no signed/unsigned wrap or something
1305// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1306// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1307// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1308// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1309// expression "Step + sext/zext(PreIncAR)" is congruent with
1310// "sext/zext(PostIncAR)"
1311template <typename ExtendOpTy>
1312static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1313 ScalarEvolution *SE) {
1314 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1315 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1316
1317 const Loop *L = AR->getLoop();
1318 const SCEV *Start = AR->getStart();
1319 const SCEV *Step = AR->getStepRecurrence(*SE);
1320
1321 // Check for a simple looking step prior to loop entry.
1322 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1323 if (!SA)
1324 return nullptr;
1325
1326 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1327 // subtraction is expensive. For this purpose, perform a quick and dirty
1328 // difference, by checking for Step in the operand list.
1329 SmallVector<const SCEV *, 4> DiffOps;
1330 for (const SCEV *Op : SA->operands())
1331 if (Op != Step)
1332 DiffOps.push_back(Op);
1333
1334 if (DiffOps.size() == SA->getNumOperands())
1335 return nullptr;
1336
1337 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1338 // `Step`:
1339
1340 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001341 auto PreStartFlags =
1342 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1343 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001344 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1345 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1346
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001347 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1348 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001349 //
1350
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001351 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1352 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1353 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001354 return PreStart;
1355
1356 // 2. Direct overflow check on the step operation's expression.
1357 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1358 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1359 const SCEV *OperandExtendedStart =
1360 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1361 (SE->*GetExtendExpr)(Step, WideTy));
1362 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1363 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1364 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1365 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1366 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1367 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1368 }
1369 return PreStart;
1370 }
1371
1372 // 3. Loop precondition.
1373 ICmpInst::Predicate Pred;
1374 const SCEV *OverflowLimit =
1375 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1376
1377 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001378 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001379 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001380
Sanjoy Das4153f472015-02-18 01:47:07 +00001381 return nullptr;
1382}
1383
1384// Get the normalized zero or sign extended expression for this AddRec's Start.
1385template <typename ExtendOpTy>
1386static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1387 ScalarEvolution *SE) {
1388 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1389
1390 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1391 if (!PreStart)
1392 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1393
1394 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1395 (SE->*GetExtendExpr)(PreStart, Ty));
1396}
1397
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001398// Try to prove away overflow by looking at "nearby" add recurrences. A
1399// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1400// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1401//
1402// Formally:
1403//
1404// {S,+,X} == {S-T,+,X} + T
1405// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1406//
1407// If ({S-T,+,X} + T) does not overflow ... (1)
1408//
1409// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1410//
1411// If {S-T,+,X} does not overflow ... (2)
1412//
1413// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1414// == {Ext(S-T)+Ext(T),+,Ext(X)}
1415//
1416// If (S-T)+T does not overflow ... (3)
1417//
1418// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1419// == {Ext(S),+,Ext(X)} == LHS
1420//
1421// Thus, if (1), (2) and (3) are true for some T, then
1422// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1423//
1424// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1425// does not overflow" restricted to the 0th iteration. Therefore we only need
1426// to check for (1) and (2).
1427//
1428// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1429// is `Delta` (defined below).
1430//
1431template <typename ExtendOpTy>
1432bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1433 const SCEV *Step,
1434 const Loop *L) {
1435 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1436
1437 // We restrict `Start` to a constant to prevent SCEV from spending too much
1438 // time here. It is correct (but more expensive) to continue with a
1439 // non-constant `Start` and do a general SCEV subtraction to compute
1440 // `PreStart` below.
1441 //
1442 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1443 if (!StartC)
1444 return false;
1445
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001446 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001447
1448 for (unsigned Delta : {-2, -1, 1, 2}) {
1449 const SCEV *PreStart = getConstant(StartAI - Delta);
1450
Sanjoy Das42801102015-10-23 06:57:21 +00001451 FoldingSetNodeID ID;
1452 ID.AddInteger(scAddRecExpr);
1453 ID.AddPointer(PreStart);
1454 ID.AddPointer(Step);
1455 ID.AddPointer(L);
1456 void *IP = nullptr;
1457 const auto *PreAR =
1458 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1459
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001460 // Give up if we don't already have the add recurrence we need because
1461 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001462 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1463 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1464 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1465 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1466 DeltaS, &Pred, this);
1467 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1468 return true;
1469 }
1470 }
1471
1472 return false;
1473}
1474
Dan Gohmanaf752342009-07-07 17:06:11 +00001475const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001476 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001477 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001478 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001479 assert(isSCEVable(Ty) &&
1480 "This is not a conversion to a SCEVable type!");
1481 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001482
Dan Gohman3423e722009-06-30 20:13:32 +00001483 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001484 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1485 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001486 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001487
Dan Gohman79af8542009-04-22 16:20:48 +00001488 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001489 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001490 return getZeroExtendExpr(SZ->getOperand(), Ty);
1491
Dan Gohman74a0ba12009-07-13 20:55:53 +00001492 // Before doing any expensive analysis, check to see if we've already
1493 // computed a SCEV for this Op and Ty.
1494 FoldingSetNodeID ID;
1495 ID.AddInteger(scZeroExtend);
1496 ID.AddPointer(Op);
1497 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001498 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001499 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1500
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001501 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1502 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1503 // It's possible the bits taken off by the truncate were all zero bits. If
1504 // so, we should be able to simplify this further.
1505 const SCEV *X = ST->getOperand();
1506 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001507 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1508 unsigned NewBits = getTypeSizeInBits(Ty);
1509 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001510 CR.zextOrTrunc(NewBits)))
1511 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001512 }
1513
Dan Gohman76466372009-04-27 20:16:15 +00001514 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001515 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001516 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001517 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001518 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001519 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001520 const SCEV *Start = AR->getStart();
1521 const SCEV *Step = AR->getStepRecurrence(*this);
1522 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1523 const Loop *L = AR->getLoop();
1524
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001525 if (!AR->hasNoUnsignedWrap()) {
1526 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1527 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1528 }
1529
Dan Gohman62ef6a72009-07-25 01:22:26 +00001530 // If we have special knowledge that this addrec won't overflow,
1531 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001532 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001533 return getAddRecExpr(
1534 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1535 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001536
Dan Gohman76466372009-04-27 20:16:15 +00001537 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1538 // Note that this serves two purposes: It filters out loops that are
1539 // simply not analyzable, and it covers the case where this code is
1540 // being called from within backedge-taken count analysis, such that
1541 // attempting to ask for the backedge-taken count would likely result
1542 // in infinite recursion. In the later case, the analysis code will
1543 // cope with a conservative value, and it will take care to purge
1544 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001545 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001546 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001547 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001548 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001549
1550 // Check whether the backedge-taken count can be losslessly casted to
1551 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001552 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001553 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001554 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001555 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1556 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001557 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001558 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001559 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001560 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1561 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1562 const SCEV *WideMaxBECount =
1563 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001564 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001565 getAddExpr(WideStart,
1566 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001567 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001568 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001569 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1570 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001571 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001572 return getAddRecExpr(
1573 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1574 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001575 }
Dan Gohman76466372009-04-27 20:16:15 +00001576 // Similar to above, only this time treat the step value as signed.
1577 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001578 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001579 getAddExpr(WideStart,
1580 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001581 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001582 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001583 // Cache knowledge of AR NW, which is propagated to this AddRec.
1584 // Negative step causes unsigned wrap, but it still can't self-wrap.
1585 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001586 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001587 return getAddRecExpr(
1588 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1589 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001590 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001591 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001592 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001593
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001594 // Normally, in the cases we can prove no-overflow via a
1595 // backedge guarding condition, we can also compute a backedge
1596 // taken count for the loop. The exceptions are assumptions and
1597 // guards present in the loop -- SCEV is not great at exploiting
1598 // these to compute max backedge taken counts, but can still use
1599 // these to prove lack of overflow. Use this fact to avoid
1600 // doing extra work that may not pay off.
1601 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Hal Finkelcb9f78e2016-12-15 02:53:42 +00001602 !AffectedMap.empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001603 // If the backedge is guarded by a comparison with the pre-inc
1604 // value the addrec is safe. Also, if the entry is guarded by
1605 // a comparison with the start value and the backedge is
1606 // guarded by a comparison with the post-inc value, the addrec
1607 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001608 if (isKnownPositive(Step)) {
1609 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1610 getUnsignedRange(Step).getUnsignedMax());
1611 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001612 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001613 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001614 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001615 // Cache knowledge of AR NUW, which is propagated to this
1616 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001617 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001618 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001619 return getAddRecExpr(
1620 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1621 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001622 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001623 } else if (isKnownNegative(Step)) {
1624 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1625 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001626 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1627 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001628 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001629 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001630 // Cache knowledge of AR NW, which is propagated to this
1631 // AddRec. Negative step causes unsigned wrap, but it
1632 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001633 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1634 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001635 return getAddRecExpr(
1636 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1637 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001638 }
Dan Gohman76466372009-04-27 20:16:15 +00001639 }
1640 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001641
1642 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1643 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1644 return getAddRecExpr(
1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1646 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1647 }
Dan Gohman76466372009-04-27 20:16:15 +00001648 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001649
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001650 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1651 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001652 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001653 // If the addition does not unsign overflow then we can, by definition,
1654 // commute the zero extension with the addition operation.
1655 SmallVector<const SCEV *, 4> Ops;
1656 for (const auto *Op : SA->operands())
1657 Ops.push_back(getZeroExtendExpr(Op, Ty));
1658 return getAddExpr(Ops, SCEV::FlagNUW);
1659 }
1660 }
1661
Dan Gohman74a0ba12009-07-13 20:55:53 +00001662 // The cast wasn't folded; create an explicit cast node.
1663 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001664 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001665 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1666 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001667 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00001668 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001669 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001670}
1671
Dan Gohmanaf752342009-07-07 17:06:11 +00001672const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001673 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001674 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001675 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001676 assert(isSCEVable(Ty) &&
1677 "This is not a conversion to a SCEVable type!");
1678 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001679
Dan Gohman3423e722009-06-30 20:13:32 +00001680 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001681 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1682 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001683 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001684
Dan Gohman79af8542009-04-22 16:20:48 +00001685 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001686 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001687 return getSignExtendExpr(SS->getOperand(), Ty);
1688
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001689 // sext(zext(x)) --> zext(x)
1690 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1691 return getZeroExtendExpr(SZ->getOperand(), Ty);
1692
Dan Gohman74a0ba12009-07-13 20:55:53 +00001693 // Before doing any expensive analysis, check to see if we've already
1694 // computed a SCEV for this Op and Ty.
1695 FoldingSetNodeID ID;
1696 ID.AddInteger(scSignExtend);
1697 ID.AddPointer(Op);
1698 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001699 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001700 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1701
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001702 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1703 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1704 // It's possible the bits taken off by the truncate were all sign bits. If
1705 // so, we should be able to simplify this further.
1706 const SCEV *X = ST->getOperand();
1707 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001708 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1709 unsigned NewBits = getTypeSizeInBits(Ty);
1710 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001711 CR.sextOrTrunc(NewBits)))
1712 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001713 }
1714
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001715 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001716 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001717 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001718 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1719 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001720 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001721 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001722 const APInt &C1 = SC1->getAPInt();
1723 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001724 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001725 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001726 return getAddExpr(getSignExtendExpr(SC1, Ty),
1727 getSignExtendExpr(SMul, Ty));
1728 }
1729 }
1730 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001731
1732 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001733 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001734 // If the addition does not sign overflow then we can, by definition,
1735 // commute the sign extension with the addition operation.
1736 SmallVector<const SCEV *, 4> Ops;
1737 for (const auto *Op : SA->operands())
1738 Ops.push_back(getSignExtendExpr(Op, Ty));
1739 return getAddExpr(Ops, SCEV::FlagNSW);
1740 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001741 }
Dan Gohman76466372009-04-27 20:16:15 +00001742 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001743 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001744 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001745 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001746 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001747 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001748 const SCEV *Start = AR->getStart();
1749 const SCEV *Step = AR->getStepRecurrence(*this);
1750 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1751 const Loop *L = AR->getLoop();
1752
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001753 if (!AR->hasNoSignedWrap()) {
1754 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1755 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1756 }
1757
Dan Gohman62ef6a72009-07-25 01:22:26 +00001758 // If we have special knowledge that this addrec won't overflow,
1759 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001760 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001761 return getAddRecExpr(
1762 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1763 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001764
Dan Gohman76466372009-04-27 20:16:15 +00001765 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1766 // Note that this serves two purposes: It filters out loops that are
1767 // simply not analyzable, and it covers the case where this code is
1768 // being called from within backedge-taken count analysis, such that
1769 // attempting to ask for the backedge-taken count would likely result
1770 // in infinite recursion. In the later case, the analysis code will
1771 // cope with a conservative value, and it will take care to purge
1772 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001773 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001774 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001775 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001776 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001777
1778 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001779 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001780 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001781 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001782 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001783 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1784 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001785 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001786 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001787 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001788 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1789 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1790 const SCEV *WideMaxBECount =
1791 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001792 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001793 getAddExpr(WideStart,
1794 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001795 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001796 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001797 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1798 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001799 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001800 return getAddRecExpr(
1801 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1802 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001803 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001804 // Similar to above, only this time treat the step value as unsigned.
1805 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001806 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001807 getAddExpr(WideStart,
1808 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001809 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001810 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001811 // If AR wraps around then
1812 //
1813 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1814 // => SAdd != OperandExtendedAdd
1815 //
1816 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1817 // (SAdd == OperandExtendedAdd => AR is NW)
1818
1819 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1820
Dan Gohman8c129d72009-07-16 17:34:36 +00001821 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001822 return getAddRecExpr(
1823 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1824 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001825 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001826 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001827 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001828
Sanjoy Das787c2462016-05-11 17:41:26 +00001829 // Normally, in the cases we can prove no-overflow via a
1830 // backedge guarding condition, we can also compute a backedge
1831 // taken count for the loop. The exceptions are assumptions and
1832 // guards present in the loop -- SCEV is not great at exploiting
1833 // these to compute max backedge taken counts, but can still use
1834 // these to prove lack of overflow. Use this fact to avoid
1835 // doing extra work that may not pay off.
1836
1837 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Hal Finkelcb9f78e2016-12-15 02:53:42 +00001838 !AffectedMap.empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001839 // If the backedge is guarded by a comparison with the pre-inc
1840 // value the addrec is safe. Also, if the entry is guarded by
1841 // a comparison with the start value and the backedge is
1842 // guarded by a comparison with the post-inc value, the addrec
1843 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001844 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001845 const SCEV *OverflowLimit =
1846 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001847 if (OverflowLimit &&
1848 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1849 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1850 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1851 OverflowLimit)))) {
1852 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1853 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001854 return getAddRecExpr(
1855 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1856 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001857 }
1858 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001859
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001860 // If Start and Step are constants, check if we can apply this
1861 // transformation:
1862 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001863 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1864 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001865 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001866 const APInt &C1 = SC1->getAPInt();
1867 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001868 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1869 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001870 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001871 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1872 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001873 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1874 }
1875 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001876
1877 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1878 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1879 return getAddRecExpr(
1880 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1881 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1882 }
Dan Gohman76466372009-04-27 20:16:15 +00001883 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001884
Sanjoy Das11ef6062016-03-03 18:31:23 +00001885 // If the input value is provably positive and we could not simplify
1886 // away the sext build a zext instead.
1887 if (isKnownNonNegative(Op))
1888 return getZeroExtendExpr(Op, Ty);
1889
Dan Gohman74a0ba12009-07-13 20:55:53 +00001890 // The cast wasn't folded; create an explicit cast node.
1891 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001892 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001893 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1894 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001895 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00001896 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001897 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001898}
1899
Dan Gohman8db2edc2009-06-13 15:56:47 +00001900/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1901/// unspecified bits out to the given type.
1902///
Dan Gohmanaf752342009-07-07 17:06:11 +00001903const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001904 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001905 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1906 "This is not an extending conversion!");
1907 assert(isSCEVable(Ty) &&
1908 "This is not a conversion to a SCEVable type!");
1909 Ty = getEffectiveSCEVType(Ty);
1910
1911 // Sign-extend negative constants.
1912 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001913 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001914 return getSignExtendExpr(Op, Ty);
1915
1916 // Peel off a truncate cast.
1917 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001918 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001919 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1920 return getAnyExtendExpr(NewOp, Ty);
1921 return getTruncateOrNoop(NewOp, Ty);
1922 }
1923
1924 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001925 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001926 if (!isa<SCEVZeroExtendExpr>(ZExt))
1927 return ZExt;
1928
1929 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001930 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001931 if (!isa<SCEVSignExtendExpr>(SExt))
1932 return SExt;
1933
Dan Gohman51ad99d2010-01-21 02:09:26 +00001934 // Force the cast to be folded into the operands of an addrec.
1935 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1936 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001937 for (const SCEV *Op : AR->operands())
1938 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001939 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001940 }
1941
Dan Gohman8db2edc2009-06-13 15:56:47 +00001942 // If the expression is obviously signed, use the sext cast value.
1943 if (isa<SCEVSMaxExpr>(Op))
1944 return SExt;
1945
1946 // Absent any other information, use the zext cast value.
1947 return ZExt;
1948}
1949
Sanjoy Dasf8570812016-05-29 00:38:22 +00001950/// Process the given Ops list, which is a list of operands to be added under
1951/// the given scale, update the given map. This is a helper function for
1952/// getAddRecExpr. As an example of what it does, given a sequence of operands
1953/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001954///
Tobias Grosserba49e422014-03-05 10:37:17 +00001955/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001956///
1957/// where A and B are constants, update the map with these values:
1958///
1959/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1960///
1961/// and add 13 + A*B*29 to AccumulatedConstant.
1962/// This will allow getAddRecExpr to produce this:
1963///
1964/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1965///
1966/// This form often exposes folding opportunities that are hidden in
1967/// the original operand list.
1968///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001969/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001970/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1971/// the common case where no interesting opportunities are present, and
1972/// is also used as a check to avoid infinite recursion.
1973///
1974static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001975CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001976 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001977 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001978 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001979 const APInt &Scale,
1980 ScalarEvolution &SE) {
1981 bool Interesting = false;
1982
Dan Gohman45073042010-06-18 19:12:32 +00001983 // Iterate over the add operands. They are sorted, with constants first.
1984 unsigned i = 0;
1985 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1986 ++i;
1987 // Pull a buried constant out to the outside.
1988 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1989 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001990 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001991 }
1992
1993 // Next comes everything else. We're especially interested in multiplies
1994 // here, but they're in the middle, so just visit the rest with one loop.
1995 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001996 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1997 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1998 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001999 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00002000 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2001 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00002002 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002003 Interesting |=
2004 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002005 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002006 NewScale, SE);
2007 } else {
2008 // A multiplication of a constant with some other value. Update
2009 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002010 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2011 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002012 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002013 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002014 NewOps.push_back(Pair.first->first);
2015 } else {
2016 Pair.first->second += NewScale;
2017 // The map already had an entry for this value, which may indicate
2018 // a folding opportunity.
2019 Interesting = true;
2020 }
2021 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002022 } else {
2023 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002024 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002025 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002026 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002027 NewOps.push_back(Pair.first->first);
2028 } else {
2029 Pair.first->second += Scale;
2030 // The map already had an entry for this value, which may indicate
2031 // a folding opportunity.
2032 Interesting = true;
2033 }
2034 }
2035 }
2036
2037 return Interesting;
2038}
2039
Sanjoy Das81401d42015-01-10 23:41:24 +00002040// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2041// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2042// can't-overflow flags for the operation if possible.
2043static SCEV::NoWrapFlags
2044StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2045 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002046 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002047 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002048 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002049
2050 bool CanAnalyze =
2051 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2052 (void)CanAnalyze;
2053 assert(CanAnalyze && "don't call from other places!");
2054
2055 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2056 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002057 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002058
2059 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002060 auto IsKnownNonNegative = [&](const SCEV *S) {
2061 return SE->isKnownNonNegative(S);
2062 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002063
Sanjoy Das3b827c72015-11-29 23:40:53 +00002064 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002065 Flags =
2066 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002067
Sanjoy Das8f274152015-10-22 19:57:19 +00002068 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2069
2070 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2071 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2072
2073 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2074 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2075
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002076 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002077 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002078 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2079 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002080 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2081 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2082 }
2083 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002084 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2085 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002086 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2087 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2088 }
2089 }
2090
2091 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002092}
2093
Sanjoy Dasf8570812016-05-29 00:38:22 +00002094/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002095const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002096 SCEV::NoWrapFlags Flags) {
2097 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2098 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002099 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002100 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002101#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002102 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002103 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002104 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002105 "SCEVAddExpr operand types don't match!");
2106#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002107
2108 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002109 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002110
Sanjoy Das64895612015-10-09 02:44:45 +00002111 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2112
Chris Lattnerd934c702004-04-02 20:23:17 +00002113 // If there are any constants, fold them together.
2114 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002115 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002116 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002117 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002118 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002119 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002120 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002121 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002122 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002123 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002124 }
2125
2126 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002127 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002128 Ops.erase(Ops.begin());
2129 --Idx;
2130 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002131
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002132 if (Ops.size() == 1) return Ops[0];
2133 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002134
Dan Gohman15871f22010-08-27 21:39:59 +00002135 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002136 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002137 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002138 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002139 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002140 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002141 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002142 // Scan ahead to count how many equal operands there are.
2143 unsigned Count = 2;
2144 while (i+Count != e && Ops[i+Count] == Ops[i])
2145 ++Count;
2146 // Merge the values into a multiply.
2147 const SCEV *Scale = getConstant(Ty, Count);
2148 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2149 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002150 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002151 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002152 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002153 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002154 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002155 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002156 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002157 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002158
Dan Gohman2e55cc52009-05-08 21:03:19 +00002159 // Check for truncates. If all the operands are truncated from the same
2160 // type, see if factoring out the truncate would permit the result to be
2161 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2162 // if the contents of the resulting outer trunc fold to something simple.
2163 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2164 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002165 Type *DstType = Trunc->getType();
2166 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002167 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002168 bool Ok = true;
2169 // Check all the operands to see if they can be represented in the
2170 // source type of the truncate.
2171 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2172 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2173 if (T->getOperand()->getType() != SrcType) {
2174 Ok = false;
2175 break;
2176 }
2177 LargeOps.push_back(T->getOperand());
2178 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002179 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002180 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002181 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002182 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2183 if (const SCEVTruncateExpr *T =
2184 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2185 if (T->getOperand()->getType() != SrcType) {
2186 Ok = false;
2187 break;
2188 }
2189 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002190 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002191 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002192 } else {
2193 Ok = false;
2194 break;
2195 }
2196 }
2197 if (Ok)
2198 LargeOps.push_back(getMulExpr(LargeMulOps));
2199 } else {
2200 Ok = false;
2201 break;
2202 }
2203 }
2204 if (Ok) {
2205 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002206 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002207 // If it folds to something simple, use it. Otherwise, don't.
2208 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2209 return getTruncateExpr(Fold, DstType);
2210 }
2211 }
2212
2213 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002214 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2215 ++Idx;
2216
2217 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002218 if (Idx < Ops.size()) {
2219 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002220 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002221 // If we have an add, expand the add operands onto the end of the operands
2222 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002223 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002224 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002225 DeletedAdd = true;
2226 }
2227
2228 // If we deleted at least one add, we added operands to the end of the list,
2229 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002230 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002231 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002232 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002233 }
2234
2235 // Skip over the add expression until we get to a multiply.
2236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2237 ++Idx;
2238
Dan Gohman038d02e2009-06-14 22:58:51 +00002239 // Check to see if there are any folding opportunities present with
2240 // operands multiplied by constant values.
2241 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2242 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002243 DenseMap<const SCEV *, APInt> M;
2244 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002245 APInt AccumulatedConstant(BitWidth, 0);
2246 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002247 Ops.data(), Ops.size(),
2248 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002249 struct APIntCompare {
2250 bool operator()(const APInt &LHS, const APInt &RHS) const {
2251 return LHS.ult(RHS);
2252 }
2253 };
2254
Dan Gohman038d02e2009-06-14 22:58:51 +00002255 // Some interesting folding opportunity is present, so its worthwhile to
2256 // re-generate the operands list. Group the operands by constant scale,
2257 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002258 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002259 for (const SCEV *NewOp : NewOps)
2260 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002261 // Re-generate the operands list.
2262 Ops.clear();
2263 if (AccumulatedConstant != 0)
2264 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002265 for (auto &MulOp : MulOpLists)
2266 if (MulOp.first != 0)
2267 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2268 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002269 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002270 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002271 if (Ops.size() == 1)
2272 return Ops[0];
2273 return getAddExpr(Ops);
2274 }
2275 }
2276
Chris Lattnerd934c702004-04-02 20:23:17 +00002277 // If we are adding something to a multiply expression, make sure the
2278 // something is not already an operand of the multiply. If so, merge it into
2279 // the multiply.
2280 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002281 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002282 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002283 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002284 if (isa<SCEVConstant>(MulOpSCEV))
2285 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002286 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002287 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002288 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002289 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002290 if (Mul->getNumOperands() != 2) {
2291 // If the multiply has more than two operands, we must get the
2292 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002293 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2294 Mul->op_begin()+MulOp);
2295 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002296 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002297 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002298 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002299 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002300 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002301 if (Ops.size() == 2) return OuterMul;
2302 if (AddOp < Idx) {
2303 Ops.erase(Ops.begin()+AddOp);
2304 Ops.erase(Ops.begin()+Idx-1);
2305 } else {
2306 Ops.erase(Ops.begin()+Idx);
2307 Ops.erase(Ops.begin()+AddOp-1);
2308 }
2309 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002310 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002311 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002312
Chris Lattnerd934c702004-04-02 20:23:17 +00002313 // Check this multiply against other multiplies being added together.
2314 for (unsigned OtherMulIdx = Idx+1;
2315 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2316 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002317 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002318 // If MulOp occurs in OtherMul, we can fold the two multiplies
2319 // together.
2320 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2321 OMulOp != e; ++OMulOp)
2322 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2323 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002324 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002325 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002326 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002327 Mul->op_begin()+MulOp);
2328 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002329 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002330 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002331 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002332 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002333 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002334 OtherMul->op_begin()+OMulOp);
2335 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002336 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002337 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002338 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2339 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002340 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002341 Ops.erase(Ops.begin()+Idx);
2342 Ops.erase(Ops.begin()+OtherMulIdx-1);
2343 Ops.push_back(OuterMul);
2344 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002345 }
2346 }
2347 }
2348 }
2349
2350 // If there are any add recurrences in the operands list, see if any other
2351 // added values are loop invariant. If so, we can fold them into the
2352 // recurrence.
2353 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2354 ++Idx;
2355
2356 // Scan over all recurrences, trying to fold loop invariants into them.
2357 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2358 // Scan all of the other operands to this add and add them to the vector if
2359 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002360 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002361 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002362 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002363 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002364 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002365 LIOps.push_back(Ops[i]);
2366 Ops.erase(Ops.begin()+i);
2367 --i; --e;
2368 }
2369
2370 // If we found some loop invariants, fold them into the recurrence.
2371 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002372 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002373 LIOps.push_back(AddRec->getStart());
2374
Dan Gohmanaf752342009-07-07 17:06:11 +00002375 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002376 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002377 // This follows from the fact that the no-wrap flags on the outer add
2378 // expression are applicable on the 0th iteration, when the add recurrence
2379 // will be equal to its start value.
2380 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002381
Dan Gohman16206132010-06-30 07:16:37 +00002382 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002383 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002384 // Always propagate NW.
2385 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002386 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002387
Chris Lattnerd934c702004-04-02 20:23:17 +00002388 // If all of the other operands were loop invariant, we are done.
2389 if (Ops.size() == 1) return NewRec;
2390
Nick Lewyckydb66b822011-09-06 05:08:09 +00002391 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002392 for (unsigned i = 0;; ++i)
2393 if (Ops[i] == AddRec) {
2394 Ops[i] = NewRec;
2395 break;
2396 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002397 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002398 }
2399
2400 // Okay, if there weren't any loop invariants to be folded, check to see if
2401 // there are multiple AddRec's with the same loop induction variable being
2402 // added together. If so, we can fold them.
2403 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002404 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2405 ++OtherIdx)
2406 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2407 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2408 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2409 AddRec->op_end());
2410 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2411 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002412 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002413 if (OtherAddRec->getLoop() == AddRecLoop) {
2414 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2415 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002416 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002417 AddRecOps.append(OtherAddRec->op_begin()+i,
2418 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002419 break;
2420 }
Dan Gohman028c1812010-08-29 14:53:34 +00002421 AddRecOps[i] = getAddExpr(AddRecOps[i],
2422 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002423 }
2424 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002425 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002426 // Step size has changed, so we cannot guarantee no self-wraparound.
2427 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002428 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002429 }
2430
2431 // Otherwise couldn't fold anything into this recurrence. Move onto the
2432 // next one.
2433 }
2434
2435 // Okay, it looks like we really DO need an add expr. Check to see if we
2436 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002437 FoldingSetNodeID ID;
2438 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002439 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2440 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002441 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002442 SCEVAddExpr *S =
2443 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2444 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002445 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2446 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002447 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2448 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002449 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00002450 addAffectedFromOperands(S);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002451 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002452 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002453 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002454}
2455
Nick Lewycky287682e2011-10-04 06:51:26 +00002456static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2457 uint64_t k = i*j;
2458 if (j > 1 && k / j != i) Overflow = true;
2459 return k;
2460}
2461
2462/// Compute the result of "n choose k", the binomial coefficient. If an
2463/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002464/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002465static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2466 // We use the multiplicative formula:
2467 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2468 // At each iteration, we take the n-th term of the numeral and divide by the
2469 // (k-n)th term of the denominator. This division will always produce an
2470 // integral result, and helps reduce the chance of overflow in the
2471 // intermediate computations. However, we can still overflow even when the
2472 // final result would fit.
2473
2474 if (n == 0 || n == k) return 1;
2475 if (k > n) return 0;
2476
2477 if (k > n/2)
2478 k = n-k;
2479
2480 uint64_t r = 1;
2481 for (uint64_t i = 1; i <= k; ++i) {
2482 r = umul_ov(r, n-(i-1), Overflow);
2483 r /= i;
2484 }
2485 return r;
2486}
2487
Nick Lewycky05044c22014-12-06 00:45:50 +00002488/// Determine if any of the operands in this SCEV are a constant or if
2489/// any of the add or multiply expressions in this SCEV contain a constant.
2490static bool containsConstantSomewhere(const SCEV *StartExpr) {
2491 SmallVector<const SCEV *, 4> Ops;
2492 Ops.push_back(StartExpr);
2493 while (!Ops.empty()) {
2494 const SCEV *CurrentExpr = Ops.pop_back_val();
2495 if (isa<SCEVConstant>(*CurrentExpr))
2496 return true;
2497
2498 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2499 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002500 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002501 }
2502 }
2503 return false;
2504}
2505
Sanjoy Dasf8570812016-05-29 00:38:22 +00002506/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002507const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002508 SCEV::NoWrapFlags Flags) {
2509 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2510 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002511 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002512 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002513#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002514 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002515 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002516 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002517 "SCEVMulExpr operand types don't match!");
2518#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002519
2520 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002521 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002522
Sanjoy Das64895612015-10-09 02:44:45 +00002523 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2524
Chris Lattnerd934c702004-04-02 20:23:17 +00002525 // If there are any constants, fold them together.
2526 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002527 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002528
2529 // C1*(C2+V) -> C1*C2 + C1*V
2530 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002531 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2532 // If any of Add's ops are Adds or Muls with a constant,
2533 // apply this transformation as well.
2534 if (Add->getNumOperands() == 2)
2535 if (containsConstantSomewhere(Add))
2536 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2537 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002538
Chris Lattnerd934c702004-04-02 20:23:17 +00002539 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002540 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002541 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002542 ConstantInt *Fold =
2543 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002544 Ops[0] = getConstant(Fold);
2545 Ops.erase(Ops.begin()+1); // Erase the folded element
2546 if (Ops.size() == 1) return Ops[0];
2547 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002548 }
2549
2550 // If we are left with a constant one being multiplied, strip it off.
2551 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2552 Ops.erase(Ops.begin());
2553 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002554 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002555 // If we have a multiply of zero, it will always be zero.
2556 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002557 } else if (Ops[0]->isAllOnesValue()) {
2558 // If we have a mul by -1 of an add, try distributing the -1 among the
2559 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002560 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002561 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2562 SmallVector<const SCEV *, 4> NewOps;
2563 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002564 for (const SCEV *AddOp : Add->operands()) {
2565 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002566 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2567 NewOps.push_back(Mul);
2568 }
2569 if (AnyFolded)
2570 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002571 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002572 // Negation preserves a recurrence's no self-wrap property.
2573 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002574 for (const SCEV *AddRecOp : AddRec->operands())
2575 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2576
Andrew Tricke92dcce2011-03-14 17:38:54 +00002577 return getAddRecExpr(Operands, AddRec->getLoop(),
2578 AddRec->getNoWrapFlags(SCEV::FlagNW));
2579 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002580 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002581 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002582
2583 if (Ops.size() == 1)
2584 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002585 }
2586
2587 // Skip over the add expression until we get to a multiply.
2588 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2589 ++Idx;
2590
Chris Lattnerd934c702004-04-02 20:23:17 +00002591 // If there are mul operands inline them all into this expression.
2592 if (Idx < Ops.size()) {
2593 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002594 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002595 if (Ops.size() > MulOpsInlineThreshold)
2596 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002597 // If we have an mul, expand the mul operands onto the end of the operands
2598 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002599 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002600 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002601 DeletedMul = true;
2602 }
2603
2604 // If we deleted at least one mul, we added operands to the end of the list,
2605 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002606 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002607 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002608 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002609 }
2610
2611 // If there are any add recurrences in the operands list, see if any other
2612 // added values are loop invariant. If so, we can fold them into the
2613 // recurrence.
2614 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2615 ++Idx;
2616
2617 // Scan over all recurrences, trying to fold loop invariants into them.
2618 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2619 // Scan all of the other operands to this mul and add them to the vector if
2620 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002621 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002622 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002623 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002624 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002625 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002626 LIOps.push_back(Ops[i]);
2627 Ops.erase(Ops.begin()+i);
2628 --i; --e;
2629 }
2630
2631 // If we found some loop invariants, fold them into the recurrence.
2632 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002633 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002634 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002635 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002636 const SCEV *Scale = getMulExpr(LIOps);
2637 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2638 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002639
Dan Gohman16206132010-06-30 07:16:37 +00002640 // Build the new addrec. Propagate the NUW and NSW flags if both the
2641 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002642 //
2643 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002644 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002645 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2646 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002647
2648 // If all of the other operands were loop invariant, we are done.
2649 if (Ops.size() == 1) return NewRec;
2650
Nick Lewyckydb66b822011-09-06 05:08:09 +00002651 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002652 for (unsigned i = 0;; ++i)
2653 if (Ops[i] == AddRec) {
2654 Ops[i] = NewRec;
2655 break;
2656 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002657 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002658 }
2659
2660 // Okay, if there weren't any loop invariants to be folded, check to see if
2661 // there are multiple AddRec's with the same loop induction variable being
2662 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002663
2664 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2665 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2666 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2667 // ]]],+,...up to x=2n}.
2668 // Note that the arguments to choose() are always integers with values
2669 // known at compile time, never SCEV objects.
2670 //
2671 // The implementation avoids pointless extra computations when the two
2672 // addrec's are of different length (mathematically, it's equivalent to
2673 // an infinite stream of zeros on the right).
2674 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002675 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002676 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002677 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002678 const SCEVAddRecExpr *OtherAddRec =
2679 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2680 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002681 continue;
2682
Nick Lewycky97756402014-09-01 05:17:15 +00002683 bool Overflow = false;
2684 Type *Ty = AddRec->getType();
2685 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2686 SmallVector<const SCEV*, 7> AddRecOps;
2687 for (int x = 0, xe = AddRec->getNumOperands() +
2688 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002689 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002690 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2691 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2692 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2693 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2694 z < ze && !Overflow; ++z) {
2695 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2696 uint64_t Coeff;
2697 if (LargerThan64Bits)
2698 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2699 else
2700 Coeff = Coeff1*Coeff2;
2701 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2702 const SCEV *Term1 = AddRec->getOperand(y-z);
2703 const SCEV *Term2 = OtherAddRec->getOperand(z);
2704 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002705 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002706 }
Nick Lewycky97756402014-09-01 05:17:15 +00002707 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002708 }
Nick Lewycky97756402014-09-01 05:17:15 +00002709 if (!Overflow) {
2710 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2711 SCEV::FlagAnyWrap);
2712 if (Ops.size() == 2) return NewAddRec;
2713 Ops[Idx] = NewAddRec;
2714 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2715 OpsModified = true;
2716 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2717 if (!AddRec)
2718 break;
2719 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002720 }
Nick Lewycky97756402014-09-01 05:17:15 +00002721 if (OpsModified)
2722 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002723
2724 // Otherwise couldn't fold anything into this recurrence. Move onto the
2725 // next one.
2726 }
2727
2728 // Okay, it looks like we really DO need an mul expr. Check to see if we
2729 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002730 FoldingSetNodeID ID;
2731 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002732 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2733 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002734 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002735 SCEVMulExpr *S =
2736 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2737 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002738 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2739 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002740 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2741 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002742 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00002743 addAffectedFromOperands(S);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002744 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002745 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002746 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002747}
2748
Sanjoy Dasf8570812016-05-29 00:38:22 +00002749/// Get a canonical unsigned division expression, or something simpler if
2750/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002751const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2752 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002753 assert(getEffectiveSCEVType(LHS->getType()) ==
2754 getEffectiveSCEVType(RHS->getType()) &&
2755 "SCEVUDivExpr operand types don't match!");
2756
Dan Gohmana30370b2009-05-04 22:02:23 +00002757 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002758 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002759 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002760 // If the denominator is zero, the result of the udiv is undefined. Don't
2761 // try to analyze it, because the resolution chosen here may differ from
2762 // the resolution chosen in other parts of the compiler.
2763 if (!RHSC->getValue()->isZero()) {
2764 // Determine if the division can be folded into the operands of
2765 // its operands.
2766 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002767 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002768 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002769 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002770 // For non-power-of-two values, effectively round the value up to the
2771 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002772 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002773 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002774 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002775 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002776 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2777 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002778 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2779 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002780 const APInt &StepInt = Step->getAPInt();
2781 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002782 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002783 getZeroExtendExpr(AR, ExtTy) ==
2784 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2785 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002786 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002787 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002788 for (const SCEV *Op : AR->operands())
2789 Operands.push_back(getUDivExpr(Op, RHS));
2790 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002791 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002792 /// Get a canonical UDivExpr for a recurrence.
2793 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2794 // We can currently only fold X%N if X is constant.
2795 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2796 if (StartC && !DivInt.urem(StepInt) &&
2797 getZeroExtendExpr(AR, ExtTy) ==
2798 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2799 getZeroExtendExpr(Step, ExtTy),
2800 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002801 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002802 const APInt &StartRem = StartInt.urem(StepInt);
2803 if (StartRem != 0)
2804 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2805 AR->getLoop(), SCEV::FlagNW);
2806 }
2807 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002808 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2809 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2810 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002811 for (const SCEV *Op : M->operands())
2812 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002813 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2814 // Find an operand that's safely divisible.
2815 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2816 const SCEV *Op = M->getOperand(i);
2817 const SCEV *Div = getUDivExpr(Op, RHSC);
2818 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2819 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2820 M->op_end());
2821 Operands[i] = Div;
2822 return getMulExpr(Operands);
2823 }
2824 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002825 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002826 // (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 +00002827 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002828 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002829 for (const SCEV *Op : A->operands())
2830 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002831 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2832 Operands.clear();
2833 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2834 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2835 if (isa<SCEVUDivExpr>(Op) ||
2836 getMulExpr(Op, RHS) != A->getOperand(i))
2837 break;
2838 Operands.push_back(Op);
2839 }
2840 if (Operands.size() == A->getNumOperands())
2841 return getAddExpr(Operands);
2842 }
2843 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002844
Dan Gohmanacd700a2010-04-22 01:35:11 +00002845 // Fold if both operands are constant.
2846 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2847 Constant *LHSCV = LHSC->getValue();
2848 Constant *RHSCV = RHSC->getValue();
2849 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2850 RHSCV)));
2851 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002852 }
2853 }
2854
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002855 FoldingSetNodeID ID;
2856 ID.AddInteger(scUDivExpr);
2857 ID.AddPointer(LHS);
2858 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002859 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002860 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002861 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2862 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002863 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00002864 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002865 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002866}
2867
Nick Lewycky31eaca52014-01-27 10:04:03 +00002868static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002869 APInt A = C1->getAPInt().abs();
2870 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002871 uint32_t ABW = A.getBitWidth();
2872 uint32_t BBW = B.getBitWidth();
2873
2874 if (ABW > BBW)
2875 B = B.zext(ABW);
2876 else if (ABW < BBW)
2877 A = A.zext(BBW);
2878
2879 return APIntOps::GreatestCommonDivisor(A, B);
2880}
2881
Sanjoy Dasf8570812016-05-29 00:38:22 +00002882/// Get a canonical unsigned division expression, or something simpler if
2883/// possible. There is no representation for an exact udiv in SCEV IR, but we
2884/// can attempt to remove factors from the LHS and RHS. We can't do this when
2885/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002886const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2887 const SCEV *RHS) {
2888 // TODO: we could try to find factors in all sorts of things, but for now we
2889 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2890 // end of this file for inspiration.
2891
2892 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2893 if (!Mul)
2894 return getUDivExpr(LHS, RHS);
2895
2896 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2897 // If the mulexpr multiplies by a constant, then that constant must be the
2898 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002899 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002900 if (LHSCst == RHSCst) {
2901 SmallVector<const SCEV *, 2> Operands;
2902 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2903 return getMulExpr(Operands);
2904 }
2905
2906 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2907 // that there's a factor provided by one of the other terms. We need to
2908 // check.
2909 APInt Factor = gcd(LHSCst, RHSCst);
2910 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002911 LHSCst =
2912 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2913 RHSCst =
2914 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002915 SmallVector<const SCEV *, 2> Operands;
2916 Operands.push_back(LHSCst);
2917 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2918 LHS = getMulExpr(Operands);
2919 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002920 Mul = dyn_cast<SCEVMulExpr>(LHS);
2921 if (!Mul)
2922 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002923 }
2924 }
2925 }
2926
2927 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2928 if (Mul->getOperand(i) == RHS) {
2929 SmallVector<const SCEV *, 2> Operands;
2930 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2931 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2932 return getMulExpr(Operands);
2933 }
2934 }
2935
2936 return getUDivExpr(LHS, RHS);
2937}
Chris Lattnerd934c702004-04-02 20:23:17 +00002938
Sanjoy Dasf8570812016-05-29 00:38:22 +00002939/// Get an add recurrence expression for the specified loop. Simplify the
2940/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002941const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2942 const Loop *L,
2943 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002944 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002945 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002946 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002947 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002948 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002949 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002950 }
2951
2952 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002953 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002954}
2955
Sanjoy Dasf8570812016-05-29 00:38:22 +00002956/// Get an add recurrence expression for the specified loop. Simplify the
2957/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002958const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002959ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002960 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002961 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002962#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002963 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002964 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002965 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002966 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002967 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002968 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002969 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002970#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002971
Dan Gohmanbe928e32008-06-18 16:23:07 +00002972 if (Operands.back()->isZero()) {
2973 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002974 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002975 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002976
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002977 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2978 // use that information to infer NUW and NSW flags. However, computing a
2979 // BE count requires calling getAddRecExpr, so we may not yet have a
2980 // meaningful BE count at this point (and if we don't, we'd be stuck
2981 // with a SCEVCouldNotCompute as the cached BE count).
2982
Sanjoy Das81401d42015-01-10 23:41:24 +00002983 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002984
Dan Gohman223a5d22008-08-08 18:33:12 +00002985 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002986 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002987 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002988 if (L->contains(NestedLoop)
2989 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2990 : (!NestedLoop->contains(L) &&
2991 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002992 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002993 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002994 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002995 // AddRecs require their operands be loop-invariant with respect to their
2996 // loops. Don't perform this transformation if it would break this
2997 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002998 bool AllInvariant = all_of(
2999 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003000
Dan Gohmancc030b72009-06-26 22:36:20 +00003001 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003002 // Create a recurrence for the outer loop with the same step size.
3003 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003004 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3005 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003006 SCEV::NoWrapFlags OuterFlags =
3007 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003008
3009 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003010 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3011 return isLoopInvariant(Op, NestedLoop);
3012 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003013
Andrew Trick8b55b732011-03-14 16:50:06 +00003014 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003015 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003016 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003017 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3018 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003019 SCEV::NoWrapFlags InnerFlags =
3020 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003021 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3022 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003023 }
3024 // Reset Operands to its original state.
3025 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003026 }
3027 }
3028
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003029 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3030 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003031 FoldingSetNodeID ID;
3032 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003033 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3034 ID.AddPointer(Operands[i]);
3035 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003036 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003037 SCEVAddRecExpr *S =
3038 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3039 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003040 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3041 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003042 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3043 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003044 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003045 addAffectedFromOperands(S);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003046 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003047 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003048 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003049}
3050
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003051const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003052ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3053 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3054 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003055 // getSCEV(Base)->getType() has the same address space as Base->getType()
3056 // because SCEV::getType() preserves the address space.
3057 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3058 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3059 // instruction to its SCEV, because the Instruction may be guarded by control
3060 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003061 // context. This can be fixed similarly to how these flags are handled for
3062 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003063 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3064 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003065
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003066 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003067 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003068 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003069 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003070 for (const SCEV *IndexExpr : IndexExprs) {
3071 // Compute the (potentially symbolic) offset in bytes for this index.
3072 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3073 // For a struct, add the member offset.
3074 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3075 unsigned FieldNo = Index->getZExtValue();
3076 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3077
3078 // Add the field offset to the running total offset.
3079 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3080
3081 // Update CurTy to the type of the field at Index.
3082 CurTy = STy->getTypeAtIndex(Index);
3083 } else {
3084 // Update CurTy to its element type.
3085 CurTy = cast<SequentialType>(CurTy)->getElementType();
3086 // For an array, add the element offset, explicitly scaled.
3087 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3088 // Getelementptr indices are signed.
3089 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3090
3091 // Multiply the index by the element size to compute the element offset.
3092 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3093
3094 // Add the element offset to the running total offset.
3095 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3096 }
3097 }
3098
3099 // Add the total offset from all the GEP indices to the base.
3100 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3101}
3102
Dan Gohmanabd17092009-06-24 14:49:00 +00003103const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3104 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003105 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003106 return getSMaxExpr(Ops);
3107}
3108
Dan Gohmanaf752342009-07-07 17:06:11 +00003109const SCEV *
3110ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003111 assert(!Ops.empty() && "Cannot get empty smax!");
3112 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003113#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003114 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003115 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003116 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003117 "SCEVSMaxExpr operand types don't match!");
3118#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003119
3120 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003121 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003122
3123 // If there are any constants, fold them together.
3124 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003125 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003126 ++Idx;
3127 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003128 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003129 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003130 ConstantInt *Fold = ConstantInt::get(
3131 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003132 Ops[0] = getConstant(Fold);
3133 Ops.erase(Ops.begin()+1); // Erase the folded element
3134 if (Ops.size() == 1) return Ops[0];
3135 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003136 }
3137
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003138 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003139 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3140 Ops.erase(Ops.begin());
3141 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003142 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3143 // If we have an smax with a constant maximum-int, it will always be
3144 // maximum-int.
3145 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003146 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003147
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003148 if (Ops.size() == 1) return Ops[0];
3149 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003150
3151 // Find the first SMax
3152 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3153 ++Idx;
3154
3155 // Check to see if one of the operands is an SMax. If so, expand its operands
3156 // onto our operand list, and recurse to simplify.
3157 if (Idx < Ops.size()) {
3158 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003159 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003160 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003161 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003162 DeletedSMax = true;
3163 }
3164
3165 if (DeletedSMax)
3166 return getSMaxExpr(Ops);
3167 }
3168
3169 // Okay, check to see if the same value occurs in the operand list twice. If
3170 // so, delete one. Since we sorted the list, these values are required to
3171 // be adjacent.
3172 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003173 // X smax Y smax Y --> X smax Y
3174 // X smax Y --> X, if X is always greater than Y
3175 if (Ops[i] == Ops[i+1] ||
3176 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3177 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3178 --i; --e;
3179 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003180 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3181 --i; --e;
3182 }
3183
3184 if (Ops.size() == 1) return Ops[0];
3185
3186 assert(!Ops.empty() && "Reduced smax down to nothing!");
3187
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003188 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003189 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003190 FoldingSetNodeID ID;
3191 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003192 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3193 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003194 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003195 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003196 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3197 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003198 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3199 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003200 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003201 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003202 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003203}
3204
Dan Gohmanabd17092009-06-24 14:49:00 +00003205const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3206 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003207 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003208 return getUMaxExpr(Ops);
3209}
3210
Dan Gohmanaf752342009-07-07 17:06:11 +00003211const SCEV *
3212ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003213 assert(!Ops.empty() && "Cannot get empty umax!");
3214 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003215#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003216 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003217 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003218 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003219 "SCEVUMaxExpr operand types don't match!");
3220#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003221
3222 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003223 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003224
3225 // If there are any constants, fold them together.
3226 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003227 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003228 ++Idx;
3229 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003230 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003231 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003232 ConstantInt *Fold = ConstantInt::get(
3233 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003234 Ops[0] = getConstant(Fold);
3235 Ops.erase(Ops.begin()+1); // Erase the folded element
3236 if (Ops.size() == 1) return Ops[0];
3237 LHSC = cast<SCEVConstant>(Ops[0]);
3238 }
3239
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003240 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003241 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3242 Ops.erase(Ops.begin());
3243 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003244 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3245 // If we have an umax with a constant maximum-int, it will always be
3246 // maximum-int.
3247 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003248 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003249
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003250 if (Ops.size() == 1) return Ops[0];
3251 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003252
3253 // Find the first UMax
3254 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3255 ++Idx;
3256
3257 // Check to see if one of the operands is a UMax. If so, expand its operands
3258 // onto our operand list, and recurse to simplify.
3259 if (Idx < Ops.size()) {
3260 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003261 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003262 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003263 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003264 DeletedUMax = true;
3265 }
3266
3267 if (DeletedUMax)
3268 return getUMaxExpr(Ops);
3269 }
3270
3271 // Okay, check to see if the same value occurs in the operand list twice. If
3272 // so, delete one. Since we sorted the list, these values are required to
3273 // be adjacent.
3274 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003275 // X umax Y umax Y --> X umax Y
3276 // X umax Y --> X, if X is always greater than Y
3277 if (Ops[i] == Ops[i+1] ||
3278 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3279 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3280 --i; --e;
3281 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003282 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3283 --i; --e;
3284 }
3285
3286 if (Ops.size() == 1) return Ops[0];
3287
3288 assert(!Ops.empty() && "Reduced umax down to nothing!");
3289
3290 // Okay, it looks like we really DO need a umax expr. Check to see if we
3291 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003292 FoldingSetNodeID ID;
3293 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003294 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3295 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003296 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003297 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003298 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3299 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003300 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3301 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003302 UniqueSCEVs.InsertNode(S, IP);
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003303 addAffectedFromOperands(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003304 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003305}
3306
Dan Gohmanabd17092009-06-24 14:49:00 +00003307const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3308 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003309 // ~smax(~x, ~y) == smin(x, y).
3310 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3311}
3312
Dan Gohmanabd17092009-06-24 14:49:00 +00003313const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3314 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003315 // ~umax(~x, ~y) == umin(x, y)
3316 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3317}
3318
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003319const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003320 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003321 // constant expression and then folding it back into a ConstantInt.
3322 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003323 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003324}
3325
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003326const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3327 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003328 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003329 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003330 // constant expression and then folding it back into a ConstantInt.
3331 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003332 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003333 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003334}
3335
Dan Gohmanaf752342009-07-07 17:06:11 +00003336const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003337 // Don't attempt to do anything other than create a SCEVUnknown object
3338 // here. createSCEV only calls getUnknown after checking for all other
3339 // interesting possibilities, and any other code that calls getUnknown
3340 // is doing so in order to hide a value from SCEV canonicalization.
3341
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003342 FoldingSetNodeID ID;
3343 ID.AddInteger(scUnknown);
3344 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003345 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003346 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3347 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3348 "Stale SCEVUnknown in uniquing map!");
3349 return S;
3350 }
3351 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3352 FirstUnknown);
3353 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003354 UniqueSCEVs.InsertNode(S, IP);
3355 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003356}
3357
Chris Lattnerd934c702004-04-02 20:23:17 +00003358//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003359// Basic SCEV Analysis and PHI Idiom Recognition Code
3360//
3361
Sanjoy Dasf8570812016-05-29 00:38:22 +00003362/// Test if values of the given type are analyzable within the SCEV
3363/// framework. This primarily includes integer types, and it can optionally
3364/// include pointer types if the ScalarEvolution class has access to
3365/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003366bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003367 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003368 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003369}
3370
Sanjoy Dasf8570812016-05-29 00:38:22 +00003371/// Return the size in bits of the specified type, for which isSCEVable must
3372/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003373uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003374 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003375 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003376}
3377
Sanjoy Dasf8570812016-05-29 00:38:22 +00003378/// Return a type with the same bitwidth as the given type and which represents
3379/// how SCEV will treat the given type, for which isSCEVable must return
3380/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003381Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003382 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3383
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003384 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003385 return Ty;
3386
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003387 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003388 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003389 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003390}
Chris Lattnerd934c702004-04-02 20:23:17 +00003391
Dan Gohmanaf752342009-07-07 17:06:11 +00003392const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003393 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003394}
3395
Sanjoy Das7d752672015-12-08 04:32:54 +00003396bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003397 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3398 auto *SU = dyn_cast<SCEVUnknown>(S);
3399 return SU && SU->getValue() == nullptr;
3400 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003401
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003402 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003403}
3404
Wei Mia49559b2016-02-04 01:27:38 +00003405bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003406 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003407 if (I != HasRecMap.end())
3408 return I->second;
3409
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003410 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003411 HasRecMap.insert({S, FoundAddRec});
3412 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003413}
3414
Wei Mi785858c2016-08-09 20:37:50 +00003415/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3416/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3417/// offset I, then return {S', I}, else return {\p S, nullptr}.
3418static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3419 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3420 if (!Add)
3421 return {S, nullptr};
3422
3423 if (Add->getNumOperands() != 2)
3424 return {S, nullptr};
3425
3426 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3427 if (!ConstOp)
3428 return {S, nullptr};
3429
3430 return {Add->getOperand(1), ConstOp->getValue()};
3431}
3432
3433/// Return the ValueOffsetPair set for \p S. \p S can be represented
3434/// by the value and offset from any ValueOffsetPair in the set.
3435SetVector<ScalarEvolution::ValueOffsetPair> *
3436ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003437 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3438 if (SI == ExprValueMap.end())
3439 return nullptr;
3440#ifndef NDEBUG
3441 if (VerifySCEVMap) {
3442 // Check there is no dangling Value in the set returned.
3443 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003444 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003445 }
3446#endif
3447 return &SI->second;
3448}
3449
Wei Mi785858c2016-08-09 20:37:50 +00003450/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3451/// cannot be used separately. eraseValueFromMap should be used to remove
3452/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003453void ScalarEvolution::eraseValueFromMap(Value *V) {
3454 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3455 if (I != ValueExprMap.end()) {
3456 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003457 // Remove {V, 0} from the set of ExprValueMap[S]
3458 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3459 SV->remove({V, nullptr});
3460
3461 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3462 const SCEV *Stripped;
3463 ConstantInt *Offset;
3464 std::tie(Stripped, Offset) = splitAddExpr(S);
3465 if (Offset != nullptr) {
3466 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3467 SV->remove({V, Offset});
3468 }
Wei Mia49559b2016-02-04 01:27:38 +00003469 ValueExprMap.erase(V);
3470 }
3471}
3472
Sanjoy Dasf8570812016-05-29 00:38:22 +00003473/// Return an existing SCEV if it exists, otherwise analyze the expression and
3474/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003475const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003476 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003477
Jingyue Wu42f1d672015-07-28 18:22:40 +00003478 const SCEV *S = getExistingSCEV(V);
3479 if (S == nullptr) {
3480 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003481 // During PHI resolution, it is possible to create two SCEVs for the same
3482 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003483 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003484 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003485 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003486 if (Pair.second) {
3487 ExprValueMap[S].insert({V, nullptr});
3488
3489 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3490 // ExprValueMap.
3491 const SCEV *Stripped = S;
3492 ConstantInt *Offset = nullptr;
3493 std::tie(Stripped, Offset) = splitAddExpr(S);
3494 // If stripped is SCEVUnknown, don't bother to save
3495 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3496 // increase the complexity of the expansion code.
3497 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3498 // because it may generate add/sub instead of GEP in SCEV expansion.
3499 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3500 !isa<GetElementPtrInst>(V))
3501 ExprValueMap[Stripped].insert({V, Offset});
3502 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003503 }
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003504
3505 // If this value is an instruction or an argument, and might be affected by
3506 // an assumption, and its SCEV to the AffectedMap.
3507 if (isa<Instruction>(V) || isa<Argument>(V)) {
3508 for (auto *U : V->users()) {
3509 auto *II = dyn_cast<IntrinsicInst>(U);
3510 if (!II)
3511 continue;
3512 if (II->getIntrinsicID() != Intrinsic::assume)
3513 continue;
3514
3515 AffectedMap[S].insert(II);
3516 }
3517 }
3518
Jingyue Wu42f1d672015-07-28 18:22:40 +00003519 return S;
3520}
3521
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003522// If one of this SCEV's operands is in the AffectedMap (meaning that it might
3523// be affected by an assumption), then this SCEV might be affected by the same
3524// assumption.
3525void ScalarEvolution::addAffectedFromOperands(const SCEV *S) {
3526 if (auto *NS = dyn_cast<SCEVNAryExpr>(S))
3527 for (auto *Op : NS->operands()) {
3528 auto AMI = AffectedMap.find(Op);
3529 if (AMI == AffectedMap.end())
3530 continue;
3531
Hal Finkel321053a2016-12-15 03:30:40 +00003532 auto &ISet = AffectedMap[S];
3533 AMI = AffectedMap.find(Op);
3534 ISet.insert(AMI->second.begin(), AMI->second.end());
Hal Finkelcb9f78e2016-12-15 02:53:42 +00003535 }
3536}
3537
Jingyue Wu42f1d672015-07-28 18:22:40 +00003538const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3539 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3540
Shuxin Yangefc4c012013-07-08 17:33:13 +00003541 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3542 if (I != ValueExprMap.end()) {
3543 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003544 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003545 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003546 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003547 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003548 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003549 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003550}
3551
Sanjoy Dasf8570812016-05-29 00:38:22 +00003552/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003553///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003554const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3555 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003556 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003557 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003558 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003559
Chris Lattner229907c2011-07-18 04:54:35 +00003560 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003561 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003562 return getMulExpr(
3563 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003564}
3565
Sanjoy Dasf8570812016-05-29 00:38:22 +00003566/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003567const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003568 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003569 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003570 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003571
Chris Lattner229907c2011-07-18 04:54:35 +00003572 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003573 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003574 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003575 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003576 return getMinusSCEV(AllOnes, V);
3577}
3578
Chris Lattnerfc877522011-01-09 22:26:35 +00003579const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003580 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003581 // Fast path: X - X --> 0.
3582 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003583 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003584
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003585 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3586 // makes it so that we cannot make much use of NUW.
3587 auto AddFlags = SCEV::FlagAnyWrap;
3588 const bool RHSIsNotMinSigned =
3589 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3590 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3591 // Let M be the minimum representable signed value. Then (-1)*RHS
3592 // signed-wraps if and only if RHS is M. That can happen even for
3593 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3594 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3595 // (-1)*RHS, we need to prove that RHS != M.
3596 //
3597 // If LHS is non-negative and we know that LHS - RHS does not
3598 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3599 // either by proving that RHS > M or that LHS >= 0.
3600 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3601 AddFlags = SCEV::FlagNSW;
3602 }
3603 }
3604
3605 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3606 // RHS is NSW and LHS >= 0.
3607 //
3608 // The difficulty here is that the NSW flag may have been proven
3609 // relative to a loop that is to be found in a recurrence in LHS and
3610 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3611 // larger scope than intended.
3612 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3613
3614 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003615}
3616
Dan Gohmanaf752342009-07-07 17:06:11 +00003617const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003618ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3619 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003620 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3621 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003622 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003623 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003624 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003625 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003626 return getTruncateExpr(V, Ty);
3627 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003628}
3629
Dan Gohmanaf752342009-07-07 17:06:11 +00003630const SCEV *
3631ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003632 Type *Ty) {
3633 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003634 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3635 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003636 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003637 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003638 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003639 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003640 return getTruncateExpr(V, Ty);
3641 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003642}
3643
Dan Gohmanaf752342009-07-07 17:06:11 +00003644const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003645ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3646 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003647 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3648 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003649 "Cannot noop or zero extend with non-integer arguments!");
3650 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3651 "getNoopOrZeroExtend cannot truncate!");
3652 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3653 return V; // No conversion
3654 return getZeroExtendExpr(V, Ty);
3655}
3656
Dan Gohmanaf752342009-07-07 17:06:11 +00003657const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003658ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3659 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003660 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3661 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003662 "Cannot noop or sign extend with non-integer arguments!");
3663 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3664 "getNoopOrSignExtend cannot truncate!");
3665 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3666 return V; // No conversion
3667 return getSignExtendExpr(V, Ty);
3668}
3669
Dan Gohmanaf752342009-07-07 17:06:11 +00003670const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003671ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3672 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003673 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3674 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003675 "Cannot noop or any extend with non-integer arguments!");
3676 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3677 "getNoopOrAnyExtend cannot truncate!");
3678 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3679 return V; // No conversion
3680 return getAnyExtendExpr(V, Ty);
3681}
3682
Dan Gohmanaf752342009-07-07 17:06:11 +00003683const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003684ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3685 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003686 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3687 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003688 "Cannot truncate or noop with non-integer arguments!");
3689 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3690 "getTruncateOrNoop cannot extend!");
3691 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3692 return V; // No conversion
3693 return getTruncateExpr(V, Ty);
3694}
3695
Dan Gohmanabd17092009-06-24 14:49:00 +00003696const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3697 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003698 const SCEV *PromotedLHS = LHS;
3699 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003700
3701 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3702 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3703 else
3704 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3705
3706 return getUMaxExpr(PromotedLHS, PromotedRHS);
3707}
3708
Dan Gohmanabd17092009-06-24 14:49:00 +00003709const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3710 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003711 const SCEV *PromotedLHS = LHS;
3712 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003713
3714 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3715 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3716 else
3717 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3718
3719 return getUMinExpr(PromotedLHS, PromotedRHS);
3720}
3721
Andrew Trick87716c92011-03-17 23:51:11 +00003722const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3723 // A pointer operand may evaluate to a nonpointer expression, such as null.
3724 if (!V->getType()->isPointerTy())
3725 return V;
3726
3727 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3728 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003729 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003730 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003731 for (const SCEV *NAryOp : NAry->operands()) {
3732 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003733 // Cannot find the base of an expression with multiple pointer operands.
3734 if (PtrOp)
3735 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003736 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003737 }
3738 }
3739 if (!PtrOp)
3740 return V;
3741 return getPointerBase(PtrOp);
3742 }
3743 return V;
3744}
3745
Sanjoy Dasf8570812016-05-29 00:38:22 +00003746/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003747static void
3748PushDefUseChildren(Instruction *I,
3749 SmallVectorImpl<Instruction *> &Worklist) {
3750 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003751 for (User *U : I->users())
3752 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003753}
3754
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003755void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003756 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003757 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003758
Dan Gohman0b89dff2009-07-25 01:13:03 +00003759 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003760 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003761 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003762 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003763 if (!Visited.insert(I).second)
3764 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003765
Sanjoy Das63914592015-10-18 00:29:20 +00003766 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003767 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003768 const SCEV *Old = It->second;
3769
Dan Gohman0b89dff2009-07-25 01:13:03 +00003770 // Short-circuit the def-use traversal if the symbolic name
3771 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003772 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003773 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003774
Dan Gohman0b89dff2009-07-25 01:13:03 +00003775 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003776 // structure, it's a PHI that's in the progress of being computed
3777 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3778 // additional loop trip count information isn't going to change anything.
3779 // In the second case, createNodeForPHI will perform the necessary
3780 // updates on its own when it gets to that point. In the third, we do
3781 // want to forget the SCEVUnknown.
3782 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003783 !isa<SCEVUnknown>(Old) ||
3784 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003785 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003786 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003787 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003788 }
3789
3790 PushDefUseChildren(I, Worklist);
3791 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003792}
Chris Lattnerd934c702004-04-02 20:23:17 +00003793
Benjamin Kramer83709b12015-11-16 09:01:28 +00003794namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003795class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3796public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003797 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003798 ScalarEvolution &SE) {
3799 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003800 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003801 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3802 }
3803
3804 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3805 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3806
3807 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3808 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3809 Valid = false;
3810 return Expr;
3811 }
3812
3813 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3814 // Only allow AddRecExprs for this loop.
3815 if (Expr->getLoop() == L)
3816 return Expr->getStart();
3817 Valid = false;
3818 return Expr;
3819 }
3820
3821 bool isValid() { return Valid; }
3822
3823private:
3824 const Loop *L;
3825 bool Valid;
3826};
3827
3828class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3829public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003830 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003831 ScalarEvolution &SE) {
3832 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003833 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003834 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3835 }
3836
3837 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3838 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3839
3840 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3841 // Only allow AddRecExprs for this loop.
3842 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3843 Valid = false;
3844 return Expr;
3845 }
3846
3847 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3848 if (Expr->getLoop() == L && Expr->isAffine())
3849 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3850 Valid = false;
3851 return Expr;
3852 }
3853 bool isValid() { return Valid; }
3854
3855private:
3856 const Loop *L;
3857 bool Valid;
3858};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003859} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003860
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003861SCEV::NoWrapFlags
3862ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3863 if (!AR->isAffine())
3864 return SCEV::FlagAnyWrap;
3865
3866 typedef OverflowingBinaryOperator OBO;
3867 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3868
3869 if (!AR->hasNoSignedWrap()) {
3870 ConstantRange AddRecRange = getSignedRange(AR);
3871 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3872
3873 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3874 Instruction::Add, IncRange, OBO::NoSignedWrap);
3875 if (NSWRegion.contains(AddRecRange))
3876 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3877 }
3878
3879 if (!AR->hasNoUnsignedWrap()) {
3880 ConstantRange AddRecRange = getUnsignedRange(AR);
3881 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3882
3883 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3884 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3885 if (NUWRegion.contains(AddRecRange))
3886 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3887 }
3888
3889 return Result;
3890}
3891
Sanjoy Das118d9192016-03-31 05:14:22 +00003892namespace {
3893/// Represents an abstract binary operation. This may exist as a
3894/// normal instruction or constant expression, or may have been
3895/// derived from an expression tree.
3896struct BinaryOp {
3897 unsigned Opcode;
3898 Value *LHS;
3899 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003900 bool IsNSW;
3901 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003902
3903 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3904 /// constant expression.
3905 Operator *Op;
3906
3907 explicit BinaryOp(Operator *Op)
3908 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003909 IsNSW(false), IsNUW(false), Op(Op) {
3910 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3911 IsNSW = OBO->hasNoSignedWrap();
3912 IsNUW = OBO->hasNoUnsignedWrap();
3913 }
3914 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003915
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003916 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3917 bool IsNUW = false)
3918 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3919 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003920};
3921}
3922
3923
3924/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003925static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003926 auto *Op = dyn_cast<Operator>(V);
3927 if (!Op)
3928 return None;
3929
3930 // Implementation detail: all the cleverness here should happen without
3931 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3932 // SCEV expressions when possible, and we should not break that.
3933
3934 switch (Op->getOpcode()) {
3935 case Instruction::Add:
3936 case Instruction::Sub:
3937 case Instruction::Mul:
3938 case Instruction::UDiv:
3939 case Instruction::And:
3940 case Instruction::Or:
3941 case Instruction::AShr:
3942 case Instruction::Shl:
3943 return BinaryOp(Op);
3944
3945 case Instruction::Xor:
3946 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3947 // If the RHS of the xor is a signbit, then this is just an add.
3948 // Instcombine turns add of signbit into xor as a strength reduction step.
3949 if (RHSC->getValue().isSignBit())
3950 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3951 return BinaryOp(Op);
3952
3953 case Instruction::LShr:
3954 // Turn logical shift right of a constant into a unsigned divide.
3955 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3956 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3957
3958 // If the shift count is not less than the bitwidth, the result of
3959 // the shift is undefined. Don't try to analyze it, because the
3960 // resolution chosen here may differ from the resolution chosen in
3961 // other parts of the compiler.
3962 if (SA->getValue().ult(BitWidth)) {
3963 Constant *X =
3964 ConstantInt::get(SA->getContext(),
3965 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3966 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3967 }
3968 }
3969 return BinaryOp(Op);
3970
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003971 case Instruction::ExtractValue: {
3972 auto *EVI = cast<ExtractValueInst>(Op);
3973 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3974 break;
3975
3976 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3977 if (!CI)
3978 break;
3979
3980 if (auto *F = CI->getCalledFunction())
3981 switch (F->getIntrinsicID()) {
3982 case Intrinsic::sadd_with_overflow:
3983 case Intrinsic::uadd_with_overflow: {
3984 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3985 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3986 CI->getArgOperand(1));
3987
3988 // Now that we know that all uses of the arithmetic-result component of
3989 // CI are guarded by the overflow check, we can go ahead and pretend
3990 // that the arithmetic is non-overflowing.
3991 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3992 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3993 CI->getArgOperand(1), /* IsNSW = */ true,
3994 /* IsNUW = */ false);
3995 else
3996 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3997 CI->getArgOperand(1), /* IsNSW = */ false,
3998 /* IsNUW*/ true);
3999 }
4000
4001 case Intrinsic::ssub_with_overflow:
4002 case Intrinsic::usub_with_overflow:
4003 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4004 CI->getArgOperand(1));
4005
4006 case Intrinsic::smul_with_overflow:
4007 case Intrinsic::umul_with_overflow:
4008 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4009 CI->getArgOperand(1));
4010 default:
4011 break;
4012 }
4013 }
4014
Sanjoy Das118d9192016-03-31 05:14:22 +00004015 default:
4016 break;
4017 }
4018
4019 return None;
4020}
4021
Sanjoy Das55015d22015-10-02 23:09:44 +00004022const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4023 const Loop *L = LI.getLoopFor(PN->getParent());
4024 if (!L || L->getHeader() != PN->getParent())
4025 return nullptr;
4026
4027 // The loop may have multiple entrances or multiple exits; we can analyze
4028 // this phi as an addrec if it has a unique entry value and a unique
4029 // backedge value.
4030 Value *BEValueV = nullptr, *StartValueV = nullptr;
4031 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4032 Value *V = PN->getIncomingValue(i);
4033 if (L->contains(PN->getIncomingBlock(i))) {
4034 if (!BEValueV) {
4035 BEValueV = V;
4036 } else if (BEValueV != V) {
4037 BEValueV = nullptr;
4038 break;
4039 }
4040 } else if (!StartValueV) {
4041 StartValueV = V;
4042 } else if (StartValueV != V) {
4043 StartValueV = nullptr;
4044 break;
4045 }
4046 }
4047 if (BEValueV && StartValueV) {
4048 // While we are analyzing this PHI node, handle its value symbolically.
4049 const SCEV *SymbolicName = getUnknown(PN);
4050 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4051 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00004052 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004053
4054 // Using this symbolic name for the PHI, analyze the value coming around
4055 // the back-edge.
4056 const SCEV *BEValue = getSCEV(BEValueV);
4057
4058 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4059 // has a special value for the first iteration of the loop.
4060
4061 // If the value coming around the backedge is an add with the symbolic
4062 // value we just inserted, then we found a simple induction variable!
4063 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4064 // If there is a single occurrence of the symbolic value, replace it
4065 // with a recurrence.
4066 unsigned FoundIndex = Add->getNumOperands();
4067 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4068 if (Add->getOperand(i) == SymbolicName)
4069 if (FoundIndex == e) {
4070 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004071 break;
4072 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004073
4074 if (FoundIndex != Add->getNumOperands()) {
4075 // Create an add with everything but the specified operand.
4076 SmallVector<const SCEV *, 8> Ops;
4077 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4078 if (i != FoundIndex)
4079 Ops.push_back(Add->getOperand(i));
4080 const SCEV *Accum = getAddExpr(Ops);
4081
4082 // This is not a valid addrec if the step amount is varying each
4083 // loop iteration, but is not itself an addrec in this loop.
4084 if (isLoopInvariant(Accum, L) ||
4085 (isa<SCEVAddRecExpr>(Accum) &&
4086 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4087 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4088
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004089 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004090 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4091 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004092 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004093 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004094 Flags = setFlags(Flags, SCEV::FlagNSW);
4095 }
4096 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4097 // If the increment is an inbounds GEP, then we know the address
4098 // space cannot be wrapped around. We cannot make any guarantee
4099 // about signed or unsigned overflow because pointers are
4100 // unsigned but we may have a negative index from the base
4101 // pointer. We can guarantee that no unsigned wrap occurs if the
4102 // indices form a positive value.
4103 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4104 Flags = setFlags(Flags, SCEV::FlagNW);
4105
4106 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4107 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4108 Flags = setFlags(Flags, SCEV::FlagNUW);
4109 }
4110
4111 // We cannot transfer nuw and nsw flags from subtraction
4112 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4113 // for instance.
4114 }
4115
4116 const SCEV *StartVal = getSCEV(StartValueV);
4117 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4118
Sanjoy Das55015d22015-10-02 23:09:44 +00004119 // Okay, for the entire analysis of this edge we assumed the PHI
4120 // to be symbolic. We now need to go back and purge all of the
4121 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004122 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004123 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004124
4125 // We can add Flags to the post-inc expression only if we
4126 // know that it us *undefined behavior* for BEValueV to
4127 // overflow.
4128 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4129 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4130 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4131
Sanjoy Das55015d22015-10-02 23:09:44 +00004132 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004133 }
4134 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004135 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004136 // Otherwise, this could be a loop like this:
4137 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4138 // In this case, j = {1,+,1} and BEValue is j.
4139 // Because the other in-value of i (0) fits the evolution of BEValue
4140 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004141 //
4142 // We can generalize this saying that i is the shifted value of BEValue
4143 // by one iteration:
4144 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4145 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4146 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4147 if (Shifted != getCouldNotCompute() &&
4148 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004149 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004150 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004151 // Okay, for the entire analysis of this edge we assumed the PHI
4152 // to be symbolic. We now need to go back and purge all of the
4153 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004154 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004155 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4156 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004157 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004158 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004159 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004160
4161 // Remove the temporary PHI node SCEV that has been inserted while intending
4162 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4163 // as it will prevent later (possibly simpler) SCEV expressions to be added
4164 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004165 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004166 }
4167
4168 return nullptr;
4169}
4170
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004171// Checks if the SCEV S is available at BB. S is considered available at BB
4172// if S can be materialized at BB without introducing a fault.
4173static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4174 BasicBlock *BB) {
4175 struct CheckAvailable {
4176 bool TraversalDone = false;
4177 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004178
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004179 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4180 BasicBlock *BB = nullptr;
4181 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004182
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004183 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4184 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004185
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004186 bool setUnavailable() {
4187 TraversalDone = true;
4188 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004189 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004190 }
4191
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004192 bool follow(const SCEV *S) {
4193 switch (S->getSCEVType()) {
4194 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4195 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004196 // These expressions are available if their operand(s) is/are.
4197 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004198
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004199 case scAddRecExpr: {
4200 // We allow add recurrences that are on the loop BB is in, or some
4201 // outer loop. This guarantees availability because the value of the
4202 // add recurrence at BB is simply the "current" value of the induction
4203 // variable. We can relax this in the future; for instance an add
4204 // recurrence on a sibling dominating loop is also available at BB.
4205 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4206 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004207 return true;
4208
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004209 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004210 }
4211
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004212 case scUnknown: {
4213 // For SCEVUnknown, we check for simple dominance.
4214 const auto *SU = cast<SCEVUnknown>(S);
4215 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004216
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004217 if (isa<Argument>(V))
4218 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004219
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004220 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4221 return false;
4222
4223 return setUnavailable();
4224 }
4225
4226 case scUDivExpr:
4227 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004228 // We do not try to smart about these at all.
4229 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004230 }
4231 llvm_unreachable("switch should be fully covered!");
4232 }
4233
4234 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004235 };
4236
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004237 CheckAvailable CA(L, BB, DT);
4238 SCEVTraversal<CheckAvailable> ST(CA);
4239
4240 ST.visitAll(S);
4241 return CA.Available;
4242}
4243
4244// Try to match a control flow sequence that branches out at BI and merges back
4245// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4246// match.
4247static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4248 Value *&C, Value *&LHS, Value *&RHS) {
4249 C = BI->getCondition();
4250
4251 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4252 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4253
4254 if (!LeftEdge.isSingleEdge())
4255 return false;
4256
4257 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4258
4259 Use &LeftUse = Merge->getOperandUse(0);
4260 Use &RightUse = Merge->getOperandUse(1);
4261
4262 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4263 LHS = LeftUse;
4264 RHS = RightUse;
4265 return true;
4266 }
4267
4268 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4269 LHS = RightUse;
4270 RHS = LeftUse;
4271 return true;
4272 }
4273
4274 return false;
4275}
4276
4277const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004278 auto IsReachable =
4279 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4280 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004281 const Loop *L = LI.getLoopFor(PN->getParent());
4282
Sanjoy Das337d4782015-10-31 23:21:40 +00004283 // We don't want to break LCSSA, even in a SCEV expression tree.
4284 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4285 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4286 return nullptr;
4287
Sanjoy Das55015d22015-10-02 23:09:44 +00004288 // Try to match
4289 //
4290 // br %cond, label %left, label %right
4291 // left:
4292 // br label %merge
4293 // right:
4294 // br label %merge
4295 // merge:
4296 // V = phi [ %x, %left ], [ %y, %right ]
4297 //
4298 // as "select %cond, %x, %y"
4299
4300 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4301 assert(IDom && "At least the entry block should dominate PN");
4302
4303 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4304 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4305
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004306 if (BI && BI->isConditional() &&
4307 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4308 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4309 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004310 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4311 }
4312
4313 return nullptr;
4314}
4315
4316const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4317 if (const SCEV *S = createAddRecFromPHI(PN))
4318 return S;
4319
4320 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4321 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004322
Dan Gohmana9c205c2010-02-25 06:57:05 +00004323 // If the PHI has a single incoming value, follow that value, unless the
4324 // PHI's incoming blocks are in a different loop, in which case doing so
4325 // risks breaking LCSSA form. Instcombine would normally zap these, but
4326 // it doesn't have DominatorTree information, so it may miss cases.
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004327 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004328 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004329 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004330
Chris Lattnerd934c702004-04-02 20:23:17 +00004331 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004332 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004333}
4334
Sanjoy Das55015d22015-10-02 23:09:44 +00004335const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4336 Value *Cond,
4337 Value *TrueVal,
4338 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004339 // Handle "constant" branch or select. This can occur for instance when a
4340 // loop pass transforms an inner loop and moves on to process the outer loop.
4341 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4342 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4343
Sanjoy Dasd0671342015-10-02 19:39:59 +00004344 // Try to match some simple smax or umax patterns.
4345 auto *ICI = dyn_cast<ICmpInst>(Cond);
4346 if (!ICI)
4347 return getUnknown(I);
4348
4349 Value *LHS = ICI->getOperand(0);
4350 Value *RHS = ICI->getOperand(1);
4351
4352 switch (ICI->getPredicate()) {
4353 case ICmpInst::ICMP_SLT:
4354 case ICmpInst::ICMP_SLE:
4355 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004356 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004357 case ICmpInst::ICMP_SGT:
4358 case ICmpInst::ICMP_SGE:
4359 // a >s b ? a+x : b+x -> smax(a, b)+x
4360 // a >s b ? b+x : a+x -> smin(a, b)+x
4361 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4362 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4363 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4364 const SCEV *LA = getSCEV(TrueVal);
4365 const SCEV *RA = getSCEV(FalseVal);
4366 const SCEV *LDiff = getMinusSCEV(LA, LS);
4367 const SCEV *RDiff = getMinusSCEV(RA, RS);
4368 if (LDiff == RDiff)
4369 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4370 LDiff = getMinusSCEV(LA, RS);
4371 RDiff = getMinusSCEV(RA, LS);
4372 if (LDiff == RDiff)
4373 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4374 }
4375 break;
4376 case ICmpInst::ICMP_ULT:
4377 case ICmpInst::ICMP_ULE:
4378 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004379 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004380 case ICmpInst::ICMP_UGT:
4381 case ICmpInst::ICMP_UGE:
4382 // a >u b ? a+x : b+x -> umax(a, b)+x
4383 // a >u b ? b+x : a+x -> umin(a, b)+x
4384 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4385 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4386 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4387 const SCEV *LA = getSCEV(TrueVal);
4388 const SCEV *RA = getSCEV(FalseVal);
4389 const SCEV *LDiff = getMinusSCEV(LA, LS);
4390 const SCEV *RDiff = getMinusSCEV(RA, RS);
4391 if (LDiff == RDiff)
4392 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4393 LDiff = getMinusSCEV(LA, RS);
4394 RDiff = getMinusSCEV(RA, LS);
4395 if (LDiff == RDiff)
4396 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4397 }
4398 break;
4399 case ICmpInst::ICMP_NE:
4400 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4401 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4402 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4403 const SCEV *One = getOne(I->getType());
4404 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4405 const SCEV *LA = getSCEV(TrueVal);
4406 const SCEV *RA = getSCEV(FalseVal);
4407 const SCEV *LDiff = getMinusSCEV(LA, LS);
4408 const SCEV *RDiff = getMinusSCEV(RA, One);
4409 if (LDiff == RDiff)
4410 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4411 }
4412 break;
4413 case ICmpInst::ICMP_EQ:
4414 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4415 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4416 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4417 const SCEV *One = getOne(I->getType());
4418 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4419 const SCEV *LA = getSCEV(TrueVal);
4420 const SCEV *RA = getSCEV(FalseVal);
4421 const SCEV *LDiff = getMinusSCEV(LA, One);
4422 const SCEV *RDiff = getMinusSCEV(RA, LS);
4423 if (LDiff == RDiff)
4424 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4425 }
4426 break;
4427 default:
4428 break;
4429 }
4430
4431 return getUnknown(I);
4432}
4433
Sanjoy Dasf8570812016-05-29 00:38:22 +00004434/// Expand GEP instructions into add and multiply operations. This allows them
4435/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004436const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004437 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004438 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004439 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004440
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004441 SmallVector<const SCEV *, 4> IndexExprs;
4442 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4443 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004444 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004445}
4446
Dan Gohmanc702fc02009-06-19 23:29:04 +00004447uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004448ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004449 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004450 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004451
Dan Gohmana30370b2009-05-04 22:02:23 +00004452 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004453 return std::min(GetMinTrailingZeros(T->getOperand()),
4454 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004455
Dan Gohmana30370b2009-05-04 22:02:23 +00004456 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004457 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4458 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4459 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004460 }
4461
Dan Gohmana30370b2009-05-04 22:02:23 +00004462 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004463 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4464 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4465 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004466 }
4467
Dan Gohmana30370b2009-05-04 22:02:23 +00004468 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004469 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004470 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004471 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004472 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004473 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004474 }
4475
Dan Gohmana30370b2009-05-04 22:02:23 +00004476 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004477 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004478 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4479 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004480 for (unsigned i = 1, e = M->getNumOperands();
4481 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004482 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004483 BitWidth);
4484 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004485 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004486
Dan Gohmana30370b2009-05-04 22:02:23 +00004487 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004488 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004489 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004490 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004491 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004492 return MinOpRes;
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 SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004496 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004497 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004498 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004500 return MinOpRes;
4501 }
4502
Dan Gohmana30370b2009-05-04 22:02:23 +00004503 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +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 Lewycky1c44ebc2008-02-20 06:48:22 +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 Lewycky1c44ebc2008-02-20 06:48:22 +00004508 return MinOpRes;
4509 }
4510
Dan Gohmanc702fc02009-06-19 23:29:04 +00004511 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4512 // For a SCEVUnknown, ask ValueTracking.
4513 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004514 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004515 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004516 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004517 return Zeros.countTrailingOnes();
4518 }
4519
4520 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004521 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004522}
Chris Lattnerd934c702004-04-02 20:23:17 +00004523
Sanjoy Dasf8570812016-05-29 00:38:22 +00004524/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004525static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004526 if (Instruction *I = dyn_cast<Instruction>(V))
4527 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4528 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004529
4530 return None;
4531}
4532
Sanjoy Dasf8570812016-05-29 00:38:22 +00004533/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004534/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4535/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004536ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004537ScalarEvolution::getRange(const SCEV *S,
4538 ScalarEvolution::RangeSignHint SignHint) {
4539 DenseMap<const SCEV *, ConstantRange> &Cache =
4540 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4541 : SignedRanges;
4542
Dan Gohman761065e2010-11-17 02:44:44 +00004543 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004544 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4545 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004546 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004547
4548 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004549 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004550
Dan Gohman85be4332010-01-26 19:19:05 +00004551 unsigned BitWidth = getTypeSizeInBits(S->getType());
4552 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4553
Sanjoy Das91b54772015-03-09 21:43:43 +00004554 // If the value has known zeros, the maximum value will have those known zeros
4555 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004556 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004557 if (TZ != 0) {
4558 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4559 ConservativeResult =
4560 ConstantRange(APInt::getMinValue(BitWidth),
4561 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4562 else
4563 ConservativeResult = ConstantRange(
4564 APInt::getSignedMinValue(BitWidth),
4565 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4566 }
Dan Gohman85be4332010-01-26 19:19:05 +00004567
Dan Gohmane65c9172009-07-13 21:35:55 +00004568 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004569 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004570 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004571 X = X.add(getRange(Add->getOperand(i), SignHint));
4572 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004573 }
4574
4575 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004576 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004577 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004578 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4579 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004580 }
4581
4582 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004583 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004584 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004585 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4586 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004587 }
4588
4589 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004590 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004591 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004592 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4593 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004594 }
4595
4596 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004597 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4598 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4599 return setRange(UDiv, SignHint,
4600 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004601 }
4602
4603 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004604 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4605 return setRange(ZExt, SignHint,
4606 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004607 }
4608
4609 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004610 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4611 return setRange(SExt, SignHint,
4612 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004613 }
4614
4615 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004616 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4617 return setRange(Trunc, SignHint,
4618 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004619 }
4620
Dan Gohmane65c9172009-07-13 21:35:55 +00004621 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004622 // If there's no unsigned wrap, the value will never be less than its
4623 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004624 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004625 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004626 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004627 ConservativeResult = ConservativeResult.intersectWith(
4628 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004629
Dan Gohman51ad99d2010-01-21 02:09:26 +00004630 // If there's no signed wrap, and all the operands have the same sign or
4631 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004632 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004633 bool AllNonNeg = true;
4634 bool AllNonPos = true;
4635 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4636 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4637 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4638 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004639 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004640 ConservativeResult = ConservativeResult.intersectWith(
4641 ConstantRange(APInt(BitWidth, 0),
4642 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004643 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004644 ConservativeResult = ConservativeResult.intersectWith(
4645 ConstantRange(APInt::getSignedMinValue(BitWidth),
4646 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004647 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004648
4649 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004650 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004651 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004652 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4653 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004654 auto RangeFromAffine = getRangeForAffineAR(
4655 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4656 BitWidth);
4657 if (!RangeFromAffine.isFullSet())
4658 ConservativeResult =
4659 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004660
4661 auto RangeFromFactoring = getRangeViaFactoring(
4662 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4663 BitWidth);
4664 if (!RangeFromFactoring.isFullSet())
4665 ConservativeResult =
4666 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004667 }
Dan Gohmand261d272009-06-24 01:05:09 +00004668 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004669
Sanjoy Das91b54772015-03-09 21:43:43 +00004670 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004671 }
4672
Dan Gohmanc702fc02009-06-19 23:29:04 +00004673 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004674 // Check if the IR explicitly contains !range metadata.
4675 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4676 if (MDRange.hasValue())
4677 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4678
Sanjoy Das91b54772015-03-09 21:43:43 +00004679 // Split here to avoid paying the compile-time cost of calling both
4680 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4681 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004682 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004683 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4684 // For a SCEVUnknown, ask ValueTracking.
4685 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004686 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004687 if (Ones != ~Zeros + 1)
4688 ConservativeResult =
4689 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4690 } else {
4691 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4692 "generalize as needed!");
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004693 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004694 if (NS > 1)
4695 ConservativeResult = ConservativeResult.intersectWith(
4696 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4697 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004698 }
4699
4700 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004701 }
4702
Sanjoy Das91b54772015-03-09 21:43:43 +00004703 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004704}
4705
Sanjoy Dasb765b632016-03-02 00:57:39 +00004706ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4707 const SCEV *Step,
4708 const SCEV *MaxBECount,
4709 unsigned BitWidth) {
4710 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4711 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4712 "Precondition!");
4713
4714 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4715
4716 // Check for overflow. This must be done with ConstantRange arithmetic
4717 // because we could be called from within the ScalarEvolution overflow
4718 // checking code.
4719
4720 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4721 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4722 ConstantRange ZExtMaxBECountRange =
4723 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4724
4725 ConstantRange StepSRange = getSignedRange(Step);
4726 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4727
4728 ConstantRange StartURange = getUnsignedRange(Start);
4729 ConstantRange EndURange =
4730 StartURange.add(MaxBECountRange.multiply(StepSRange));
4731
4732 // Check for unsigned overflow.
4733 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4734 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4735 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4736 ZExtEndURange) {
4737 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4738 EndURange.getUnsignedMin());
4739 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4740 EndURange.getUnsignedMax());
4741 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4742 if (!IsFullRange)
4743 Result =
4744 Result.intersectWith(ConstantRange(Min, Max + 1));
4745 }
4746
4747 ConstantRange StartSRange = getSignedRange(Start);
4748 ConstantRange EndSRange =
4749 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4750
4751 // Check for signed overflow. This must be done with ConstantRange
4752 // arithmetic because we could be called from within the ScalarEvolution
4753 // overflow checking code.
4754 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4755 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4756 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4757 SExtEndSRange) {
4758 APInt Min =
4759 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4760 APInt Max =
4761 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4762 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4763 if (!IsFullRange)
4764 Result =
4765 Result.intersectWith(ConstantRange(Min, Max + 1));
4766 }
4767
4768 return Result;
4769}
4770
Sanjoy Dasbf730982016-03-02 00:57:54 +00004771ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4772 const SCEV *Step,
4773 const SCEV *MaxBECount,
4774 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004775 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4776 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4777
4778 struct SelectPattern {
4779 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004780 APInt TrueValue;
4781 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004782
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004783 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4784 const SCEV *S) {
4785 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004786 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004787
4788 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4789 "Should be!");
4790
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004791 // Peel off a constant offset:
4792 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4793 // In the future we could consider being smarter here and handle
4794 // {Start+Step,+,Step} too.
4795 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4796 return;
4797
4798 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4799 S = SA->getOperand(1);
4800 }
4801
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004802 // Peel off a cast operation
4803 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4804 CastOp = SCast->getSCEVType();
4805 S = SCast->getOperand();
4806 }
4807
Sanjoy Dasbf730982016-03-02 00:57:54 +00004808 using namespace llvm::PatternMatch;
4809
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004810 auto *SU = dyn_cast<SCEVUnknown>(S);
4811 const APInt *TrueVal, *FalseVal;
4812 if (!SU ||
4813 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4814 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004815 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004816 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004817 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004818
4819 TrueValue = *TrueVal;
4820 FalseValue = *FalseVal;
4821
4822 // Re-apply the cast we peeled off earlier
4823 if (CastOp.hasValue())
4824 switch (*CastOp) {
4825 default:
4826 llvm_unreachable("Unknown SCEV cast type!");
4827
4828 case scTruncate:
4829 TrueValue = TrueValue.trunc(BitWidth);
4830 FalseValue = FalseValue.trunc(BitWidth);
4831 break;
4832 case scZeroExtend:
4833 TrueValue = TrueValue.zext(BitWidth);
4834 FalseValue = FalseValue.zext(BitWidth);
4835 break;
4836 case scSignExtend:
4837 TrueValue = TrueValue.sext(BitWidth);
4838 FalseValue = FalseValue.sext(BitWidth);
4839 break;
4840 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004841
4842 // Re-apply the constant offset we peeled off earlier
4843 TrueValue += Offset;
4844 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004845 }
4846
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004847 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004848 };
4849
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004850 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004851 if (!StartPattern.isRecognized())
4852 return ConstantRange(BitWidth, /* isFullSet = */ true);
4853
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004854 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004855 if (!StepPattern.isRecognized())
4856 return ConstantRange(BitWidth, /* isFullSet = */ true);
4857
4858 if (StartPattern.Condition != StepPattern.Condition) {
4859 // We don't handle this case today; but we could, by considering four
4860 // possibilities below instead of two. I'm not sure if there are cases where
4861 // that will help over what getRange already does, though.
4862 return ConstantRange(BitWidth, /* isFullSet = */ true);
4863 }
4864
4865 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4866 // construct arbitrary general SCEV expressions here. This function is called
4867 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4868 // say) can end up caching a suboptimal value.
4869
Sanjoy Das6b017a12016-03-02 02:56:29 +00004870 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4871 // C2352 and C2512 (otherwise it isn't needed).
4872
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004873 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004874 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004875 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004876 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004877
Sanjoy Das1168f932016-03-02 02:34:20 +00004878 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004879 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004880 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004881 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004882
4883 return TrueRange.unionWith(FalseRange);
4884}
4885
Jingyue Wu42f1d672015-07-28 18:22:40 +00004886SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004887 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004888 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4889
4890 // Return early if there are no flags to propagate to the SCEV.
4891 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4892 if (BinOp->hasNoUnsignedWrap())
4893 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4894 if (BinOp->hasNoSignedWrap())
4895 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004896 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004897 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004898
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004899 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4900}
4901
4902bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4903 // Here we check that I is in the header of the innermost loop containing I,
4904 // since we only deal with instructions in the loop header. The actual loop we
4905 // need to check later will come from an add recurrence, but getting that
4906 // requires computing the SCEV of the operands, which can be expensive. This
4907 // check we can do cheaply to rule out some cases early.
4908 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004909 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004910 InnermostContainingLoop->getHeader() != I->getParent())
4911 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004912
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004913 // Only proceed if we can prove that I does not yield poison.
4914 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004915
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004916 // At this point we know that if I is executed, then it does not wrap
4917 // according to at least one of NSW or NUW. If I is not executed, then we do
4918 // not know if the calculation that I represents would wrap. Multiple
4919 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004920 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4921 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004922 // that guarantee for cases where I is not executed. So we need to find the
4923 // loop that I is considered in relation to and prove that I is executed for
4924 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004925 // calculates does not wrap anywhere in the loop, so then we can apply the
4926 // flags to the SCEV.
4927 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004928 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4929 // from different loops, so that we know which loop to prove that I is
4930 // executed in.
4931 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004932 // I could be an extractvalue from a call to an overflow intrinsic.
4933 // TODO: We can do better here in some cases.
4934 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4935 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004936 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004937 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004938 bool AllOtherOpsLoopInvariant = true;
4939 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4940 ++OtherOpIndex) {
4941 if (OtherOpIndex != OpIndex) {
4942 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4943 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4944 AllOtherOpsLoopInvariant = false;
4945 break;
4946 }
4947 }
4948 }
4949 if (AllOtherOpsLoopInvariant &&
4950 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4951 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004952 }
4953 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004954 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004955}
4956
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004957bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4958 // If we know that \c I can never be poison period, then that's enough.
4959 if (isSCEVExprNeverPoison(I))
4960 return true;
4961
4962 // For an add recurrence specifically, we assume that infinite loops without
4963 // side effects are undefined behavior, and then reason as follows:
4964 //
4965 // If the add recurrence is poison in any iteration, it is poison on all
4966 // future iterations (since incrementing poison yields poison). If the result
4967 // of the add recurrence is fed into the loop latch condition and the loop
4968 // does not contain any throws or exiting blocks other than the latch, we now
4969 // have the ability to "choose" whether the backedge is taken or not (by
4970 // choosing a sufficiently evil value for the poison feeding into the branch)
4971 // for every iteration including and after the one in which \p I first became
4972 // poison. There are two possibilities (let's call the iteration in which \p
4973 // I first became poison as K):
4974 //
4975 // 1. In the set of iterations including and after K, the loop body executes
4976 // no side effects. In this case executing the backege an infinte number
4977 // of times will yield undefined behavior.
4978 //
4979 // 2. In the set of iterations including and after K, the loop body executes
4980 // at least one side effect. In this case, that specific instance of side
4981 // effect is control dependent on poison, which also yields undefined
4982 // behavior.
4983
4984 auto *ExitingBB = L->getExitingBlock();
4985 auto *LatchBB = L->getLoopLatch();
4986 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4987 return false;
4988
4989 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004990 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004991
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004992 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4993 // things that are known to be fully poison under that assumption go on the
4994 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004995 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004996 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004997
4998 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004999 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005000 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005001
Sanjoy Dasa19edc42016-06-08 17:48:31 +00005002 for (auto *PoisonUser : Poison->users()) {
5003 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5004 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5005 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5006 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005007 assert(BI->isConditional() && "Only possibility!");
5008 if (BI->getParent() == LatchBB) {
5009 LatchControlDependentOnPoison = true;
5010 break;
5011 }
5012 }
5013 }
5014 }
5015
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005016 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5017}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005018
Sanjoy Das5603fc02016-09-26 02:44:07 +00005019ScalarEvolution::LoopProperties
5020ScalarEvolution::getLoopProperties(const Loop *L) {
5021 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005022
Sanjoy Das5603fc02016-09-26 02:44:07 +00005023 auto Itr = LoopPropertiesCache.find(L);
5024 if (Itr == LoopPropertiesCache.end()) {
5025 auto HasSideEffects = [](Instruction *I) {
5026 if (auto *SI = dyn_cast<StoreInst>(I))
5027 return !SI->isSimple();
5028
5029 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005030 };
5031
Sanjoy Das5603fc02016-09-26 02:44:07 +00005032 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5033 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005034
Sanjoy Das5603fc02016-09-26 02:44:07 +00005035 for (auto *BB : L->getBlocks())
5036 for (auto &I : *BB) {
5037 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5038 LP.HasNoAbnormalExits = false;
5039 if (HasSideEffects(&I))
5040 LP.HasNoSideEffects = false;
5041 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5042 break; // We're already as pessimistic as we can get.
5043 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005044
Sanjoy Das5603fc02016-09-26 02:44:07 +00005045 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005046 assert(InsertPair.second && "We just checked!");
5047 Itr = InsertPair.first;
5048 }
5049
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005050 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005051}
5052
Dan Gohmanaf752342009-07-07 17:06:11 +00005053const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005054 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005055 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005056
Dan Gohman69451a02010-03-09 23:46:50 +00005057 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005058 // Don't attempt to analyze instructions in blocks that aren't
5059 // reachable. Such instructions don't matter, and they aren't required
5060 // to obey basic rules for definitions dominating uses which this
5061 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005062 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005063 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005064 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005065 return getConstant(CI);
5066 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005067 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005068 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005069 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005070 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005071 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005072
Dan Gohman80ca01c2009-07-17 20:47:02 +00005073 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005074 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005075 switch (BO->Opcode) {
5076 case Instruction::Add: {
5077 // The simple thing to do would be to just call getSCEV on both operands
5078 // and call getAddExpr with the result. However if we're looking at a
5079 // bunch of things all added together, this can be quite inefficient,
5080 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5081 // Instead, gather up all the operands and make a single getAddExpr call.
5082 // LLVM IR canonical form means we need only traverse the left operands.
5083 SmallVector<const SCEV *, 4> AddOps;
5084 do {
5085 if (BO->Op) {
5086 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5087 AddOps.push_back(OpSCEV);
5088 break;
5089 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005090
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005091 // If a NUW or NSW flag can be applied to the SCEV for this
5092 // addition, then compute the SCEV for this addition by itself
5093 // with a separate call to getAddExpr. We need to do that
5094 // instead of pushing the operands of the addition onto AddOps,
5095 // since the flags are only known to apply to this particular
5096 // addition - they may not apply to other additions that can be
5097 // formed with operands from AddOps.
5098 const SCEV *RHS = getSCEV(BO->RHS);
5099 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5100 if (Flags != SCEV::FlagAnyWrap) {
5101 const SCEV *LHS = getSCEV(BO->LHS);
5102 if (BO->Opcode == Instruction::Sub)
5103 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5104 else
5105 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5106 break;
5107 }
Dan Gohman36bad002009-09-17 18:05:20 +00005108 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005109
5110 if (BO->Opcode == Instruction::Sub)
5111 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5112 else
5113 AddOps.push_back(getSCEV(BO->RHS));
5114
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005115 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005116 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5117 NewBO->Opcode != Instruction::Sub)) {
5118 AddOps.push_back(getSCEV(BO->LHS));
5119 break;
5120 }
5121 BO = NewBO;
5122 } while (true);
5123
5124 return getAddExpr(AddOps);
5125 }
5126
5127 case Instruction::Mul: {
5128 SmallVector<const SCEV *, 4> MulOps;
5129 do {
5130 if (BO->Op) {
5131 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5132 MulOps.push_back(OpSCEV);
5133 break;
5134 }
5135
5136 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5137 if (Flags != SCEV::FlagAnyWrap) {
5138 MulOps.push_back(
5139 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5140 break;
5141 }
5142 }
5143
5144 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005145 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005146 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5147 MulOps.push_back(getSCEV(BO->LHS));
5148 break;
5149 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005150 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005151 } while (true);
5152
5153 return getMulExpr(MulOps);
5154 }
5155 case Instruction::UDiv:
5156 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5157 case Instruction::Sub: {
5158 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5159 if (BO->Op)
5160 Flags = getNoWrapFlagsFromUB(BO->Op);
5161 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5162 }
5163 case Instruction::And:
5164 // For an expression like x&255 that merely masks off the high bits,
5165 // use zext(trunc(x)) as the SCEV expression.
5166 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5167 if (CI->isNullValue())
5168 return getSCEV(BO->RHS);
5169 if (CI->isAllOnesValue())
5170 return getSCEV(BO->LHS);
5171 const APInt &A = CI->getValue();
5172
5173 // Instcombine's ShrinkDemandedConstant may strip bits out of
5174 // constants, obscuring what would otherwise be a low-bits mask.
5175 // Use computeKnownBits to compute what ShrinkDemandedConstant
5176 // knew about to reconstruct a low-bits mask value.
5177 unsigned LZ = A.countLeadingZeros();
5178 unsigned TZ = A.countTrailingZeros();
5179 unsigned BitWidth = A.getBitWidth();
5180 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5181 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00005182 0, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005183
5184 APInt EffectiveMask =
5185 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5186 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5187 const SCEV *MulCount = getConstant(ConstantInt::get(
5188 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5189 return getMulExpr(
5190 getZeroExtendExpr(
5191 getTruncateExpr(
5192 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5193 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5194 BO->LHS->getType()),
5195 MulCount);
5196 }
Dan Gohman36bad002009-09-17 18:05:20 +00005197 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005198 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005199
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005200 case Instruction::Or:
5201 // If the RHS of the Or is a constant, we may have something like:
5202 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5203 // optimizations will transparently handle this case.
5204 //
5205 // In order for this transformation to be safe, the LHS must be of the
5206 // form X*(2^n) and the Or constant must be less than 2^n.
5207 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5208 const SCEV *LHS = getSCEV(BO->LHS);
5209 const APInt &CIVal = CI->getValue();
5210 if (GetMinTrailingZeros(LHS) >=
5211 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5212 // Build a plain add SCEV.
5213 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5214 // If the LHS of the add was an addrec and it has no-wrap flags,
5215 // transfer the no-wrap flags, since an or won't introduce a wrap.
5216 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5217 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5218 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5219 OldAR->getNoWrapFlags());
5220 }
5221 return S;
5222 }
5223 }
5224 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005225
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005226 case Instruction::Xor:
5227 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5228 // If the RHS of xor is -1, then this is a not operation.
5229 if (CI->isAllOnesValue())
5230 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005231
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005232 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5233 // This is a variant of the check for xor with -1, and it handles
5234 // the case where instcombine has trimmed non-demanded bits out
5235 // of an xor with -1.
5236 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5237 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5238 if (LBO->getOpcode() == Instruction::And &&
5239 LCI->getValue() == CI->getValue())
5240 if (const SCEVZeroExtendExpr *Z =
5241 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5242 Type *UTy = BO->LHS->getType();
5243 const SCEV *Z0 = Z->getOperand();
5244 Type *Z0Ty = Z0->getType();
5245 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005246
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005247 // If C is a low-bits mask, the zero extend is serving to
5248 // mask off the high bits. Complement the operand and
5249 // re-apply the zext.
5250 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5251 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5252
5253 // If C is a single bit, it may be in the sign-bit position
5254 // before the zero-extend. In this case, represent the xor
5255 // using an add, which is equivalent, and re-apply the zext.
5256 APInt Trunc = CI->getValue().trunc(Z0TySize);
5257 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5258 Trunc.isSignBit())
5259 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5260 UTy);
5261 }
5262 }
5263 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005264
5265 case Instruction::Shl:
5266 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005267 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5268 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005269
5270 // If the shift count is not less than the bitwidth, the result of
5271 // the shift is undefined. Don't try to analyze it, because the
5272 // resolution chosen here may differ from the resolution chosen in
5273 // other parts of the compiler.
5274 if (SA->getValue().uge(BitWidth))
5275 break;
5276
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005277 // It is currently not resolved how to interpret NSW for left
5278 // shift by BitWidth - 1, so we avoid applying flags in that
5279 // case. Remove this check (or this comment) once the situation
5280 // is resolved. See
5281 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5282 // and http://reviews.llvm.org/D8890 .
5283 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005284 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5285 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005286
Owen Andersonedb4a702009-07-24 23:12:02 +00005287 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005288 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005289 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005290 }
5291 break;
5292
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005293 case Instruction::AShr:
5294 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5295 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5296 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5297 if (L->getOpcode() == Instruction::Shl &&
5298 L->getOperand(1) == BO->RHS) {
5299 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005300
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005301 // If the shift count is not less than the bitwidth, the result of
5302 // the shift is undefined. Don't try to analyze it, because the
5303 // resolution chosen here may differ from the resolution chosen in
5304 // other parts of the compiler.
5305 if (CI->getValue().uge(BitWidth))
5306 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005307
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005308 uint64_t Amt = BitWidth - CI->getZExtValue();
5309 if (Amt == BitWidth)
5310 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5311 return getSignExtendExpr(
5312 getTruncateExpr(getSCEV(L->getOperand(0)),
5313 IntegerType::get(getContext(), Amt)),
5314 BO->LHS->getType());
5315 }
5316 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005317 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005318 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005319
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005320 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005321 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005322 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005323
5324 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005325 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005326
5327 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005328 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005329
5330 case Instruction::BitCast:
5331 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005332 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005333 return getSCEV(U->getOperand(0));
5334 break;
5335
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005336 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5337 // lead to pointer expressions which cannot safely be expanded to GEPs,
5338 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5339 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005340
Dan Gohmanee750d12009-05-08 20:26:55 +00005341 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005342 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005343
Dan Gohman05e89732008-06-22 19:56:46 +00005344 case Instruction::PHI:
5345 return createNodeForPHI(cast<PHINode>(U));
5346
5347 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005348 // U can also be a select constant expr, which let fall through. Since
5349 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5350 // constant expressions cannot have instructions as operands, we'd have
5351 // returned getUnknown for a select constant expressions anyway.
5352 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005353 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5354 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005355 break;
5356
5357 case Instruction::Call:
5358 case Instruction::Invoke:
5359 if (Value *RV = CallSite(U).getReturnedArgOperand())
5360 return getSCEV(RV);
5361 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005362 }
5363
Dan Gohmanc8e23622009-04-21 23:15:49 +00005364 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005365}
5366
5367
5368
5369//===----------------------------------------------------------------------===//
5370// Iteration Count Computation Code
5371//
5372
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005373static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5374 if (!ExitCount)
5375 return 0;
5376
5377 ConstantInt *ExitConst = ExitCount->getValue();
5378
5379 // Guard against huge trip counts.
5380 if (ExitConst->getValue().getActiveBits() > 32)
5381 return 0;
5382
5383 // In case of integer overflow, this returns 0, which is correct.
5384 return ((unsigned)ExitConst->getZExtValue()) + 1;
5385}
5386
Chandler Carruth6666c272014-10-11 00:12:11 +00005387unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5388 if (BasicBlock *ExitingBB = L->getExitingBlock())
5389 return getSmallConstantTripCount(L, ExitingBB);
5390
5391 // No trip count information for multiple exits.
5392 return 0;
5393}
5394
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005395unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5396 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005397 assert(ExitingBlock && "Must pass a non-null exiting block!");
5398 assert(L->isLoopExiting(ExitingBlock) &&
5399 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005400 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005401 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005402 return getConstantTripCount(ExitCount);
5403}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005404
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005405unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5406 const auto *MaxExitCount =
5407 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5408 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005409}
5410
Chandler Carruth6666c272014-10-11 00:12:11 +00005411unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5412 if (BasicBlock *ExitingBB = L->getExitingBlock())
5413 return getSmallConstantTripMultiple(L, ExitingBB);
5414
5415 // No trip multiple information for multiple exits.
5416 return 0;
5417}
5418
Sanjoy Dasf8570812016-05-29 00:38:22 +00005419/// Returns the largest constant divisor of the trip count of this loop as a
5420/// normal unsigned value, if possible. This means that the actual trip count is
5421/// always a multiple of the returned value (don't forget the trip count could
5422/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005423///
5424/// Returns 1 if the trip count is unknown or not guaranteed to be the
5425/// multiple of a constant (which is also the case if the trip count is simply
5426/// constant, use getSmallConstantTripCount for that case), Will also return 1
5427/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005428///
5429/// As explained in the comments for getSmallConstantTripCount, this assumes
5430/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005431unsigned
5432ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5433 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005434 assert(ExitingBlock && "Must pass a non-null exiting block!");
5435 assert(L->isLoopExiting(ExitingBlock) &&
5436 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005437 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005438 if (ExitCount == getCouldNotCompute())
5439 return 1;
5440
5441 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005442 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005443 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5444 // to factor simple cases.
5445 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5446 TCMul = Mul->getOperand(0);
5447
5448 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5449 if (!MulC)
5450 return 1;
5451
5452 ConstantInt *Result = MulC->getValue();
5453
Hal Finkel30bd9342012-10-24 19:46:44 +00005454 // Guard against huge trip counts (this requires checking
5455 // for zero to handle the case where the trip count == -1 and the
5456 // addition wraps).
5457 if (!Result || Result->getValue().getActiveBits() > 32 ||
5458 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005459 return 1;
5460
5461 return (unsigned)Result->getZExtValue();
5462}
5463
Sanjoy Dasf8570812016-05-29 00:38:22 +00005464/// Get the expression for the number of loop iterations for which this loop is
5465/// guaranteed not to exit via ExitingBlock. Otherwise return
5466/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005467const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5468 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005469}
5470
Silviu Baranga6f444df2016-04-08 14:29:09 +00005471const SCEV *
5472ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5473 SCEVUnionPredicate &Preds) {
5474 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5475}
5476
Dan Gohmanaf752342009-07-07 17:06:11 +00005477const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005478 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005479}
5480
Sanjoy Dasf8570812016-05-29 00:38:22 +00005481/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5482/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005483const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005484 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005485}
5486
John Brawn84b21832016-10-21 11:08:48 +00005487bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5488 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5489}
5490
Sanjoy Dasf8570812016-05-29 00:38:22 +00005491/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005492static void
5493PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5494 BasicBlock *Header = L->getHeader();
5495
5496 // Push all Loop-header PHIs onto the Worklist stack.
5497 for (BasicBlock::iterator I = Header->begin();
5498 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5499 Worklist.push_back(PN);
5500}
5501
Dan Gohman2b8da352009-04-30 20:47:05 +00005502const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005503ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5504 auto &BTI = getBackedgeTakenInfo(L);
5505 if (BTI.hasFullInfo())
5506 return BTI;
5507
5508 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5509
5510 if (!Pair.second)
5511 return Pair.first->second;
5512
5513 BackedgeTakenInfo Result =
5514 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5515
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005516 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005517}
5518
5519const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005520ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005521 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005522 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005523 // update the value. The temporary CouldNotCompute value tells SCEV
5524 // code elsewhere that it shouldn't attempt to request a new
5525 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005526 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005527 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005528 if (!Pair.second)
5529 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005530
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005531 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005532 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5533 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005534 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005535
5536 if (Result.getExact(this) != getCouldNotCompute()) {
5537 assert(isLoopInvariant(Result.getExact(this), L) &&
5538 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005539 "Computed backedge-taken count isn't loop invariant for loop!");
5540 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005541 }
5542 else if (Result.getMax(this) == getCouldNotCompute() &&
5543 isa<PHINode>(L->getHeader()->begin())) {
5544 // Only count loops that have phi nodes as not being computable.
5545 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005546 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005547
Chris Lattnera337f5e2011-01-09 02:16:18 +00005548 // Now that we know more about the trip count for this loop, forget any
5549 // existing SCEV values for PHI nodes in this loop since they are only
5550 // conservative estimates made without the benefit of trip count
5551 // information. This is similar to the code in forgetLoop, except that
5552 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005553 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005554 SmallVector<Instruction *, 16> Worklist;
5555 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005556
Chris Lattnera337f5e2011-01-09 02:16:18 +00005557 SmallPtrSet<Instruction *, 8> Visited;
5558 while (!Worklist.empty()) {
5559 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005560 if (!Visited.insert(I).second)
5561 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005562
Chris Lattnera337f5e2011-01-09 02:16:18 +00005563 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005564 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005565 if (It != ValueExprMap.end()) {
5566 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005567
Chris Lattnera337f5e2011-01-09 02:16:18 +00005568 // SCEVUnknown for a PHI either means that it has an unrecognized
5569 // structure, or it's a PHI that's in the progress of being computed
5570 // by createNodeForPHI. In the former case, additional loop trip
5571 // count information isn't going to change anything. In the later
5572 // case, createNodeForPHI will perform the necessary updates on its
5573 // own when it gets to that point.
5574 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005575 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005576 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005577 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005578 if (PHINode *PN = dyn_cast<PHINode>(I))
5579 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005580 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005581
5582 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005583 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005584 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005585
5586 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005587 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005588 // recusive call to getBackedgeTakenInfo (on a different
5589 // loop), which would invalidate the iterator computed
5590 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005591 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005592}
5593
Dan Gohman880c92a2009-10-31 15:04:55 +00005594void ScalarEvolution::forgetLoop(const Loop *L) {
5595 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005596 auto RemoveLoopFromBackedgeMap =
5597 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5598 auto BTCPos = Map.find(L);
5599 if (BTCPos != Map.end()) {
5600 BTCPos->second.clear();
5601 Map.erase(BTCPos);
5602 }
5603 };
5604
5605 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5606 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005607
Dan Gohman880c92a2009-10-31 15:04:55 +00005608 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005609 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005610 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005611
Dan Gohmandc191042009-07-08 19:23:34 +00005612 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005613 while (!Worklist.empty()) {
5614 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005615 if (!Visited.insert(I).second)
5616 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005617
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005618 ValueExprMapType::iterator It =
5619 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005620 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005621 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005622 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005623 if (PHINode *PN = dyn_cast<PHINode>(I))
5624 ConstantEvolutionLoopExitValue.erase(PN);
5625 }
5626
5627 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005628 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005629
5630 // Forget all contained loops too, to avoid dangling entries in the
5631 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005632 for (Loop *I : *L)
5633 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005634
Sanjoy Das5603fc02016-09-26 02:44:07 +00005635 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005636}
5637
Eric Christopheref6d5932010-07-29 01:25:38 +00005638void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005639 Instruction *I = dyn_cast<Instruction>(V);
5640 if (!I) return;
5641
5642 // Drop information about expressions based on loop-header PHIs.
5643 SmallVector<Instruction *, 16> Worklist;
5644 Worklist.push_back(I);
5645
5646 SmallPtrSet<Instruction *, 8> Visited;
5647 while (!Worklist.empty()) {
5648 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005649 if (!Visited.insert(I).second)
5650 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005651
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005652 ValueExprMapType::iterator It =
5653 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005654 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005655 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005656 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005657 if (PHINode *PN = dyn_cast<PHINode>(I))
5658 ConstantEvolutionLoopExitValue.erase(PN);
5659 }
5660
5661 PushDefUseChildren(I, Worklist);
5662 }
5663}
5664
Sanjoy Dasf8570812016-05-29 00:38:22 +00005665/// Get the exact loop backedge taken count considering all loop exits. A
5666/// computable result can only be returned for loops with a single exit.
5667/// Returning the minimum taken count among all exits is incorrect because one
5668/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5669/// the limit of each loop test is never skipped. This is a valid assumption as
5670/// long as the loop exits via that test. For precise results, it is the
5671/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005672/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005673const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005674ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5675 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005676 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005677 if (!isComplete() || ExitNotTaken.empty())
5678 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005679
Craig Topper9f008862014-04-15 04:59:12 +00005680 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005681 for (auto &ENT : ExitNotTaken) {
5682 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005683
5684 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005685 BECount = ENT.ExactNotTaken;
5686 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005687 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005688 if (Preds && !ENT.hasAlwaysTruePredicate())
5689 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005690
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005691 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005692 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005693 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005694
Andrew Trickbbb226a2011-09-02 21:20:46 +00005695 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005696 return BECount;
5697}
5698
Sanjoy Dasf8570812016-05-29 00:38:22 +00005699/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005700const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005701ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005702 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005703 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005704 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005705 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005706
Andrew Trick3ca3f982011-07-26 17:19:55 +00005707 return SE->getCouldNotCompute();
5708}
5709
5710/// getMax - Get the max backedge taken count for the loop.
5711const SCEV *
5712ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005713 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5714 return !ENT.hasAlwaysTruePredicate();
5715 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005716
Sanjoy Das73268612016-09-26 01:10:22 +00005717 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5718 return SE->getCouldNotCompute();
5719
5720 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005721}
5722
John Brawn84b21832016-10-21 11:08:48 +00005723bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5724 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5725 return !ENT.hasAlwaysTruePredicate();
5726 };
5727 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5728}
5729
Andrew Trick9093e152013-03-26 03:14:53 +00005730bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5731 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005732 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5733 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005734 return true;
5735
Silviu Baranga6f444df2016-04-08 14:29:09 +00005736 for (auto &ENT : ExitNotTaken)
5737 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5738 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005739 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005740
Andrew Trick9093e152013-03-26 03:14:53 +00005741 return false;
5742}
5743
Andrew Trick3ca3f982011-07-26 17:19:55 +00005744/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5745/// computable exit into a persistent ExitNotTakenInfo array.
5746ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005747 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5748 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005749 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5750 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005751 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005752 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005753 std::transform(
5754 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005755 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005756 BasicBlock *ExitBB = EEI.first;
5757 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005758 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005759 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005760
5761 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5762 for (auto *Pred : EL.Predicates)
5763 Predicate->add(Pred);
5764
5765 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005766 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005767}
5768
Sanjoy Dasf8570812016-05-29 00:38:22 +00005769/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005770void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005771 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005772}
5773
Sanjoy Dasf8570812016-05-29 00:38:22 +00005774/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005775ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005776ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5777 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005778 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005779 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005780
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005781 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5782
5783 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005784 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005785 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005786 const SCEV *MustExitMaxBECount = nullptr;
5787 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005788 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005789
5790 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5791 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005792 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005793 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005794 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005795 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5796
Sanjoy Dasf0022122016-09-28 17:14:58 +00005797 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005798 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005799
5800 // 1. For each exit that can be computed, add an entry to ExitCounts.
5801 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005802 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005803 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005804 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005805 CouldComputeBECount = false;
5806 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005807 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005808
Andrew Trick839e30b2014-05-23 19:47:13 +00005809 // 2. Derive the loop's MaxBECount from each exit's max number of
5810 // non-exiting iterations. Partition the loop exits into two kinds:
5811 // LoopMustExits and LoopMayExits.
5812 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005813 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5814 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005815 // MaxBECount is the minimum EL.MaxNotTaken of computable
5816 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5817 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5818 // computable EL.MaxNotTaken.
5819 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005820 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005821 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005822 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005823 MustExitMaxOrZero = EL.MaxOrZero;
5824 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005825 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005826 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005827 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005828 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005829 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5830 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005831 else {
5832 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005833 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005834 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005835 }
Dan Gohman96212b62009-06-22 00:31:57 +00005836 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005837 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5838 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00005839 // The loop backedge will be taken the maximum or zero times if there's
5840 // a single exit that must be taken the maximum or zero times.
5841 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005842 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00005843 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00005844}
5845
Andrew Trick3ca3f982011-07-26 17:19:55 +00005846ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005847ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5848 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005849
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005850 // Okay, we've chosen an exiting block. See what condition causes us to exit
5851 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005852 // lead to the loop header.
5853 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005854 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005855 for (auto *SBB : successors(ExitingBlock))
5856 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005857 if (Exit) // Multiple exit successors.
5858 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005859 Exit = SBB;
5860 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005861 MustExecuteLoopHeader = false;
5862 }
Dan Gohmance973df2009-06-24 04:48:43 +00005863
Chris Lattner18954852007-01-07 02:24:26 +00005864 // At this point, we know we have a conditional branch that determines whether
5865 // the loop is exited. However, we don't know if the branch is executed each
5866 // time through the loop. If not, then the execution count of the branch will
5867 // not be equal to the trip count of the loop.
5868 //
5869 // Currently we check for this by checking to see if the Exit branch goes to
5870 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005871 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005872 // loop header. This is common for un-rotated loops.
5873 //
5874 // If both of those tests fail, walk up the unique predecessor chain to the
5875 // header, stopping if there is an edge that doesn't exit the loop. If the
5876 // header is reached, the execution count of the branch will be equal to the
5877 // trip count of the loop.
5878 //
5879 // More extensive analysis could be done to handle more cases here.
5880 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005881 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005882 // The simple checks failed, try climbing the unique predecessor chain
5883 // up to the header.
5884 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005885 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005886 BasicBlock *Pred = BB->getUniquePredecessor();
5887 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005888 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005889 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005890 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005891 if (PredSucc == BB)
5892 continue;
5893 // If the predecessor has a successor that isn't BB and isn't
5894 // outside the loop, assume the worst.
5895 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005896 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005897 }
5898 if (Pred == L->getHeader()) {
5899 Ok = true;
5900 break;
5901 }
5902 BB = Pred;
5903 }
5904 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005905 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005906 }
5907
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005908 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005909 TerminatorInst *Term = ExitingBlock->getTerminator();
5910 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5911 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5912 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005913 return computeExitLimitFromCond(
5914 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5915 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005916 }
5917
5918 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005919 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005920 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005921
5922 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005923}
5924
Andrew Trick3ca3f982011-07-26 17:19:55 +00005925ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005926ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005927 Value *ExitCond,
5928 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005929 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005930 bool ControlsExit,
5931 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005932 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005933 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5934 if (BO->getOpcode() == Instruction::And) {
5935 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005936 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005937 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005938 ControlsExit && !EitherMayExit,
5939 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005940 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005941 ControlsExit && !EitherMayExit,
5942 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005943 const SCEV *BECount = getCouldNotCompute();
5944 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005945 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005946 // Both conditions must be true for the loop to continue executing.
5947 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005948 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5949 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005950 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005951 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005952 BECount =
5953 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5954 if (EL0.MaxNotTaken == getCouldNotCompute())
5955 MaxBECount = EL1.MaxNotTaken;
5956 else if (EL1.MaxNotTaken == getCouldNotCompute())
5957 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005958 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005959 MaxBECount =
5960 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005961 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005962 // Both conditions must be true at the same time for the loop to exit.
5963 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005964 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005965 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5966 MaxBECount = EL0.MaxNotTaken;
5967 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5968 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005969 }
5970
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005971 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5972 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005973 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
5974 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5975 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005976 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5977 !isa<SCEVCouldNotCompute>(BECount))
5978 MaxBECount = BECount;
5979
John Brawn84b21832016-10-21 11:08:48 +00005980 return ExitLimit(BECount, MaxBECount, false,
5981 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00005982 }
5983 if (BO->getOpcode() == Instruction::Or) {
5984 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005985 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005986 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005987 ControlsExit && !EitherMayExit,
5988 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005989 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005990 ControlsExit && !EitherMayExit,
5991 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005992 const SCEV *BECount = getCouldNotCompute();
5993 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005994 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005995 // Both conditions must be false for the loop to continue executing.
5996 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005997 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5998 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005999 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00006000 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006001 BECount =
6002 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6003 if (EL0.MaxNotTaken == getCouldNotCompute())
6004 MaxBECount = EL1.MaxNotTaken;
6005 else if (EL1.MaxNotTaken == getCouldNotCompute())
6006 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00006007 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006008 MaxBECount =
6009 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00006010 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00006011 // Both conditions must be false at the same time for the loop to exit.
6012 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00006013 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00006014 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6015 MaxBECount = EL0.MaxNotTaken;
6016 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6017 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00006018 }
6019
John Brawn84b21832016-10-21 11:08:48 +00006020 return ExitLimit(BECount, MaxBECount, false,
6021 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00006022 }
6023 }
6024
6025 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00006026 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00006027 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6028 ExitLimit EL =
6029 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6030 if (EL.hasFullInfo() || !AllowPredicates)
6031 return EL;
6032
6033 // Try again, but use SCEV predicates this time.
6034 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6035 /*AllowPredicates=*/true);
6036 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006037
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006038 // Check for a constant condition. These are normally stripped out by
6039 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6040 // preserve the CFG and is temporarily leaving constant conditions
6041 // in place.
6042 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6043 if (L->contains(FBB) == !CI->getZExtValue())
6044 // The backedge is always taken.
6045 return getCouldNotCompute();
6046 else
6047 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006048 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006049 }
6050
Eli Friedmanebf98b02009-05-09 12:32:42 +00006051 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006052 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006053}
6054
Andrew Trick3ca3f982011-07-26 17:19:55 +00006055ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006056ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006057 ICmpInst *ExitCond,
6058 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006059 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006060 bool ControlsExit,
6061 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006062
Reid Spencer266e42b2006-12-23 06:05:41 +00006063 // If the condition was exit on true, convert the condition to exit on false
6064 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006065 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006066 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006067 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006068 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006069
6070 // Handle common loops like: for (X = "string"; *X; ++X)
6071 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6072 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006073 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006074 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006075 if (ItCnt.hasAnyInfo())
6076 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006077 }
6078
Dan Gohmanaf752342009-07-07 17:06:11 +00006079 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6080 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006081
6082 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006083 LHS = getSCEVAtScope(LHS, L);
6084 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006085
Dan Gohmance973df2009-06-24 04:48:43 +00006086 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006087 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006088 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006089 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006090 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006091 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006092 }
6093
Dan Gohman81585c12010-05-03 16:35:17 +00006094 // Simplify the operands before analyzing them.
6095 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6096
Chris Lattnerd934c702004-04-02 20:23:17 +00006097 // If we have a comparison of a chrec against a constant, try to use value
6098 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006099 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6100 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006101 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006102 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006103 ConstantRange CompRange =
6104 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006105
Dan Gohmanaf752342009-07-07 17:06:11 +00006106 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006107 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006108 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006109
Chris Lattnerd934c702004-04-02 20:23:17 +00006110 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006111 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006112 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006113 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006114 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006115 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006116 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006117 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006118 case ICmpInst::ICMP_EQ: { // while (X == Y)
6119 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006120 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006121 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006122 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006123 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006124 case ICmpInst::ICMP_SLT:
6125 case ICmpInst::ICMP_ULT: { // while (X < Y)
6126 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006127 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006128 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006129 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006130 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006131 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006132 case ICmpInst::ICMP_SGT:
6133 case ICmpInst::ICMP_UGT: { // while (X > Y)
6134 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006135 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006136 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006137 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006138 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006139 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006140 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006141 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006142 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006143 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006144
6145 auto *ExhaustiveCount =
6146 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6147
6148 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6149 return ExhaustiveCount;
6150
6151 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6152 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006153}
6154
Benjamin Kramer5a188542014-02-11 15:44:32 +00006155ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006156ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006157 SwitchInst *Switch,
6158 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006159 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006160 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6161
6162 // Give up if the exit is the default dest of a switch.
6163 if (Switch->getDefaultDest() == ExitingBlock)
6164 return getCouldNotCompute();
6165
6166 assert(L->contains(Switch->getDefaultDest()) &&
6167 "Default case must not exit the loop!");
6168 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6169 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6170
6171 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006172 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006173 if (EL.hasAnyInfo())
6174 return EL;
6175
6176 return getCouldNotCompute();
6177}
6178
Chris Lattnerec901cc2004-10-12 01:49:27 +00006179static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006180EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6181 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006182 const SCEV *InVal = SE.getConstant(C);
6183 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006184 assert(isa<SCEVConstant>(Val) &&
6185 "Evaluation of SCEV at constant didn't fold correctly?");
6186 return cast<SCEVConstant>(Val)->getValue();
6187}
6188
Sanjoy Dasf8570812016-05-29 00:38:22 +00006189/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6190/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006191ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006192ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006193 LoadInst *LI,
6194 Constant *RHS,
6195 const Loop *L,
6196 ICmpInst::Predicate predicate) {
6197
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006198 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006199
6200 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006201 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006202 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006203 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006204
6205 // Make sure that it is really a constant global we are gepping, with an
6206 // initializer, and make sure the first IDX is really 0.
6207 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006208 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006209 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6210 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006211 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006212
6213 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006214 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006215 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006216 unsigned VarIdxNum = 0;
6217 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6218 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6219 Indexes.push_back(CI);
6220 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006221 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006222 VarIdx = GEP->getOperand(i);
6223 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006224 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006225 }
6226
Andrew Trick7004e4b2012-03-26 22:33:59 +00006227 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6228 if (!VarIdx)
6229 return getCouldNotCompute();
6230
Chris Lattnerec901cc2004-10-12 01:49:27 +00006231 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6232 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006233 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006234 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006235
6236 // We can only recognize very limited forms of loop index expressions, in
6237 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006238 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006239 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006240 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6241 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006242 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006243
6244 unsigned MaxSteps = MaxBruteForceIterations;
6245 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006246 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006247 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006248 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006249
6250 // Form the GEP offset.
6251 Indexes[VarIdxNum] = Val;
6252
Chris Lattnere166a852012-01-24 05:49:24 +00006253 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6254 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006255 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006256
6257 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006258 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006259 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006260 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006261 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006262 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006263 }
6264 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006265 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006266}
6267
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006268ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6269 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6270 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6271 if (!RHS)
6272 return getCouldNotCompute();
6273
6274 const BasicBlock *Latch = L->getLoopLatch();
6275 if (!Latch)
6276 return getCouldNotCompute();
6277
6278 const BasicBlock *Predecessor = L->getLoopPredecessor();
6279 if (!Predecessor)
6280 return getCouldNotCompute();
6281
6282 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6283 // Return LHS in OutLHS and shift_opt in OutOpCode.
6284 auto MatchPositiveShift =
6285 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6286
6287 using namespace PatternMatch;
6288
6289 ConstantInt *ShiftAmt;
6290 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6291 OutOpCode = Instruction::LShr;
6292 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6293 OutOpCode = Instruction::AShr;
6294 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6295 OutOpCode = Instruction::Shl;
6296 else
6297 return false;
6298
6299 return ShiftAmt->getValue().isStrictlyPositive();
6300 };
6301
6302 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6303 //
6304 // loop:
6305 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6306 // %iv.shifted = lshr i32 %iv, <positive constant>
6307 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006308 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006309 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6310 auto MatchShiftRecurrence =
6311 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6312 Optional<Instruction::BinaryOps> PostShiftOpCode;
6313
6314 {
6315 Instruction::BinaryOps OpC;
6316 Value *V;
6317
6318 // If we encounter a shift instruction, "peel off" the shift operation,
6319 // and remember that we did so. Later when we inspect %iv's backedge
6320 // value, we will make sure that the backedge value uses the same
6321 // operation.
6322 //
6323 // Note: the peeled shift operation does not have to be the same
6324 // instruction as the one feeding into the PHI's backedge value. We only
6325 // really care about it being the same *kind* of shift instruction --
6326 // that's all that is required for our later inferences to hold.
6327 if (MatchPositiveShift(LHS, V, OpC)) {
6328 PostShiftOpCode = OpC;
6329 LHS = V;
6330 }
6331 }
6332
6333 PNOut = dyn_cast<PHINode>(LHS);
6334 if (!PNOut || PNOut->getParent() != L->getHeader())
6335 return false;
6336
6337 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6338 Value *OpLHS;
6339
6340 return
6341 // The backedge value for the PHI node must be a shift by a positive
6342 // amount
6343 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6344
6345 // of the PHI node itself
6346 OpLHS == PNOut &&
6347
6348 // and the kind of shift should be match the kind of shift we peeled
6349 // off, if any.
6350 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6351 };
6352
6353 PHINode *PN;
6354 Instruction::BinaryOps OpCode;
6355 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6356 return getCouldNotCompute();
6357
6358 const DataLayout &DL = getDataLayout();
6359
6360 // The key rationale for this optimization is that for some kinds of shift
6361 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6362 // within a finite number of iterations. If the condition guarding the
6363 // backedge (in the sense that the backedge is taken if the condition is true)
6364 // is false for the value the shift recurrence stabilizes to, then we know
6365 // that the backedge is taken only a finite number of times.
6366
6367 ConstantInt *StableValue = nullptr;
6368 switch (OpCode) {
6369 default:
6370 llvm_unreachable("Impossible case!");
6371
6372 case Instruction::AShr: {
6373 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6374 // bitwidth(K) iterations.
6375 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6376 bool KnownZero, KnownOne;
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00006377 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006378 Predecessor->getTerminator(), &DT);
6379 auto *Ty = cast<IntegerType>(RHS->getType());
6380 if (KnownZero)
6381 StableValue = ConstantInt::get(Ty, 0);
6382 else if (KnownOne)
6383 StableValue = ConstantInt::get(Ty, -1, true);
6384 else
6385 return getCouldNotCompute();
6386
6387 break;
6388 }
6389 case Instruction::LShr:
6390 case Instruction::Shl:
6391 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6392 // stabilize to 0 in at most bitwidth(K) iterations.
6393 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6394 break;
6395 }
6396
6397 auto *Result =
6398 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6399 assert(Result->getType()->isIntegerTy(1) &&
6400 "Otherwise cannot be an operand to a branch instruction");
6401
6402 if (Result->isZeroValue()) {
6403 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6404 const SCEV *UpperBound =
6405 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006406 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006407 }
6408
6409 return getCouldNotCompute();
6410}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006411
Sanjoy Dasf8570812016-05-29 00:38:22 +00006412/// Return true if we can constant fold an instruction of the specified type,
6413/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006414static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006415 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006416 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6417 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006418 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006419
Chris Lattnerdd730472004-04-17 22:58:41 +00006420 if (const CallInst *CI = dyn_cast<CallInst>(I))
6421 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006422 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006423 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006424}
6425
Andrew Trick3a86ba72011-10-05 03:25:31 +00006426/// Determine whether this instruction can constant evolve within this loop
6427/// assuming its operands can all constant evolve.
6428static bool canConstantEvolve(Instruction *I, const Loop *L) {
6429 // An instruction outside of the loop can't be derived from a loop PHI.
6430 if (!L->contains(I)) return false;
6431
6432 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006433 // We don't currently keep track of the control flow needed to evaluate
6434 // PHIs, so we cannot handle PHIs inside of loops.
6435 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006436 }
6437
6438 // If we won't be able to constant fold this expression even if the operands
6439 // are constants, bail early.
6440 return CanConstantFold(I);
6441}
6442
6443/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6444/// recursing through each instruction operand until reaching a loop header phi.
6445static PHINode *
6446getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006447 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006448
6449 // Otherwise, we can evaluate this instruction if all of its operands are
6450 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006451 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006452 for (Value *Op : UseInst->operands()) {
6453 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006454
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006455 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006456 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006457
6458 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006459 if (!P)
6460 // If this operand is already visited, reuse the prior result.
6461 // We may have P != PHI if this is the deepest point at which the
6462 // inconsistent paths meet.
6463 P = PHIMap.lookup(OpInst);
6464 if (!P) {
6465 // Recurse and memoize the results, whether a phi is found or not.
6466 // This recursive call invalidates pointers into PHIMap.
6467 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6468 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006469 }
Craig Topper9f008862014-04-15 04:59:12 +00006470 if (!P)
6471 return nullptr; // Not evolving from PHI
6472 if (PHI && PHI != P)
6473 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006474 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006475 }
6476 // This is a expression evolving from a constant PHI!
6477 return PHI;
6478}
6479
Chris Lattnerdd730472004-04-17 22:58:41 +00006480/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6481/// in the loop that V is derived from. We allow arbitrary operations along the
6482/// way, but the operands of an operation must either be constants or a value
6483/// derived from a constant PHI. If this expression does not fit with these
6484/// constraints, return null.
6485static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006486 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006487 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006488
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006489 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006490 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006491
Andrew Trick3a86ba72011-10-05 03:25:31 +00006492 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006493 DenseMap<Instruction *, PHINode *> PHIMap;
6494 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006495}
6496
6497/// EvaluateExpression - Given an expression that passes the
6498/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6499/// in the loop has the value PHIVal. If we can't fold this expression for some
6500/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006501static Constant *EvaluateExpression(Value *V, const Loop *L,
6502 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006503 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006504 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006505 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006506 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006507 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006508 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006509
Andrew Trick3a86ba72011-10-05 03:25:31 +00006510 if (Constant *C = Vals.lookup(I)) return C;
6511
Nick Lewyckya6674c72011-10-22 19:58:20 +00006512 // An instruction inside the loop depends on a value outside the loop that we
6513 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006514 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006515
6516 // An unmapped PHI can be due to a branch or another loop inside this loop,
6517 // or due to this not being the initial iteration through a loop where we
6518 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006519 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006520
Dan Gohmanf820bd32010-06-22 13:15:46 +00006521 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006522
6523 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006524 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6525 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006526 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006527 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006528 continue;
6529 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006530 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006531 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006532 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006533 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006534 }
6535
Nick Lewyckya6674c72011-10-22 19:58:20 +00006536 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006537 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006538 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006539 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6540 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006541 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006542 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006543 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006544}
6545
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006546
6547// If every incoming value to PN except the one for BB is a specific Constant,
6548// return that, else return nullptr.
6549static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6550 Constant *IncomingVal = nullptr;
6551
6552 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6553 if (PN->getIncomingBlock(i) == BB)
6554 continue;
6555
6556 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6557 if (!CurrentVal)
6558 return nullptr;
6559
6560 if (IncomingVal != CurrentVal) {
6561 if (IncomingVal)
6562 return nullptr;
6563 IncomingVal = CurrentVal;
6564 }
6565 }
6566
6567 return IncomingVal;
6568}
6569
Chris Lattnerdd730472004-04-17 22:58:41 +00006570/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6571/// in the header of its containing loop, we know the loop executes a
6572/// constant number of times, and the PHI node is just a recurrence
6573/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006574Constant *
6575ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006576 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006577 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006578 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006579 if (I != ConstantEvolutionLoopExitValue.end())
6580 return I->second;
6581
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006582 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006583 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006584
6585 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6586
Andrew Trick3a86ba72011-10-05 03:25:31 +00006587 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006588 BasicBlock *Header = L->getHeader();
6589 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006590
Sanjoy Dasdd709962015-10-08 18:28:36 +00006591 BasicBlock *Latch = L->getLoopLatch();
6592 if (!Latch)
6593 return nullptr;
6594
Sanjoy Das4493b402015-10-07 17:38:25 +00006595 for (auto &I : *Header) {
6596 PHINode *PHI = dyn_cast<PHINode>(&I);
6597 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006598 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006599 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006600 CurrentIterVals[PHI] = StartCST;
6601 }
6602 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006603 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006604
Sanjoy Dasdd709962015-10-08 18:28:36 +00006605 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006606
6607 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006608 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006609 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006610
Dan Gohman0bddac12009-02-24 18:55:53 +00006611 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006612 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006613 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006614 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006615 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006616 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006617
Nick Lewyckya6674c72011-10-22 19:58:20 +00006618 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006619 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006620 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006621 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006622 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006623 if (!NextPHI)
6624 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006625 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006626
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006627 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6628
Nick Lewyckya6674c72011-10-22 19:58:20 +00006629 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6630 // cease to be able to evaluate one of them or if they stop evolving,
6631 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006632 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006633 for (const auto &I : CurrentIterVals) {
6634 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006635 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006636 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006637 }
6638 // We use two distinct loops because EvaluateExpression may invalidate any
6639 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006640 for (const auto &I : PHIsToCompute) {
6641 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006642 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006643 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006644 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006645 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006646 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006647 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006648 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006649 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006650
6651 // If all entries in CurrentIterVals == NextIterVals then we can stop
6652 // iterating, the loop can't continue to change.
6653 if (StoppedEvolving)
6654 return RetVal = CurrentIterVals[PN];
6655
Andrew Trick3a86ba72011-10-05 03:25:31 +00006656 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006657 }
6658}
6659
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006660const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006661 Value *Cond,
6662 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006663 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006664 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006665
Dan Gohman866971e2010-06-19 14:17:24 +00006666 // If the loop is canonicalized, the PHI will have exactly two entries.
6667 // That's the only form we support here.
6668 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6669
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006670 DenseMap<Instruction *, Constant *> CurrentIterVals;
6671 BasicBlock *Header = L->getHeader();
6672 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6673
Sanjoy Dasdd709962015-10-08 18:28:36 +00006674 BasicBlock *Latch = L->getLoopLatch();
6675 assert(Latch && "Should follow from NumIncomingValues == 2!");
6676
Sanjoy Das4493b402015-10-07 17:38:25 +00006677 for (auto &I : *Header) {
6678 PHINode *PHI = dyn_cast<PHINode>(&I);
6679 if (!PHI)
6680 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006681 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006682 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006683 CurrentIterVals[PHI] = StartCST;
6684 }
6685 if (!CurrentIterVals.count(PN))
6686 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006687
6688 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6689 // the loop symbolically to determine when the condition gets a value of
6690 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006691 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006692 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006693 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006694 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006695 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006696
Zhou Sheng75b871f2007-01-11 12:24:14 +00006697 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006698 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006699
Reid Spencer983e3b32007-03-01 07:25:48 +00006700 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006701 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006702 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006703 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006704
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006705 // Update all the PHI nodes for the next iteration.
6706 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006707
6708 // Create a list of which PHIs we need to compute. We want to do this before
6709 // calling EvaluateExpression on them because that may invalidate iterators
6710 // into CurrentIterVals.
6711 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006712 for (const auto &I : CurrentIterVals) {
6713 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006714 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006715 PHIsToCompute.push_back(PHI);
6716 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006717 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006718 Constant *&NextPHI = NextIterVals[PHI];
6719 if (NextPHI) continue; // Already computed!
6720
Sanjoy Dasdd709962015-10-08 18:28:36 +00006721 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006722 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006723 }
6724 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006725 }
6726
6727 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006728 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006729}
6730
Dan Gohmanaf752342009-07-07 17:06:11 +00006731const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006732 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6733 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006734 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006735 for (auto &LS : Values)
6736 if (LS.first == L)
6737 return LS.second ? LS.second : V;
6738
6739 Values.emplace_back(L, nullptr);
6740
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006741 // Otherwise compute it.
6742 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006743 for (auto &LS : reverse(ValuesAtScopes[V]))
6744 if (LS.first == L) {
6745 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006746 break;
6747 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006748 return C;
6749}
6750
Nick Lewyckya6674c72011-10-22 19:58:20 +00006751/// This builds up a Constant using the ConstantExpr interface. That way, we
6752/// will return Constants for objects which aren't represented by a
6753/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6754/// Returns NULL if the SCEV isn't representable as a Constant.
6755static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006756 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006757 case scCouldNotCompute:
6758 case scAddRecExpr:
6759 break;
6760 case scConstant:
6761 return cast<SCEVConstant>(V)->getValue();
6762 case scUnknown:
6763 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6764 case scSignExtend: {
6765 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6766 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6767 return ConstantExpr::getSExt(CastOp, SS->getType());
6768 break;
6769 }
6770 case scZeroExtend: {
6771 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6772 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6773 return ConstantExpr::getZExt(CastOp, SZ->getType());
6774 break;
6775 }
6776 case scTruncate: {
6777 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6778 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6779 return ConstantExpr::getTrunc(CastOp, ST->getType());
6780 break;
6781 }
6782 case scAddExpr: {
6783 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6784 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006785 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6786 unsigned AS = PTy->getAddressSpace();
6787 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6788 C = ConstantExpr::getBitCast(C, DestPtrTy);
6789 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006790 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6791 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006792 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006793
6794 // First pointer!
6795 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006796 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006797 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006798 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006799 // The offsets have been converted to bytes. We can add bytes to an
6800 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006801 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006802 }
6803
6804 // Don't bother trying to sum two pointers. We probably can't
6805 // statically compute a load that results from it anyway.
6806 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006807 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006808
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006809 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6810 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006811 C2 = ConstantExpr::getIntegerCast(
6812 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006813 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006814 } else
6815 C = ConstantExpr::getAdd(C, C2);
6816 }
6817 return C;
6818 }
6819 break;
6820 }
6821 case scMulExpr: {
6822 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6823 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6824 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006825 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006826 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6827 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006828 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006829 C = ConstantExpr::getMul(C, C2);
6830 }
6831 return C;
6832 }
6833 break;
6834 }
6835 case scUDivExpr: {
6836 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6837 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6838 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6839 if (LHS->getType() == RHS->getType())
6840 return ConstantExpr::getUDiv(LHS, RHS);
6841 break;
6842 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006843 case scSMaxExpr:
6844 case scUMaxExpr:
6845 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006846 }
Craig Topper9f008862014-04-15 04:59:12 +00006847 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006848}
6849
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006850const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006851 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006852
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006853 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006854 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006855 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006856 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006857 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006858 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6859 if (PHINode *PN = dyn_cast<PHINode>(I))
6860 if (PN->getParent() == LI->getHeader()) {
6861 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006862 // to see if the loop that contains it has a known backedge-taken
6863 // count. If so, we may be able to force computation of the exit
6864 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006865 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006866 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006867 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006868 // Okay, we know how many times the containing loop executes. If
6869 // this is a constant evolving PHI node, get the final value at
6870 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006871 Constant *RV =
6872 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006873 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006874 }
6875 }
6876
Reid Spencere6328ca2006-12-04 21:33:23 +00006877 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006878 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006879 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006880 // result. This is particularly useful for computing loop exit values.
6881 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006882 SmallVector<Constant *, 4> Operands;
6883 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006884 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006885 if (Constant *C = dyn_cast<Constant>(Op)) {
6886 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006887 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006888 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006889
6890 // If any of the operands is non-constant and if they are
6891 // non-integer and non-pointer, don't even try to analyze them
6892 // with scev techniques.
6893 if (!isSCEVable(Op->getType()))
6894 return V;
6895
6896 const SCEV *OrigV = getSCEV(Op);
6897 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6898 MadeImprovement |= OrigV != OpV;
6899
Nick Lewyckya6674c72011-10-22 19:58:20 +00006900 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006901 if (!C) return V;
6902 if (C->getType() != Op->getType())
6903 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6904 Op->getType(),
6905 false),
6906 C, Op->getType());
6907 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006908 }
Dan Gohmance973df2009-06-24 04:48:43 +00006909
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006910 // Check to see if getSCEVAtScope actually made an improvement.
6911 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006912 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006913 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006914 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006915 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006916 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006917 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6918 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006919 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006920 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006921 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006922 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006923 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006924 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006925 }
6926 }
6927
6928 // This is some other type of SCEVUnknown, just return it.
6929 return V;
6930 }
6931
Dan Gohmana30370b2009-05-04 22:02:23 +00006932 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006933 // Avoid performing the look-up in the common case where the specified
6934 // expression has no loop-variant portions.
6935 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006936 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006937 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006938 // Okay, at least one of these operands is loop variant but might be
6939 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006940 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6941 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006942 NewOps.push_back(OpAtScope);
6943
6944 for (++i; i != e; ++i) {
6945 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006946 NewOps.push_back(OpAtScope);
6947 }
6948 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006949 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006950 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006951 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006952 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006953 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006954 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006955 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006956 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006957 }
6958 }
6959 // If we got here, all operands are loop invariant.
6960 return Comm;
6961 }
6962
Dan Gohmana30370b2009-05-04 22:02:23 +00006963 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006964 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6965 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006966 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6967 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006968 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006969 }
6970
6971 // If this is a loop recurrence for a loop that does not contain L, then we
6972 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006973 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006974 // First, attempt to evaluate each operand.
6975 // Avoid performing the look-up in the common case where the specified
6976 // expression has no loop-variant portions.
6977 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6978 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6979 if (OpAtScope == AddRec->getOperand(i))
6980 continue;
6981
6982 // Okay, at least one of these operands is loop variant but might be
6983 // foldable. Build a new instance of the folded commutative expression.
6984 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6985 AddRec->op_begin()+i);
6986 NewOps.push_back(OpAtScope);
6987 for (++i; i != e; ++i)
6988 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6989
Andrew Trick759ba082011-04-27 01:21:25 +00006990 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006991 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006992 AddRec->getNoWrapFlags(SCEV::FlagNW));
6993 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006994 // The addrec may be folded to a nonrecurrence, for example, if the
6995 // induction variable is multiplied by zero after constant folding. Go
6996 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006997 if (!AddRec)
6998 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006999 break;
7000 }
7001
7002 // If the scope is outside the addrec's loop, evaluate it by using the
7003 // loop exit value of the addrec.
7004 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007005 // To evaluate this recurrence, we need to know how many times the AddRec
7006 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00007007 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007008 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00007009
Eli Friedman61f67622008-08-04 23:49:06 +00007010 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00007011 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007012 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00007013
Dan Gohman8ca08852009-05-24 23:25:42 +00007014 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00007015 }
7016
Dan Gohmana30370b2009-05-04 22:02:23 +00007017 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007018 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007019 if (Op == Cast->getOperand())
7020 return Cast; // must be loop invariant
7021 return getZeroExtendExpr(Op, Cast->getType());
7022 }
7023
Dan Gohmana30370b2009-05-04 22:02:23 +00007024 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007025 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007026 if (Op == Cast->getOperand())
7027 return Cast; // must be loop invariant
7028 return getSignExtendExpr(Op, Cast->getType());
7029 }
7030
Dan Gohmana30370b2009-05-04 22:02:23 +00007031 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007032 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007033 if (Op == Cast->getOperand())
7034 return Cast; // must be loop invariant
7035 return getTruncateExpr(Op, Cast->getType());
7036 }
7037
Torok Edwinfbcc6632009-07-14 16:55:14 +00007038 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007039}
7040
Dan Gohmanaf752342009-07-07 17:06:11 +00007041const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007042 return getSCEVAtScope(getSCEV(V), L);
7043}
7044
Sanjoy Dasf8570812016-05-29 00:38:22 +00007045/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007046///
7047/// A * X = B (mod N)
7048///
7049/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7050/// A and B isn't important.
7051///
7052/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007053static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007054 ScalarEvolution &SE) {
7055 uint32_t BW = A.getBitWidth();
7056 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
7057 assert(A != 0 && "A must be non-zero.");
7058
7059 // 1. D = gcd(A, N)
7060 //
7061 // The gcd of A and N may have only one prime factor: 2. The number of
7062 // trailing zeros in A is its multiplicity
7063 uint32_t Mult2 = A.countTrailingZeros();
7064 // D = 2^Mult2
7065
7066 // 2. Check if B is divisible by D.
7067 //
7068 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7069 // is not less than multiplicity of this prime factor for D.
7070 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007071 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007072
7073 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7074 // modulo (N / D).
7075 //
7076 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
7077 // bit width during computations.
7078 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7079 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007080 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007081 APInt I = AD.multiplicativeInverse(Mod);
7082
7083 // 4. Compute the minimum unsigned root of the equation:
7084 // I * (B / D) mod (N / D)
7085 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7086
7087 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7088 // bits.
7089 return SE.getConstant(Result.trunc(BW));
7090}
Chris Lattnerd934c702004-04-02 20:23:17 +00007091
Sanjoy Dasf8570812016-05-29 00:38:22 +00007092/// Find the roots of the quadratic equation for the given quadratic chrec
7093/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7094/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007095///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007096static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007097SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007098 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007099 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7100 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7101 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007102
Chris Lattnerd934c702004-04-02 20:23:17 +00007103 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007104 if (!LC || !MC || !NC)
7105 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007106
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007107 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7108 const APInt &L = LC->getAPInt();
7109 const APInt &M = MC->getAPInt();
7110 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007111 APInt Two(BitWidth, 2);
7112 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007113
Dan Gohmance973df2009-06-24 04:48:43 +00007114 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007115 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007116 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007117 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7118 // The B coefficient is M-N/2
7119 APInt B(M);
7120 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007121
Reid Spencer983e3b32007-03-01 07:25:48 +00007122 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007123 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007124
Reid Spencer983e3b32007-03-01 07:25:48 +00007125 // Compute the B^2-4ac term.
7126 APInt SqrtTerm(B);
7127 SqrtTerm *= B;
7128 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007129
Nick Lewyckyfb780832012-08-01 09:14:36 +00007130 if (SqrtTerm.isNegative()) {
7131 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007132 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007133 }
7134
Reid Spencer983e3b32007-03-01 07:25:48 +00007135 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7136 // integer value or else APInt::sqrt() will assert.
7137 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007138
Dan Gohmance973df2009-06-24 04:48:43 +00007139 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007140 // The divisions must be performed as signed divisions.
7141 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007142 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007143 if (TwoA.isMinValue())
7144 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007145
Owen Anderson47db9412009-07-22 00:24:57 +00007146 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007147
7148 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007149 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007150 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007151 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007152
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007153 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7154 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007155 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007156}
7157
Andrew Trick3ca3f982011-07-26 17:19:55 +00007158ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007159ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007160 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007161
7162 // This is only used for loops with a "x != y" exit test. The exit condition
7163 // is now expressed as a single expression, V = x-y. So the exit test is
7164 // effectively V != 0. We know and take advantage of the fact that this
7165 // expression only being used in a comparison by zero context.
7166
Sanjoy Dasf0022122016-09-28 17:14:58 +00007167 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007168 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007169 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007170 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007171 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007172 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007173 }
7174
Dan Gohman48f82222009-05-04 22:30:44 +00007175 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007176 if (!AddRec && AllowPredicates)
7177 // Try to make this an AddRec using runtime tests, in the first X
7178 // iterations of this loop, where X is the SCEV expression found by the
7179 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007180 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007181
Chris Lattnerd934c702004-04-02 20:23:17 +00007182 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007183 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007184
Chris Lattnerdff679f2011-01-09 22:39:48 +00007185 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7186 // the quadratic equation to solve it.
7187 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007188 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7189 const SCEVConstant *R1 = Roots->first;
7190 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007191 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007192 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7193 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007194 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007195 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007196
Chris Lattnerd934c702004-04-02 20:23:17 +00007197 // We can only use this value if the chrec ends up with an exact zero
7198 // value at this index. When solving for "X*X != 5", for example, we
7199 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007200 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007201 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007202 // We found a quadratic root!
7203 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007204 }
7205 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007206 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007207 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007208
Chris Lattnerdff679f2011-01-09 22:39:48 +00007209 // Otherwise we can only handle this if it is affine.
7210 if (!AddRec->isAffine())
7211 return getCouldNotCompute();
7212
7213 // If this is an affine expression, the execution count of this branch is
7214 // the minimum unsigned root of the following equation:
7215 //
7216 // Start + Step*N = 0 (mod 2^BW)
7217 //
7218 // equivalent to:
7219 //
7220 // Step*N = -Start (mod 2^BW)
7221 //
7222 // where BW is the common bit width of Start and Step.
7223
7224 // Get the initial value for the loop.
7225 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7226 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7227
7228 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007229 //
7230 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7231 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7232 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7233 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007234 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007235 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007236 return getCouldNotCompute();
7237
Andrew Trick8b55b732011-03-14 16:50:06 +00007238 // For positive steps (counting up until unsigned overflow):
7239 // N = -Start/Step (as unsigned)
7240 // For negative steps (counting down to zero):
7241 // N = Start/-Step
7242 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007243 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007244 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007245
7246 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007247 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7248 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007249 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7250 ConstantRange CR = getUnsignedRange(Start);
7251 const SCEV *MaxBECount;
7252 if (!CountDown && CR.getUnsignedMin().isMinValue())
7253 // When counting up, the worst starting value is 1, not 0.
7254 MaxBECount = CR.getUnsignedMax().isMinValue()
7255 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7256 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7257 else
7258 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7259 : -CR.getUnsignedMin());
John Brawn84b21832016-10-21 11:08:48 +00007260 return ExitLimit(Distance, MaxBECount, false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007261 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007262
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007263 // As a special case, handle the instance where Step is a positive power of
7264 // two. In this case, determining whether Step divides Distance evenly can be
7265 // done by counting and comparing the number of trailing zeros of Step and
7266 // Distance.
7267 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007268 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007269 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7270 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7271 // case is not handled as this code is guarded by !CountDown.
7272 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007273 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7274 // Here we've constrained the equation to be of the form
7275 //
7276 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7277 //
7278 // where we're operating on a W bit wide integer domain and k is
7279 // non-negative. The smallest unsigned solution for X is the trip count.
7280 //
7281 // (0) is equivalent to:
7282 //
7283 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7284 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7285 // <=> 2^k * Distance' - X = L * 2^(W - N)
7286 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7287 //
7288 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7289 // by 2^(W - N).
7290 //
7291 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7292 //
7293 // E.g. say we're solving
7294 //
7295 // 2 * Val = 2 * X (in i8) ... (3)
7296 //
7297 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7298 //
7299 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7300 // necessarily the smallest unsigned value of X that satisfies (3).
7301 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7302 // is i8 1, not i8 -127
7303
7304 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7305
7306 // Since SCEV does not have a URem node, we construct one using a truncate
7307 // and a zero extend.
7308
7309 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7310 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7311 auto *WideTy = Distance->getType();
7312
Silviu Baranga6f444df2016-04-08 14:29:09 +00007313 const SCEV *Limit =
7314 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
John Brawn84b21832016-10-21 11:08:48 +00007315 return ExitLimit(Limit, Limit, false, Predicates);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007316 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007317 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007318
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007319 // If the condition controls loop exit (the loop exits only if the expression
7320 // is true) and the addition is no-wrap we can use unsigned divide to
7321 // compute the backedge count. In this case, the step may not divide the
7322 // distance, but we don't care because if the condition is "missed" the loop
7323 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007324 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7325 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007326 const SCEV *Exact =
7327 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007328 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007329 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007330
Chris Lattnerdff679f2011-01-09 22:39:48 +00007331 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007332 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7333 const SCEV *E = SolveLinEquationWithOverflow(
7334 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
John Brawn84b21832016-10-21 11:08:48 +00007335 return ExitLimit(E, E, false, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007336 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007337 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007338}
7339
Andrew Trick3ca3f982011-07-26 17:19:55 +00007340ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007341ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007342 // Loops that look like: while (X == 0) are very strange indeed. We don't
7343 // handle them yet except for the trivial case. This could be expanded in the
7344 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007345
Chris Lattnerd934c702004-04-02 20:23:17 +00007346 // If the value is a constant, check to see if it is known to be non-zero
7347 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007348 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007349 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007350 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007351 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007352 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007353
Chris Lattnerd934c702004-04-02 20:23:17 +00007354 // We could implement others, but I really doubt anyone writes loops like
7355 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007356 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007357}
7358
Dan Gohman4e3c1132010-04-15 16:19:08 +00007359std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007360ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007361 // If the block has a unique predecessor, then there is no path from the
7362 // predecessor to the block that does not go through the direct edge
7363 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007364 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007365 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007366
7367 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007368 // If the header has a unique predecessor outside the loop, it must be
7369 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007370 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007371 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007372
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007373 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007374}
7375
Sanjoy Dasf8570812016-05-29 00:38:22 +00007376/// SCEV structural equivalence is usually sufficient for testing whether two
7377/// expressions are equal, however for the purposes of looking for a condition
7378/// guarding a loop, it can be useful to be a little more general, since a
7379/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007380///
Dan Gohmanaf752342009-07-07 17:06:11 +00007381static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007382 // Quick check to see if they are the same SCEV.
7383 if (A == B) return true;
7384
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007385 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7386 // Not all instructions that are "identical" compute the same value. For
7387 // instance, two distinct alloca instructions allocating the same type are
7388 // identical and do not read memory; but compute distinct values.
7389 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7390 };
7391
Dan Gohman450f4e02009-06-20 00:35:32 +00007392 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7393 // two different instructions with the same value. Check for this case.
7394 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7395 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7396 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7397 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007398 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007399 return true;
7400
7401 // Otherwise assume they may have a different value.
7402 return false;
7403}
7404
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007405bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007406 const SCEV *&LHS, const SCEV *&RHS,
7407 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007408 bool Changed = false;
7409
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007410 // If we hit the max recursion limit bail out.
7411 if (Depth >= 3)
7412 return false;
7413
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007414 // Canonicalize a constant to the right side.
7415 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7416 // Check for both operands constant.
7417 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7418 if (ConstantExpr::getICmp(Pred,
7419 LHSC->getValue(),
7420 RHSC->getValue())->isNullValue())
7421 goto trivially_false;
7422 else
7423 goto trivially_true;
7424 }
7425 // Otherwise swap the operands to put the constant on the right.
7426 std::swap(LHS, RHS);
7427 Pred = ICmpInst::getSwappedPredicate(Pred);
7428 Changed = true;
7429 }
7430
7431 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007432 // addrec's loop, put the addrec on the left. Also make a dominance check,
7433 // as both operands could be addrecs loop-invariant in each other's loop.
7434 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7435 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007436 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007437 std::swap(LHS, RHS);
7438 Pred = ICmpInst::getSwappedPredicate(Pred);
7439 Changed = true;
7440 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007441 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007442
7443 // If there's a constant operand, canonicalize comparisons with boundary
7444 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7445 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007446 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007447
7448 bool SimplifiedByConstantRange = false;
7449
7450 if (!ICmpInst::isEquality(Pred)) {
7451 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7452 if (ExactCR.isFullSet())
7453 goto trivially_true;
7454 else if (ExactCR.isEmptySet())
7455 goto trivially_false;
7456
7457 APInt NewRHS;
7458 CmpInst::Predicate NewPred;
7459 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7460 ICmpInst::isEquality(NewPred)) {
7461 // We were able to convert an inequality to an equality.
7462 Pred = NewPred;
7463 RHS = getConstant(NewRHS);
7464 Changed = SimplifiedByConstantRange = true;
7465 }
7466 }
7467
7468 if (!SimplifiedByConstantRange) {
7469 switch (Pred) {
7470 default:
7471 break;
7472 case ICmpInst::ICMP_EQ:
7473 case ICmpInst::ICMP_NE:
7474 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7475 if (!RA)
7476 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7477 if (const SCEVMulExpr *ME =
7478 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7479 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7480 ME->getOperand(0)->isAllOnesValue()) {
7481 RHS = AE->getOperand(1);
7482 LHS = ME->getOperand(1);
7483 Changed = true;
7484 }
7485 break;
7486
7487
7488 // The "Should have been caught earlier!" messages refer to the fact
7489 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7490 // should have fired on the corresponding cases, and canonicalized the
7491 // check to trivially_true or trivially_false.
7492
7493 case ICmpInst::ICMP_UGE:
7494 assert(!RA.isMinValue() && "Should have been caught earlier!");
7495 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007496 RHS = getConstant(RA - 1);
7497 Changed = true;
7498 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007499 case ICmpInst::ICMP_ULE:
7500 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7501 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007502 RHS = getConstant(RA + 1);
7503 Changed = true;
7504 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007505 case ICmpInst::ICMP_SGE:
7506 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7507 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007508 RHS = getConstant(RA - 1);
7509 Changed = true;
7510 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007511 case ICmpInst::ICMP_SLE:
7512 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7513 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007514 RHS = getConstant(RA + 1);
7515 Changed = true;
7516 break;
7517 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007518 }
7519 }
7520
7521 // Check for obvious equality.
7522 if (HasSameValue(LHS, RHS)) {
7523 if (ICmpInst::isTrueWhenEqual(Pred))
7524 goto trivially_true;
7525 if (ICmpInst::isFalseWhenEqual(Pred))
7526 goto trivially_false;
7527 }
7528
Dan Gohman81585c12010-05-03 16:35:17 +00007529 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7530 // adding or subtracting 1 from one of the operands.
7531 switch (Pred) {
7532 case ICmpInst::ICMP_SLE:
7533 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7534 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007535 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007536 Pred = ICmpInst::ICMP_SLT;
7537 Changed = true;
7538 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007539 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007540 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007541 Pred = ICmpInst::ICMP_SLT;
7542 Changed = true;
7543 }
7544 break;
7545 case ICmpInst::ICMP_SGE:
7546 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007547 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007548 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007549 Pred = ICmpInst::ICMP_SGT;
7550 Changed = true;
7551 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7552 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007553 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007554 Pred = ICmpInst::ICMP_SGT;
7555 Changed = true;
7556 }
7557 break;
7558 case ICmpInst::ICMP_ULE:
7559 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007560 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007561 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007562 Pred = ICmpInst::ICMP_ULT;
7563 Changed = true;
7564 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007565 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007566 Pred = ICmpInst::ICMP_ULT;
7567 Changed = true;
7568 }
7569 break;
7570 case ICmpInst::ICMP_UGE:
7571 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007572 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007573 Pred = ICmpInst::ICMP_UGT;
7574 Changed = true;
7575 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007576 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007577 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007578 Pred = ICmpInst::ICMP_UGT;
7579 Changed = true;
7580 }
7581 break;
7582 default:
7583 break;
7584 }
7585
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007586 // TODO: More simplifications are possible here.
7587
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007588 // Recursively simplify until we either hit a recursion limit or nothing
7589 // changes.
7590 if (Changed)
7591 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7592
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007593 return Changed;
7594
7595trivially_true:
7596 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007597 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007598 Pred = ICmpInst::ICMP_EQ;
7599 return true;
7600
7601trivially_false:
7602 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007603 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007604 Pred = ICmpInst::ICMP_NE;
7605 return true;
7606}
7607
Dan Gohmane65c9172009-07-13 21:35:55 +00007608bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7609 return getSignedRange(S).getSignedMax().isNegative();
7610}
7611
7612bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7613 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7614}
7615
7616bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7617 return !getSignedRange(S).getSignedMin().isNegative();
7618}
7619
7620bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7621 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7622}
7623
7624bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7625 return isKnownNegative(S) || isKnownPositive(S);
7626}
7627
7628bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7629 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007630 // Canonicalize the inputs first.
7631 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7632
Dan Gohman07591692010-04-11 22:16:48 +00007633 // If LHS or RHS is an addrec, check to see if the condition is true in
7634 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007635 // If LHS and RHS are both addrec, both conditions must be true in
7636 // every iteration of the loop.
7637 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7638 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7639 bool LeftGuarded = false;
7640 bool RightGuarded = false;
7641 if (LAR) {
7642 const Loop *L = LAR->getLoop();
7643 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7644 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7645 if (!RAR) return true;
7646 LeftGuarded = true;
7647 }
7648 }
7649 if (RAR) {
7650 const Loop *L = RAR->getLoop();
7651 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7652 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7653 if (!LAR) return true;
7654 RightGuarded = true;
7655 }
7656 }
7657 if (LeftGuarded && RightGuarded)
7658 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007659
Sanjoy Das7d910f22015-10-02 18:50:30 +00007660 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7661 return true;
7662
Dan Gohman07591692010-04-11 22:16:48 +00007663 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007664 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007665}
7666
Sanjoy Das5dab2052015-07-27 21:42:49 +00007667bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7668 ICmpInst::Predicate Pred,
7669 bool &Increasing) {
7670 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7671
7672#ifndef NDEBUG
7673 // Verify an invariant: inverting the predicate should turn a monotonically
7674 // increasing change to a monotonically decreasing one, and vice versa.
7675 bool IncreasingSwapped;
7676 bool ResultSwapped = isMonotonicPredicateImpl(
7677 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7678
7679 assert(Result == ResultSwapped && "should be able to analyze both!");
7680 if (ResultSwapped)
7681 assert(Increasing == !IncreasingSwapped &&
7682 "monotonicity should flip as we flip the predicate");
7683#endif
7684
7685 return Result;
7686}
7687
7688bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7689 ICmpInst::Predicate Pred,
7690 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007691
7692 // A zero step value for LHS means the induction variable is essentially a
7693 // loop invariant value. We don't really depend on the predicate actually
7694 // flipping from false to true (for increasing predicates, and the other way
7695 // around for decreasing predicates), all we care about is that *if* the
7696 // predicate changes then it only changes from false to true.
7697 //
7698 // A zero step value in itself is not very useful, but there may be places
7699 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7700 // as general as possible.
7701
Sanjoy Das366acc12015-08-06 20:43:41 +00007702 switch (Pred) {
7703 default:
7704 return false; // Conservative answer
7705
7706 case ICmpInst::ICMP_UGT:
7707 case ICmpInst::ICMP_UGE:
7708 case ICmpInst::ICMP_ULT:
7709 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007710 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007711 return false;
7712
7713 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007714 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007715
7716 case ICmpInst::ICMP_SGT:
7717 case ICmpInst::ICMP_SGE:
7718 case ICmpInst::ICMP_SLT:
7719 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007720 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007721 return false;
7722
7723 const SCEV *Step = LHS->getStepRecurrence(*this);
7724
7725 if (isKnownNonNegative(Step)) {
7726 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7727 return true;
7728 }
7729
7730 if (isKnownNonPositive(Step)) {
7731 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7732 return true;
7733 }
7734
7735 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007736 }
7737
Sanjoy Das5dab2052015-07-27 21:42:49 +00007738 }
7739
Sanjoy Das366acc12015-08-06 20:43:41 +00007740 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007741}
7742
7743bool ScalarEvolution::isLoopInvariantPredicate(
7744 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7745 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7746 const SCEV *&InvariantRHS) {
7747
7748 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7749 if (!isLoopInvariant(RHS, L)) {
7750 if (!isLoopInvariant(LHS, L))
7751 return false;
7752
7753 std::swap(LHS, RHS);
7754 Pred = ICmpInst::getSwappedPredicate(Pred);
7755 }
7756
7757 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7758 if (!ArLHS || ArLHS->getLoop() != L)
7759 return false;
7760
7761 bool Increasing;
7762 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7763 return false;
7764
7765 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7766 // true as the loop iterates, and the backedge is control dependent on
7767 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7768 //
7769 // * if the predicate was false in the first iteration then the predicate
7770 // is never evaluated again, since the loop exits without taking the
7771 // backedge.
7772 // * if the predicate was true in the first iteration then it will
7773 // continue to be true for all future iterations since it is
7774 // monotonically increasing.
7775 //
7776 // For both the above possibilities, we can replace the loop varying
7777 // predicate with its value on the first iteration of the loop (which is
7778 // loop invariant).
7779 //
7780 // A similar reasoning applies for a monotonically decreasing predicate, by
7781 // replacing true with false and false with true in the above two bullets.
7782
7783 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7784
7785 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7786 return false;
7787
7788 InvariantPred = Pred;
7789 InvariantLHS = ArLHS->getStart();
7790 InvariantRHS = RHS;
7791 return true;
7792}
7793
Sanjoy Das401e6312016-02-01 20:48:10 +00007794bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7795 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007796 if (HasSameValue(LHS, RHS))
7797 return ICmpInst::isTrueWhenEqual(Pred);
7798
Dan Gohman07591692010-04-11 22:16:48 +00007799 // This code is split out from isKnownPredicate because it is called from
7800 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007801
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007802 auto CheckRanges =
7803 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7804 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7805 .contains(RangeLHS);
7806 };
7807
7808 // The check at the top of the function catches the case where the values are
7809 // known to be equal.
7810 if (Pred == CmpInst::ICMP_EQ)
7811 return false;
7812
7813 if (Pred == CmpInst::ICMP_NE)
7814 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7815 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7816 isKnownNonZero(getMinusSCEV(LHS, RHS));
7817
7818 if (CmpInst::isSigned(Pred))
7819 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7820
7821 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007822}
7823
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007824bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7825 const SCEV *LHS,
7826 const SCEV *RHS) {
7827
7828 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7829 // Return Y via OutY.
7830 auto MatchBinaryAddToConst =
7831 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7832 SCEV::NoWrapFlags ExpectedFlags) {
7833 const SCEV *NonConstOp, *ConstOp;
7834 SCEV::NoWrapFlags FlagsPresent;
7835
7836 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7837 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7838 return false;
7839
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007840 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007841 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7842 };
7843
7844 APInt C;
7845
7846 switch (Pred) {
7847 default:
7848 break;
7849
7850 case ICmpInst::ICMP_SGE:
7851 std::swap(LHS, RHS);
7852 case ICmpInst::ICMP_SLE:
7853 // X s<= (X + C)<nsw> if C >= 0
7854 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7855 return true;
7856
7857 // (X + C)<nsw> s<= X if C <= 0
7858 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7859 !C.isStrictlyPositive())
7860 return true;
7861 break;
7862
7863 case ICmpInst::ICMP_SGT:
7864 std::swap(LHS, RHS);
7865 case ICmpInst::ICMP_SLT:
7866 // X s< (X + C)<nsw> if C > 0
7867 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7868 C.isStrictlyPositive())
7869 return true;
7870
7871 // (X + C)<nsw> s< X if C < 0
7872 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7873 return true;
7874 break;
7875 }
7876
7877 return false;
7878}
7879
Sanjoy Das7d910f22015-10-02 18:50:30 +00007880bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7881 const SCEV *LHS,
7882 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007883 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007884 return false;
7885
7886 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7887 // the stack can result in exponential time complexity.
7888 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7889
7890 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7891 //
7892 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7893 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7894 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7895 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7896 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007897 return isKnownNonNegative(RHS) &&
7898 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7899 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007900}
7901
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007902bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7903 ICmpInst::Predicate Pred,
7904 const SCEV *LHS, const SCEV *RHS) {
7905 // No need to even try if we know the module has no guards.
7906 if (!HasGuards)
7907 return false;
7908
7909 return any_of(*BB, [&](Instruction &I) {
7910 using namespace llvm::PatternMatch;
7911
7912 Value *Condition;
7913 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7914 m_Value(Condition))) &&
7915 isImpliedCond(Pred, LHS, RHS, Condition, false);
7916 });
7917}
7918
Dan Gohmane65c9172009-07-13 21:35:55 +00007919/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7920/// protected by a conditional between LHS and RHS. This is used to
7921/// to eliminate casts.
7922bool
7923ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7924 ICmpInst::Predicate Pred,
7925 const SCEV *LHS, const SCEV *RHS) {
7926 // Interpret a null as meaning no loop, where there is obviously no guard
7927 // (interprocedural conditions notwithstanding).
7928 if (!L) return true;
7929
Sanjoy Das401e6312016-02-01 20:48:10 +00007930 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7931 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007932
Dan Gohmane65c9172009-07-13 21:35:55 +00007933 BasicBlock *Latch = L->getLoopLatch();
7934 if (!Latch)
7935 return false;
7936
7937 BranchInst *LoopContinuePredicate =
7938 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007939 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7940 isImpliedCond(Pred, LHS, RHS,
7941 LoopContinuePredicate->getCondition(),
7942 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7943 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007944
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007945 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007946 // -- that can lead to O(n!) time complexity.
7947 if (WalkingBEDominatingConds)
7948 return false;
7949
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007950 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007951
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007952 // See if we can exploit a trip count to prove the predicate.
7953 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7954 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7955 if (LatchBECount != getCouldNotCompute()) {
7956 // We know that Latch branches back to the loop header exactly
7957 // LatchBECount times. This means the backdege condition at Latch is
7958 // equivalent to "{0,+,1} u< LatchBECount".
7959 Type *Ty = LatchBECount->getType();
7960 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7961 const SCEV *LoopCounter =
7962 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7963 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7964 LatchBECount))
7965 return true;
7966 }
7967
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007968 // Check conditions due to any @llvm.assume intrinsics.
Hal Finkelcb9f78e2016-12-15 02:53:42 +00007969 auto CheckAssumptions = [&](const SCEV *S) {
7970 auto AMI = AffectedMap.find(S);
7971 if (AMI != AffectedMap.end())
7972 for (auto *Assume : AMI->second) {
7973 auto *CI = cast<CallInst>(Assume);
7974 if (!DT.dominates(CI, Latch->getTerminator()))
7975 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007976
Hal Finkelcb9f78e2016-12-15 02:53:42 +00007977 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7978 return true;
7979 }
7980
7981 return false;
7982 };
7983
7984 if (CheckAssumptions(LHS) || CheckAssumptions(RHS))
7985 return true;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007986
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007987 // If the loop is not reachable from the entry block, we risk running into an
7988 // infinite loop as we walk up into the dom tree. These loops do not matter
7989 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007990 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007991 return false;
7992
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007993 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7994 return true;
7995
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007996 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7997 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007998
7999 assert(DTN && "should reach the loop header before reaching the root!");
8000
8001 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008002 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8003 return true;
8004
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008005 BasicBlock *PBB = BB->getSinglePredecessor();
8006 if (!PBB)
8007 continue;
8008
8009 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8010 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8011 continue;
8012
8013 Value *Condition = ContinuePredicate->getCondition();
8014
8015 // If we have an edge `E` within the loop body that dominates the only
8016 // latch, the condition guarding `E` also guards the backedge. This
8017 // reasoning works only for loops with a single latch.
8018
8019 BasicBlockEdge DominatingEdge(PBB, BB);
8020 if (DominatingEdge.isSingleEdge()) {
8021 // We're constructively (and conservatively) enumerating edges within the
8022 // loop body that dominate the latch. The dominator tree better agree
8023 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008024 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008025
8026 if (isImpliedCond(Pred, LHS, RHS, Condition,
8027 BB != ContinuePredicate->getSuccessor(0)))
8028 return true;
8029 }
8030 }
8031
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008032 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008033}
8034
Dan Gohmane65c9172009-07-13 21:35:55 +00008035bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008036ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8037 ICmpInst::Predicate Pred,
8038 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008039 // Interpret a null as meaning no loop, where there is obviously no guard
8040 // (interprocedural conditions notwithstanding).
8041 if (!L) return false;
8042
Sanjoy Das401e6312016-02-01 20:48:10 +00008043 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8044 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008045
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008046 // Starting at the loop predecessor, climb up the predecessor chain, as long
8047 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008048 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008049 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008050 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008051 Pair.first;
8052 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008053
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008054 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8055 return true;
8056
Dan Gohman2a62fd92008-08-12 20:17:31 +00008057 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008058 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008059 if (!LoopEntryPredicate ||
8060 LoopEntryPredicate->isUnconditional())
8061 continue;
8062
Dan Gohmane18c2d62010-08-10 23:46:30 +00008063 if (isImpliedCond(Pred, LHS, RHS,
8064 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008065 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008066 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008067 }
8068
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008069 // Check conditions due to any @llvm.assume intrinsics.
Hal Finkelcb9f78e2016-12-15 02:53:42 +00008070 auto CheckAssumptions = [&](const SCEV *S) {
8071 auto AMI = AffectedMap.find(S);
8072 if (AMI != AffectedMap.end())
8073 for (auto *Assume : AMI->second) {
8074 auto *CI = cast<CallInst>(Assume);
8075 if (!DT.dominates(CI, L->getHeader()))
8076 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008077
Hal Finkelcb9f78e2016-12-15 02:53:42 +00008078 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8079 return true;
8080 }
8081
8082 return false;
8083 };
8084
8085 if (CheckAssumptions(LHS) || CheckAssumptions(RHS))
8086 return true;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008087
Dan Gohman2a62fd92008-08-12 20:17:31 +00008088 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008089}
8090
Dan Gohmane18c2d62010-08-10 23:46:30 +00008091bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008092 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008093 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008094 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008095 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008096 return false;
8097
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008098 auto ClearOnExit =
8099 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8100
Dan Gohman8b0a4192010-03-01 17:49:51 +00008101 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008103 if (BO->getOpcode() == Instruction::And) {
8104 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008105 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8106 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008107 } else if (BO->getOpcode() == Instruction::Or) {
8108 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008109 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8110 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008111 }
8112 }
8113
Dan Gohmane18c2d62010-08-10 23:46:30 +00008114 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008115 if (!ICI) return false;
8116
Andrew Trickfa594032012-11-29 18:35:13 +00008117 // Now that we found a conditional branch that dominates the loop or controls
8118 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008119 ICmpInst::Predicate FoundPred;
8120 if (Inverse)
8121 FoundPred = ICI->getInversePredicate();
8122 else
8123 FoundPred = ICI->getPredicate();
8124
8125 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8126 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008127
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008128 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8129}
8130
8131bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8132 const SCEV *RHS,
8133 ICmpInst::Predicate FoundPred,
8134 const SCEV *FoundLHS,
8135 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008136 // Balance the types.
8137 if (getTypeSizeInBits(LHS->getType()) <
8138 getTypeSizeInBits(FoundLHS->getType())) {
8139 if (CmpInst::isSigned(Pred)) {
8140 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8141 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8142 } else {
8143 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8144 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8145 }
8146 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008147 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008148 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008149 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8150 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8151 } else {
8152 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8153 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8154 }
8155 }
8156
Dan Gohman430f0cc2009-07-21 23:03:19 +00008157 // Canonicalize the query to match the way instcombine will have
8158 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008159 if (SimplifyICmpOperands(Pred, LHS, RHS))
8160 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008161 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008162 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8163 if (FoundLHS == FoundRHS)
8164 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008165
8166 // Check to see if we can make the LHS or RHS match.
8167 if (LHS == FoundRHS || RHS == FoundLHS) {
8168 if (isa<SCEVConstant>(RHS)) {
8169 std::swap(FoundLHS, FoundRHS);
8170 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8171 } else {
8172 std::swap(LHS, RHS);
8173 Pred = ICmpInst::getSwappedPredicate(Pred);
8174 }
8175 }
8176
8177 // Check whether the found predicate is the same as the desired predicate.
8178 if (FoundPred == Pred)
8179 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8180
8181 // Check whether swapping the found predicate makes it the same as the
8182 // desired predicate.
8183 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8184 if (isa<SCEVConstant>(RHS))
8185 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8186 else
8187 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8188 RHS, LHS, FoundLHS, FoundRHS);
8189 }
8190
Sanjoy Das6e78b172015-10-22 19:57:34 +00008191 // Unsigned comparison is the same as signed comparison when both the operands
8192 // are non-negative.
8193 if (CmpInst::isUnsigned(FoundPred) &&
8194 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8195 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8196 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8197
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008198 // Check if we can make progress by sharpening ranges.
8199 if (FoundPred == ICmpInst::ICMP_NE &&
8200 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8201
8202 const SCEVConstant *C = nullptr;
8203 const SCEV *V = nullptr;
8204
8205 if (isa<SCEVConstant>(FoundLHS)) {
8206 C = cast<SCEVConstant>(FoundLHS);
8207 V = FoundRHS;
8208 } else {
8209 C = cast<SCEVConstant>(FoundRHS);
8210 V = FoundLHS;
8211 }
8212
8213 // The guarding predicate tells us that C != V. If the known range
8214 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8215 // range we consider has to correspond to same signedness as the
8216 // predicate we're interested in folding.
8217
8218 APInt Min = ICmpInst::isSigned(Pred) ?
8219 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8220
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008221 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008222 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8223 // This is true even if (Min + 1) wraps around -- in case of
8224 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8225
8226 APInt SharperMin = Min + 1;
8227
8228 switch (Pred) {
8229 case ICmpInst::ICMP_SGE:
8230 case ICmpInst::ICMP_UGE:
8231 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8232 // RHS, we're done.
8233 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8234 getConstant(SharperMin)))
8235 return true;
8236
8237 case ICmpInst::ICMP_SGT:
8238 case ICmpInst::ICMP_UGT:
8239 // We know from the range information that (V `Pred` Min ||
8240 // V == Min). We know from the guarding condition that !(V
8241 // == Min). This gives us
8242 //
8243 // V `Pred` Min || V == Min && !(V == Min)
8244 // => V `Pred` Min
8245 //
8246 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8247
8248 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8249 return true;
8250
8251 default:
8252 // No change
8253 break;
8254 }
8255 }
8256 }
8257
Dan Gohman430f0cc2009-07-21 23:03:19 +00008258 // Check whether the actual condition is beyond sufficient.
8259 if (FoundPred == ICmpInst::ICMP_EQ)
8260 if (ICmpInst::isTrueWhenEqual(Pred))
8261 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8262 return true;
8263 if (Pred == ICmpInst::ICMP_NE)
8264 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8265 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8266 return true;
8267
8268 // Otherwise assume the worst.
8269 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008270}
8271
Sanjoy Das1ed69102015-10-13 02:53:27 +00008272bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8273 const SCEV *&L, const SCEV *&R,
8274 SCEV::NoWrapFlags &Flags) {
8275 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8276 if (!AE || AE->getNumOperands() != 2)
8277 return false;
8278
8279 L = AE->getOperand(0);
8280 R = AE->getOperand(1);
8281 Flags = AE->getNoWrapFlags();
8282 return true;
8283}
8284
Sanjoy Das0b1af852016-07-23 00:28:56 +00008285Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8286 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008287 // We avoid subtracting expressions here because this function is usually
8288 // fairly deep in the call stack (i.e. is called many times).
8289
Sanjoy Das96709c42015-09-25 23:53:45 +00008290 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8291 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8292 const auto *MAR = cast<SCEVAddRecExpr>(More);
8293
8294 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008295 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008296
8297 // We look at affine expressions only; not for correctness but to keep
8298 // getStepRecurrence cheap.
8299 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008300 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008301
Sanjoy Das1ed69102015-10-13 02:53:27 +00008302 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008303 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008304
8305 Less = LAR->getStart();
8306 More = MAR->getStart();
8307
8308 // fall through
8309 }
8310
8311 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008312 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8313 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008314 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008315 }
8316
8317 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008318 SCEV::NoWrapFlags Flags;
8319 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008320 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008321 if (R == More)
8322 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008323
Sanjoy Das1ed69102015-10-13 02:53:27 +00008324 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008325 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008326 if (R == Less)
8327 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008328
Sanjoy Das0b1af852016-07-23 00:28:56 +00008329 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008330}
8331
8332bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8333 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8334 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8335 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8336 return false;
8337
8338 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8339 if (!AddRecLHS)
8340 return false;
8341
8342 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8343 if (!AddRecFoundLHS)
8344 return false;
8345
8346 // We'd like to let SCEV reason about control dependencies, so we constrain
8347 // both the inequalities to be about add recurrences on the same loop. This
8348 // way we can use isLoopEntryGuardedByCond later.
8349
8350 const Loop *L = AddRecFoundLHS->getLoop();
8351 if (L != AddRecLHS->getLoop())
8352 return false;
8353
8354 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8355 //
8356 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8357 // ... (2)
8358 //
8359 // Informal proof for (2), assuming (1) [*]:
8360 //
8361 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8362 //
8363 // Then
8364 //
8365 // FoundLHS s< FoundRHS s< INT_MIN - C
8366 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8367 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8368 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8369 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8370 // <=> FoundLHS + C s< FoundRHS + C
8371 //
8372 // [*]: (1) can be proved by ruling out overflow.
8373 //
8374 // [**]: This can be proved by analyzing all the four possibilities:
8375 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8376 // (A s>= 0, B s>= 0).
8377 //
8378 // Note:
8379 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8380 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8381 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8382 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8383 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8384 // C)".
8385
Sanjoy Das0b1af852016-07-23 00:28:56 +00008386 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8387 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8388 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008389 return false;
8390
Sanjoy Das0b1af852016-07-23 00:28:56 +00008391 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008392 return true;
8393
Sanjoy Das96709c42015-09-25 23:53:45 +00008394 APInt FoundRHSLimit;
8395
8396 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008397 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008398 } else {
8399 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008400 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008401 }
8402
8403 // Try to prove (1) or (2), as needed.
8404 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8405 getConstant(FoundRHSLimit));
8406}
8407
Dan Gohman430f0cc2009-07-21 23:03:19 +00008408bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8409 const SCEV *LHS, const SCEV *RHS,
8410 const SCEV *FoundLHS,
8411 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008412 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8413 return true;
8414
Sanjoy Das96709c42015-09-25 23:53:45 +00008415 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8416 return true;
8417
Dan Gohman430f0cc2009-07-21 23:03:19 +00008418 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8419 FoundLHS, FoundRHS) ||
8420 // ~x < ~y --> x > y
8421 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8422 getNotSCEV(FoundRHS),
8423 getNotSCEV(FoundLHS));
8424}
8425
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008426
8427/// If Expr computes ~A, return A else return nullptr
8428static const SCEV *MatchNotExpr(const SCEV *Expr) {
8429 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008430 if (!Add || Add->getNumOperands() != 2 ||
8431 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008432 return nullptr;
8433
8434 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008435 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8436 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008437 return nullptr;
8438
8439 return AddRHS->getOperand(1);
8440}
8441
8442
8443/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8444template<typename MaxExprType>
8445static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8446 const SCEV *Candidate) {
8447 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8448 if (!MaxExpr) return false;
8449
Sanjoy Das347d2722015-12-01 07:49:27 +00008450 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008451}
8452
8453
8454/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8455template<typename MaxExprType>
8456static bool IsMinConsistingOf(ScalarEvolution &SE,
8457 const SCEV *MaybeMinExpr,
8458 const SCEV *Candidate) {
8459 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8460 if (!MaybeMaxExpr)
8461 return false;
8462
8463 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8464}
8465
Hal Finkela8d205f2015-08-19 01:51:51 +00008466static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8467 ICmpInst::Predicate Pred,
8468 const SCEV *LHS, const SCEV *RHS) {
8469
8470 // If both sides are affine addrecs for the same loop, with equal
8471 // steps, and we know the recurrences don't wrap, then we only
8472 // need to check the predicate on the starting values.
8473
8474 if (!ICmpInst::isRelational(Pred))
8475 return false;
8476
8477 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8478 if (!LAR)
8479 return false;
8480 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8481 if (!RAR)
8482 return false;
8483 if (LAR->getLoop() != RAR->getLoop())
8484 return false;
8485 if (!LAR->isAffine() || !RAR->isAffine())
8486 return false;
8487
8488 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8489 return false;
8490
Hal Finkelff08a2e2015-08-19 17:26:07 +00008491 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8492 SCEV::FlagNSW : SCEV::FlagNUW;
8493 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008494 return false;
8495
8496 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8497}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008498
8499/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8500/// expression?
8501static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8502 ICmpInst::Predicate Pred,
8503 const SCEV *LHS, const SCEV *RHS) {
8504 switch (Pred) {
8505 default:
8506 return false;
8507
8508 case ICmpInst::ICMP_SGE:
8509 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008510 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008511 case ICmpInst::ICMP_SLE:
8512 return
8513 // min(A, ...) <= A
8514 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8515 // A <= max(A, ...)
8516 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8517
8518 case ICmpInst::ICMP_UGE:
8519 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008520 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008521 case ICmpInst::ICMP_ULE:
8522 return
8523 // min(A, ...) <= A
8524 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8525 // A <= max(A, ...)
8526 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8527 }
8528
8529 llvm_unreachable("covered switch fell through?!");
8530}
8531
Dan Gohmane65c9172009-07-13 21:35:55 +00008532bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008533ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8534 const SCEV *LHS, const SCEV *RHS,
8535 const SCEV *FoundLHS,
8536 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008537 auto IsKnownPredicateFull =
8538 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008539 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008540 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008541 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8542 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008543 };
8544
Dan Gohmane65c9172009-07-13 21:35:55 +00008545 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008546 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8547 case ICmpInst::ICMP_EQ:
8548 case ICmpInst::ICMP_NE:
8549 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8550 return true;
8551 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008552 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008553 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008554 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8555 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008556 return true;
8557 break;
8558 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008559 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008560 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8561 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008562 return true;
8563 break;
8564 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008565 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008566 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8567 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008568 return true;
8569 break;
8570 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008571 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008572 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8573 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008574 return true;
8575 break;
8576 }
8577
8578 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008579}
8580
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008581bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8582 const SCEV *LHS,
8583 const SCEV *RHS,
8584 const SCEV *FoundLHS,
8585 const SCEV *FoundRHS) {
8586 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8587 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8588 // reduce the compile time impact of this optimization.
8589 return false;
8590
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008591 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008592 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008593 return false;
8594
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008595 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008596
8597 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8598 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8599 ConstantRange FoundLHSRange =
8600 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8601
Sanjoy Das095f5b22016-07-22 20:47:55 +00008602 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8603 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008604
8605 // We can also compute the range of values for `LHS` that satisfy the
8606 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008607 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008608 ConstantRange SatisfyingLHSRange =
8609 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8610
8611 // The antecedent implies the consequent if every value of `LHS` that
8612 // satisfies the antecedent also satisfies the consequent.
8613 return SatisfyingLHSRange.contains(LHSRange);
8614}
8615
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008616bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8617 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008618 assert(isKnownPositive(Stride) && "Positive stride expected!");
8619
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008620 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008621
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008622 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008623 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008624
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008625 if (IsSigned) {
8626 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8627 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8628 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8629 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008630
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008631 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8632 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008633 }
Dan Gohman01048422009-06-21 23:46:38 +00008634
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008635 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8636 APInt MaxValue = APInt::getMaxValue(BitWidth);
8637 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8638 .getUnsignedMax();
8639
8640 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8641 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8642}
8643
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008644bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8645 bool IsSigned, bool NoWrap) {
8646 if (NoWrap) return false;
8647
8648 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008649 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008650
8651 if (IsSigned) {
8652 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8653 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8654 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8655 .getSignedMax();
8656
8657 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8658 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8659 }
8660
8661 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8662 APInt MinValue = APInt::getMinValue(BitWidth);
8663 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8664 .getUnsignedMax();
8665
8666 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8667 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8668}
8669
Johannes Doerfert2683e562015-02-09 12:34:23 +00008670const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008671 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008672 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008673 Delta = Equality ? getAddExpr(Delta, Step)
8674 : getAddExpr(Delta, getMinusSCEV(Step, One));
8675 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008676}
8677
Andrew Trick3ca3f982011-07-26 17:19:55 +00008678ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008679ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008680 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008681 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008682 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008683 // We handle only IV < Invariant
8684 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008685 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008686
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008687 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008688 bool PredicatedIV = false;
8689
8690 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008691 // Try to make this an AddRec using runtime tests, in the first X
8692 // iterations of this loop, where X is the SCEV expression found by the
8693 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008694 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008695 PredicatedIV = true;
8696 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008697
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008698 // Avoid weird loops
8699 if (!IV || IV->getLoop() != L || !IV->isAffine())
8700 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008701
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008702 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008703 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008704
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008705 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008706
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008707 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008708
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008709 // Avoid negative or zero stride values.
8710 if (!PositiveStride) {
8711 // We can compute the correct backedge taken count for loops with unknown
8712 // strides if we can prove that the loop is not an infinite loop with side
8713 // effects. Here's the loop structure we are trying to handle -
8714 //
8715 // i = start
8716 // do {
8717 // A[i] = i;
8718 // i += s;
8719 // } while (i < end);
8720 //
8721 // The backedge taken count for such loops is evaluated as -
8722 // (max(end, start + stride) - start - 1) /u stride
8723 //
8724 // The additional preconditions that we need to check to prove correctness
8725 // of the above formula is as follows -
8726 //
8727 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8728 // NoWrap flag).
8729 // b) loop is single exit with no side effects.
8730 //
8731 //
8732 // Precondition a) implies that if the stride is negative, this is a single
8733 // trip loop. The backedge taken count formula reduces to zero in this case.
8734 //
8735 // Precondition b) implies that the unknown stride cannot be zero otherwise
8736 // we have UB.
8737 //
8738 // The positive stride case is the same as isKnownPositive(Stride) returning
8739 // true (original behavior of the function).
8740 //
8741 // We want to make sure that the stride is truly unknown as there are edge
8742 // cases where ScalarEvolution propagates no wrap flags to the
8743 // post-increment/decrement IV even though the increment/decrement operation
8744 // itself is wrapping. The computed backedge taken count may be wrong in
8745 // such cases. This is prevented by checking that the stride is not known to
8746 // be either positive or non-positive. For example, no wrap flags are
8747 // propagated to the post-increment IV of this loop with a trip count of 2 -
8748 //
8749 // unsigned char i;
8750 // for(i=127; i<128; i+=129)
8751 // A[i] = i;
8752 //
8753 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8754 !loopHasNoSideEffects(L))
8755 return getCouldNotCompute();
8756
8757 } else if (!Stride->isOne() &&
8758 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8759 // Avoid proven overflow cases: this will ensure that the backedge taken
8760 // count will not generate any unsigned overflow. Relaxed no-overflow
8761 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8762 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008763 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008764
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008765 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8766 : ICmpInst::ICMP_ULT;
8767 const SCEV *Start = IV->getStart();
8768 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00008769 // If the backedge is taken at least once, then it will be taken
8770 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8771 // is the LHS value of the less-than comparison the first time it is evaluated
8772 // and End is the RHS.
8773 const SCEV *BECountIfBackedgeTaken =
8774 computeBECount(getMinusSCEV(End, Start), Stride, false);
8775 // If the loop entry is guarded by the result of the backedge test of the
8776 // first loop iteration, then we know the backedge will be taken at least
8777 // once and so the backedge taken count is as above. If not then we use the
8778 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8779 // as if the backedge is taken at least once max(End,Start) is End and so the
8780 // result is as above, and if not max(End,Start) is Start so we get a backedge
8781 // count of zero.
8782 const SCEV *BECount;
8783 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8784 BECount = BECountIfBackedgeTaken;
8785 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008786 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00008787 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8788 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008789
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008790 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00008791 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008792 if (isa<SCEVConstant>(BECount))
8793 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00008794 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00008795 // If we know exactly how many times the backedge will be taken if it's
8796 // taken at least once, then the backedge count will either be that or
8797 // zero.
8798 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00008799 MaxOrZero = true;
8800 } else {
John Brawnecf79302016-10-18 10:10:53 +00008801 // Calculate the maximum backedge count based on the range of values
8802 // permitted by Start, End, and Stride.
8803 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8804 : getUnsignedRange(Start).getUnsignedMin();
8805
8806 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8807
8808 APInt StrideForMaxBECount;
8809
8810 if (PositiveStride)
8811 StrideForMaxBECount =
8812 IsSigned ? getSignedRange(Stride).getSignedMin()
8813 : getUnsignedRange(Stride).getUnsignedMin();
8814 else
8815 // Using a stride of 1 is safe when computing max backedge taken count for
8816 // a loop with unknown stride.
8817 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8818
8819 APInt Limit =
8820 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8821 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8822
8823 // Although End can be a MAX expression we estimate MaxEnd considering only
8824 // the case End = RHS. This is safe because in the other case (End - Start)
8825 // is zero, leading to a zero maximum backedge taken count.
8826 APInt MaxEnd =
8827 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8828 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8829
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008830 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008831 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00008832 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008833
8834 if (isa<SCEVCouldNotCompute>(MaxBECount))
8835 MaxBECount = BECount;
8836
John Brawn84b21832016-10-21 11:08:48 +00008837 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008838}
8839
8840ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008841ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008842 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008843 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008844 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008845 // We handle only IV > Invariant
8846 if (!isLoopInvariant(RHS, L))
8847 return getCouldNotCompute();
8848
8849 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008850 if (!IV && AllowPredicates)
8851 // Try to make this an AddRec using runtime tests, in the first X
8852 // iterations of this loop, where X is the SCEV expression found by the
8853 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008854 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008855
8856 // Avoid weird loops
8857 if (!IV || IV->getLoop() != L || !IV->isAffine())
8858 return getCouldNotCompute();
8859
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008860 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008861 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8862
8863 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8864
8865 // Avoid negative or zero stride values
8866 if (!isKnownPositive(Stride))
8867 return getCouldNotCompute();
8868
8869 // Avoid proven overflow cases: this will ensure that the backedge taken count
8870 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008871 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008872 // behaviors like the case of C language.
8873 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8874 return getCouldNotCompute();
8875
8876 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8877 : ICmpInst::ICMP_UGT;
8878
8879 const SCEV *Start = IV->getStart();
8880 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008881 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8882 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008883
8884 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8885
8886 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8887 : getUnsignedRange(Start).getUnsignedMax();
8888
8889 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8890 : getUnsignedRange(Stride).getUnsignedMin();
8891
8892 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8893 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8894 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8895
8896 // Although End can be a MIN expression we estimate MinEnd considering only
8897 // the case End = RHS. This is safe because in the other case (Start - End)
8898 // is zero, leading to a zero maximum backedge taken count.
8899 APInt MinEnd =
8900 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8901 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8902
8903
8904 const SCEV *MaxBECount = getCouldNotCompute();
8905 if (isa<SCEVConstant>(BECount))
8906 MaxBECount = BECount;
8907 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008908 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008909 getConstant(MinStride), false);
8910
8911 if (isa<SCEVCouldNotCompute>(MaxBECount))
8912 MaxBECount = BECount;
8913
John Brawn84b21832016-10-21 11:08:48 +00008914 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00008915}
8916
Benjamin Kramerc321e532016-06-08 19:09:22 +00008917const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008918 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008919 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008920 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008921
8922 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008923 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008924 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008925 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008926 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008927 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008928 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008929 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008930 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008931 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008932 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008933 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008934 }
8935
8936 // The only time we can solve this is when we have all constant indices.
8937 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008938 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008939 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008940
8941 // Okay at this point we know that all elements of the chrec are constants and
8942 // that the start element is zero.
8943
8944 // First check to see if the range contains zero. If not, the first
8945 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008946 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008947 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008948 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008949
Chris Lattnerd934c702004-04-02 20:23:17 +00008950 if (isAffine()) {
8951 // If this is an affine expression then we have this situation:
8952 // Solve {0,+,A} in Range === Ax in Range
8953
Nick Lewycky52460262007-07-16 02:08:00 +00008954 // We know that zero is in the range. If A is positive then we know that
8955 // the upper value of the range must be the first possible exit value.
8956 // If A is negative then the lower of the range is the last possible loop
8957 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008958 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008959 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008960 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008961
Nick Lewycky52460262007-07-16 02:08:00 +00008962 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008963 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008964 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008965
8966 // Evaluate at the exit value. If we really did fall out of the valid
8967 // range, then we computed our trip count, otherwise wrap around or other
8968 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008969 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008970 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008971 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008972
8973 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008974 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008975 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008976 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008977 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008978 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008979 } else if (isQuadratic()) {
8980 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8981 // quadratic equation to solve it. To do this, we must frame our problem in
8982 // terms of figuring out when zero is crossed, instead of when
8983 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008984 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008985 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00008986 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008987
8988 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008989 if (auto Roots =
8990 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008991 const SCEVConstant *R1 = Roots->first;
8992 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008993 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008994 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8995 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008996 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008997 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008998
Chris Lattnerd934c702004-04-02 20:23:17 +00008999 // Make sure the root is not off by one. The returned iteration should
9000 // not be in the range, but the previous one should be. When solving
9001 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00009002 ConstantInt *R1Val =
9003 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009004 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009005 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009006 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009007 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009008
Dan Gohmana37eaf22007-10-22 18:31:58 +00009009 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009010 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009011 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00009012 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009013 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009014
Chris Lattnerd934c702004-04-02 20:23:17 +00009015 // If R1 was not in the range, then it is a good return value. Make
9016 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009017 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009018 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009019 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009020 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009021 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00009022 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009023 }
9024 }
9025 }
9026
Dan Gohman31efa302009-04-18 17:58:19 +00009027 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009028}
9029
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009030// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009031static inline bool containsUndefs(const SCEV *S) {
9032 return SCEVExprContains(S, [](const SCEV *S) {
9033 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9034 return isa<UndefValue>(SU->getValue());
9035 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9036 return isa<UndefValue>(SC->getValue());
9037 return false;
9038 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009039}
9040
9041namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009042// Collect all steps of SCEV expressions.
9043struct SCEVCollectStrides {
9044 ScalarEvolution &SE;
9045 SmallVectorImpl<const SCEV *> &Strides;
9046
9047 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9048 : SE(SE), Strides(S) {}
9049
9050 bool follow(const SCEV *S) {
9051 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9052 Strides.push_back(AR->getStepRecurrence(SE));
9053 return true;
9054 }
9055 bool isDone() const { return false; }
9056};
9057
9058// Collect all SCEVUnknown and SCEVMulExpr expressions.
9059struct SCEVCollectTerms {
9060 SmallVectorImpl<const SCEV *> &Terms;
9061
9062 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9063 : Terms(T) {}
9064
9065 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009066 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9067 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009068 if (!containsUndefs(S))
9069 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009070
9071 // Stop recursion: once we collected a term, do not walk its operands.
9072 return false;
9073 }
9074
9075 // Keep looking.
9076 return true;
9077 }
9078 bool isDone() const { return false; }
9079};
Tobias Grosser374bce02015-10-12 08:02:00 +00009080
9081// Check if a SCEV contains an AddRecExpr.
9082struct SCEVHasAddRec {
9083 bool &ContainsAddRec;
9084
9085 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9086 ContainsAddRec = false;
9087 }
9088
9089 bool follow(const SCEV *S) {
9090 if (isa<SCEVAddRecExpr>(S)) {
9091 ContainsAddRec = true;
9092
9093 // Stop recursion: once we collected a term, do not walk its operands.
9094 return false;
9095 }
9096
9097 // Keep looking.
9098 return true;
9099 }
9100 bool isDone() const { return false; }
9101};
9102
9103// Find factors that are multiplied with an expression that (possibly as a
9104// subexpression) contains an AddRecExpr. In the expression:
9105//
9106// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9107//
9108// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9109// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9110// parameters as they form a product with an induction variable.
9111//
9112// This collector expects all array size parameters to be in the same MulExpr.
9113// It might be necessary to later add support for collecting parameters that are
9114// spread over different nested MulExpr.
9115struct SCEVCollectAddRecMultiplies {
9116 SmallVectorImpl<const SCEV *> &Terms;
9117 ScalarEvolution &SE;
9118
9119 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9120 : Terms(T), SE(SE) {}
9121
9122 bool follow(const SCEV *S) {
9123 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9124 bool HasAddRec = false;
9125 SmallVector<const SCEV *, 0> Operands;
9126 for (auto Op : Mul->operands()) {
9127 if (isa<SCEVUnknown>(Op)) {
9128 Operands.push_back(Op);
9129 } else {
9130 bool ContainsAddRec;
9131 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9132 visitAll(Op, ContiansAddRec);
9133 HasAddRec |= ContainsAddRec;
9134 }
9135 }
9136 if (Operands.size() == 0)
9137 return true;
9138
9139 if (!HasAddRec)
9140 return false;
9141
9142 Terms.push_back(SE.getMulExpr(Operands));
9143 // Stop recursion: once we collected a term, do not walk its operands.
9144 return false;
9145 }
9146
9147 // Keep looking.
9148 return true;
9149 }
9150 bool isDone() const { return false; }
9151};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009152}
Sebastian Pop448712b2014-05-07 18:01:20 +00009153
Tobias Grosser374bce02015-10-12 08:02:00 +00009154/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9155/// two places:
9156/// 1) The strides of AddRec expressions.
9157/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009158void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9159 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009160 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009161 SCEVCollectStrides StrideCollector(*this, Strides);
9162 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009163
9164 DEBUG({
9165 dbgs() << "Strides:\n";
9166 for (const SCEV *S : Strides)
9167 dbgs() << *S << "\n";
9168 });
9169
9170 for (const SCEV *S : Strides) {
9171 SCEVCollectTerms TermCollector(Terms);
9172 visitAll(S, TermCollector);
9173 }
9174
9175 DEBUG({
9176 dbgs() << "Terms:\n";
9177 for (const SCEV *T : Terms)
9178 dbgs() << *T << "\n";
9179 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009180
9181 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9182 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009183}
9184
Sebastian Popb1a548f2014-05-12 19:01:53 +00009185static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009186 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009187 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009188 int Last = Terms.size() - 1;
9189 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009190
Sebastian Pop448712b2014-05-07 18:01:20 +00009191 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009192 if (Last == 0) {
9193 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009194 SmallVector<const SCEV *, 2> Qs;
9195 for (const SCEV *Op : M->operands())
9196 if (!isa<SCEVConstant>(Op))
9197 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009198
Sebastian Pope30bd352014-05-27 22:41:56 +00009199 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009200 }
9201
Sebastian Pope30bd352014-05-27 22:41:56 +00009202 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009203 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009204 }
9205
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009206 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009207 // Normalize the terms before the next call to findArrayDimensionsRec.
9208 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009209 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009210
9211 // Bail out when GCD does not evenly divide one of the terms.
9212 if (!R->isZero())
9213 return false;
9214
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009215 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009216 }
9217
Tobias Grosser3080cf12014-05-08 07:55:34 +00009218 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009219 Terms.erase(
9220 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9221 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009222
Sebastian Pop448712b2014-05-07 18:01:20 +00009223 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009224 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9225 return false;
9226
Sebastian Pope30bd352014-05-27 22:41:56 +00009227 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009228 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009229}
Sebastian Popc62c6792013-11-12 22:47:20 +00009230
Sebastian Pop448712b2014-05-07 18:01:20 +00009231
9232// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009233static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009234 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009235 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009236 return true;
9237 return false;
9238}
9239
9240// Return the number of product terms in S.
9241static inline int numberOfTerms(const SCEV *S) {
9242 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9243 return Expr->getNumOperands();
9244 return 1;
9245}
9246
Sebastian Popa6e58602014-05-27 22:41:45 +00009247static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9248 if (isa<SCEVConstant>(T))
9249 return nullptr;
9250
9251 if (isa<SCEVUnknown>(T))
9252 return T;
9253
9254 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9255 SmallVector<const SCEV *, 2> Factors;
9256 for (const SCEV *Op : M->operands())
9257 if (!isa<SCEVConstant>(Op))
9258 Factors.push_back(Op);
9259
9260 return SE.getMulExpr(Factors);
9261 }
9262
9263 return T;
9264}
9265
9266/// Return the size of an element read or written by Inst.
9267const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9268 Type *Ty;
9269 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9270 Ty = Store->getValueOperand()->getType();
9271 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009272 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009273 else
9274 return nullptr;
9275
9276 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9277 return getSizeOfExpr(ETy, Ty);
9278}
9279
Sebastian Popa6e58602014-05-27 22:41:45 +00009280void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9281 SmallVectorImpl<const SCEV *> &Sizes,
9282 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009283 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009284 return;
9285
9286 // Early return when Terms do not contain parameters: we do not delinearize
9287 // non parametric SCEVs.
9288 if (!containsParameters(Terms))
9289 return;
9290
9291 DEBUG({
9292 dbgs() << "Terms:\n";
9293 for (const SCEV *T : Terms)
9294 dbgs() << *T << "\n";
9295 });
9296
9297 // Remove duplicates.
9298 std::sort(Terms.begin(), Terms.end());
9299 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9300
9301 // Put larger terms first.
9302 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9303 return numberOfTerms(LHS) > numberOfTerms(RHS);
9304 });
9305
Sebastian Popa6e58602014-05-27 22:41:45 +00009306 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9307
Tobias Grosser374bce02015-10-12 08:02:00 +00009308 // Try to divide all terms by the element size. If term is not divisible by
9309 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009310 for (const SCEV *&Term : Terms) {
9311 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009312 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009313 if (!Q->isZero())
9314 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009315 }
9316
9317 SmallVector<const SCEV *, 4> NewTerms;
9318
9319 // Remove constant factors.
9320 for (const SCEV *T : Terms)
9321 if (const SCEV *NewT = removeConstantFactors(SE, T))
9322 NewTerms.push_back(NewT);
9323
Sebastian Pop448712b2014-05-07 18:01:20 +00009324 DEBUG({
9325 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009326 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009327 dbgs() << *T << "\n";
9328 });
9329
Sebastian Popa6e58602014-05-27 22:41:45 +00009330 if (NewTerms.empty() ||
9331 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009332 Sizes.clear();
9333 return;
9334 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009335
Sebastian Popa6e58602014-05-27 22:41:45 +00009336 // The last element to be pushed into Sizes is the size of an element.
9337 Sizes.push_back(ElementSize);
9338
Sebastian Pop448712b2014-05-07 18:01:20 +00009339 DEBUG({
9340 dbgs() << "Sizes:\n";
9341 for (const SCEV *S : Sizes)
9342 dbgs() << *S << "\n";
9343 });
9344}
9345
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009346void ScalarEvolution::computeAccessFunctions(
9347 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9348 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009349
Sebastian Popb1a548f2014-05-12 19:01:53 +00009350 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009351 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009352 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009353
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009354 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009355 if (!AR->isAffine())
9356 return;
9357
9358 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009359 int Last = Sizes.size() - 1;
9360 for (int i = Last; i >= 0; i--) {
9361 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009362 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009363
9364 DEBUG({
9365 dbgs() << "Res: " << *Res << "\n";
9366 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9367 dbgs() << "Res divided by Sizes[i]:\n";
9368 dbgs() << "Quotient: " << *Q << "\n";
9369 dbgs() << "Remainder: " << *R << "\n";
9370 });
9371
9372 Res = Q;
9373
Sebastian Popa6e58602014-05-27 22:41:45 +00009374 // Do not record the last subscript corresponding to the size of elements in
9375 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009376 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009377
9378 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009379 if (isa<SCEVAddRecExpr>(R)) {
9380 Subscripts.clear();
9381 Sizes.clear();
9382 return;
9383 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009384
Sebastian Pop448712b2014-05-07 18:01:20 +00009385 continue;
9386 }
9387
9388 // Record the access function for the current subscript.
9389 Subscripts.push_back(R);
9390 }
9391
9392 // Also push in last position the remainder of the last division: it will be
9393 // the access function of the innermost dimension.
9394 Subscripts.push_back(Res);
9395
9396 std::reverse(Subscripts.begin(), Subscripts.end());
9397
9398 DEBUG({
9399 dbgs() << "Subscripts:\n";
9400 for (const SCEV *S : Subscripts)
9401 dbgs() << *S << "\n";
9402 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009403}
9404
Sebastian Popc62c6792013-11-12 22:47:20 +00009405/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9406/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009407/// is the offset start of the array. The SCEV->delinearize algorithm computes
9408/// the multiples of SCEV coefficients: that is a pattern matching of sub
9409/// expressions in the stride and base of a SCEV corresponding to the
9410/// computation of a GCD (greatest common divisor) of base and stride. When
9411/// SCEV->delinearize fails, it returns the SCEV unchanged.
9412///
9413/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9414///
9415/// void foo(long n, long m, long o, double A[n][m][o]) {
9416///
9417/// for (long i = 0; i < n; i++)
9418/// for (long j = 0; j < m; j++)
9419/// for (long k = 0; k < o; k++)
9420/// A[i][j][k] = 1.0;
9421/// }
9422///
9423/// the delinearization input is the following AddRec SCEV:
9424///
9425/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9426///
9427/// From this SCEV, we are able to say that the base offset of the access is %A
9428/// because it appears as an offset that does not divide any of the strides in
9429/// the loops:
9430///
9431/// CHECK: Base offset: %A
9432///
9433/// and then SCEV->delinearize determines the size of some of the dimensions of
9434/// the array as these are the multiples by which the strides are happening:
9435///
9436/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9437///
9438/// Note that the outermost dimension remains of UnknownSize because there are
9439/// no strides that would help identifying the size of the last dimension: when
9440/// the array has been statically allocated, one could compute the size of that
9441/// dimension by dividing the overall size of the array by the size of the known
9442/// dimensions: %m * %o * 8.
9443///
9444/// Finally delinearize provides the access functions for the array reference
9445/// that does correspond to A[i][j][k] of the above C testcase:
9446///
9447/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9448///
9449/// The testcases are checking the output of a function pass:
9450/// DelinearizationPass that walks through all loads and stores of a function
9451/// asking for the SCEV of the memory access with respect to all enclosing
9452/// loops, calling SCEV->delinearize on that and printing the results.
9453
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009454void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009455 SmallVectorImpl<const SCEV *> &Subscripts,
9456 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009457 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009458 // First step: collect parametric terms.
9459 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009460 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009461
Sebastian Popb1a548f2014-05-12 19:01:53 +00009462 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009463 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009464
Sebastian Pop448712b2014-05-07 18:01:20 +00009465 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009466 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009467
Sebastian Popb1a548f2014-05-12 19:01:53 +00009468 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009469 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009470
Sebastian Pop448712b2014-05-07 18:01:20 +00009471 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009472 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009473
Sebastian Pop28e6b972014-05-27 22:41:51 +00009474 if (Subscripts.empty())
9475 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009476
Sebastian Pop448712b2014-05-07 18:01:20 +00009477 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009478 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009479 dbgs() << "ArrayDecl[UnknownSize]";
9480 for (const SCEV *S : Sizes)
9481 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009482
Sebastian Pop444621a2014-05-09 22:45:02 +00009483 dbgs() << "\nArrayRef";
9484 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009485 dbgs() << "[" << *S << "]";
9486 dbgs() << "\n";
9487 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009488}
Chris Lattnerd934c702004-04-02 20:23:17 +00009489
9490//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009491// SCEVCallbackVH Class Implementation
9492//===----------------------------------------------------------------------===//
9493
Dan Gohmand33a0902009-05-19 19:22:47 +00009494void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009495 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009496 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9497 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009498 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009499 // this now dangles!
9500}
9501
Dan Gohman7a066722010-07-28 01:09:07 +00009502void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009503 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009504
Dan Gohman48f82222009-05-04 22:30:44 +00009505 // Forget all the expressions associated with users of the old value,
9506 // so that future queries will recompute the expressions using the new
9507 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009508 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009509 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009510 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009511 while (!Worklist.empty()) {
9512 User *U = Worklist.pop_back_val();
9513 // Deleting the Old value will cause this to dangle. Postpone
9514 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009515 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009516 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009517 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009518 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009519 if (PHINode *PN = dyn_cast<PHINode>(U))
9520 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009521 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009522 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009523 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009524 // Delete the Old value.
9525 if (PHINode *PN = dyn_cast<PHINode>(Old))
9526 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009527 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009528 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009529}
9530
Dan Gohmand33a0902009-05-19 19:22:47 +00009531ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009532 : CallbackVH(V), SE(se) {}
9533
9534//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009535// ScalarEvolution Class Implementation
9536//===----------------------------------------------------------------------===//
9537
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009538ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00009539 DominatorTree &DT, LoopInfo &LI)
9540 : F(F), TLI(TLI), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009541 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009542 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9543 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009544 FirstUnknown(nullptr) {
9545
9546 // To use guards for proving predicates, we need to scan every instruction in
9547 // relevant basic blocks, and not just terminators. Doing this is a waste of
9548 // time if the IR does not actually contain any calls to
9549 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9550 //
9551 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9552 // to _add_ guards to the module when there weren't any before, and wants
9553 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9554 // efficient in lieu of being smart in that rather obscure case.
9555
9556 auto *GuardDecl = F.getParent()->getFunction(
9557 Intrinsic::getName(Intrinsic::experimental_guard));
9558 HasGuards = GuardDecl && !GuardDecl->use_empty();
9559}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009560
9561ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00009562 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009563 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009564 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009565 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009566 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009567 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009568 PredicatedBackedgeTakenCounts(
9569 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009570 ConstantEvolutionLoopExitValue(
9571 std::move(Arg.ConstantEvolutionLoopExitValue)),
9572 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9573 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009574 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009575 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009576 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9577 SignedRanges(std::move(Arg.SignedRanges)),
9578 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009579 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009580 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9581 FirstUnknown(Arg.FirstUnknown) {
9582 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009583}
9584
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009585ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009586 // Iterate through all the SCEVUnknown instances and call their
9587 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009588 for (SCEVUnknown *U = FirstUnknown; U;) {
9589 SCEVUnknown *Tmp = U;
9590 U = U->Next;
9591 Tmp->~SCEVUnknown();
9592 }
Craig Topper9f008862014-04-15 04:59:12 +00009593 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009594
Wei Mia49559b2016-02-04 01:27:38 +00009595 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009596 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009597 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009598
9599 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9600 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009601 for (auto &BTCI : BackedgeTakenCounts)
9602 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009603 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9604 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009605
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009606 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009607 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009608 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009609}
9610
Dan Gohmanc8e23622009-04-21 23:15:49 +00009611bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009612 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009613}
9614
Dan Gohmanc8e23622009-04-21 23:15:49 +00009615static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009616 const Loop *L) {
9617 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009618 for (Loop *I : *L)
9619 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009620
Dan Gohmanbc694912010-01-09 18:17:45 +00009621 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009622 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009623 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009624
Dan Gohmancb0efec2009-12-18 01:14:11 +00009625 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009626 L->getExitBlocks(ExitBlocks);
9627 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009628 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009629
Dan Gohman0bddac12009-02-24 18:55:53 +00009630 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9631 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009632 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009633 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009634 }
9635
Dan Gohmanbc694912010-01-09 18:17:45 +00009636 OS << "\n"
9637 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009638 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009639 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009640
9641 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9642 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009643 if (SE->isBackedgeTakenCountMaxOrZero(L))
9644 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009645 } else {
9646 OS << "Unpredictable max backedge-taken count. ";
9647 }
9648
Silviu Baranga6f444df2016-04-08 14:29:09 +00009649 OS << "\n"
9650 "Loop ";
9651 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9652 OS << ": ";
9653
9654 SCEVUnionPredicate Pred;
9655 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9656 if (!isa<SCEVCouldNotCompute>(PBT)) {
9657 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9658 OS << " Predicates:\n";
9659 Pred.print(OS, 4);
9660 } else {
9661 OS << "Unpredictable predicated backedge-taken count. ";
9662 }
Dan Gohman69942932009-06-24 00:33:16 +00009663 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009664}
9665
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009666static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9667 switch (LD) {
9668 case ScalarEvolution::LoopVariant:
9669 return "Variant";
9670 case ScalarEvolution::LoopInvariant:
9671 return "Invariant";
9672 case ScalarEvolution::LoopComputable:
9673 return "Computable";
9674 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009675 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009676}
9677
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009678void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009679 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009680 // out SCEV values of all instructions that are interesting. Doing
9681 // this potentially causes it to create new SCEV objects though,
9682 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009683 // observable from outside the class though, so casting away the
9684 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009685 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009686
Dan Gohmanbc694912010-01-09 18:17:45 +00009687 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009688 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009689 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009690 for (Instruction &I : instructions(F))
9691 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9692 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009693 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009694 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009695 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009696 if (!isa<SCEVCouldNotCompute>(SV)) {
9697 OS << " U: ";
9698 SE.getUnsignedRange(SV).print(OS);
9699 OS << " S: ";
9700 SE.getSignedRange(SV).print(OS);
9701 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009702
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009703 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009704
Dan Gohmanaf752342009-07-07 17:06:11 +00009705 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009706 if (AtUse != SV) {
9707 OS << " --> ";
9708 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009709 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9710 OS << " U: ";
9711 SE.getUnsignedRange(AtUse).print(OS);
9712 OS << " S: ";
9713 SE.getSignedRange(AtUse).print(OS);
9714 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009715 }
9716
9717 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009718 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009719 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009720 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009721 OS << "<<Unknown>>";
9722 } else {
9723 OS << *ExitValue;
9724 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009725
9726 bool First = true;
9727 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9728 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009729 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009730 First = false;
9731 } else {
9732 OS << ", ";
9733 }
9734
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009735 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9736 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009737 }
9738
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009739 for (auto *InnerL : depth_first(L)) {
9740 if (InnerL == L)
9741 continue;
9742 if (First) {
9743 OS << "\t\t" "LoopDispositions: { ";
9744 First = false;
9745 } else {
9746 OS << ", ";
9747 }
9748
9749 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9750 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9751 }
9752
9753 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009754 }
9755
Chris Lattnerd934c702004-04-02 20:23:17 +00009756 OS << "\n";
9757 }
9758
Dan Gohmanbc694912010-01-09 18:17:45 +00009759 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009760 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009761 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009762 for (Loop *I : LI)
9763 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009764}
Dan Gohmane20f8242009-04-21 00:47:46 +00009765
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009766ScalarEvolution::LoopDisposition
9767ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009768 auto &Values = LoopDispositions[S];
9769 for (auto &V : Values) {
9770 if (V.getPointer() == L)
9771 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009772 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009773 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009774 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009775 auto &Values2 = LoopDispositions[S];
9776 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9777 if (V.getPointer() == L) {
9778 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009779 break;
9780 }
9781 }
9782 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009783}
9784
9785ScalarEvolution::LoopDisposition
9786ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009787 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009788 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009789 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009790 case scTruncate:
9791 case scZeroExtend:
9792 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009793 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009794 case scAddRecExpr: {
9795 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9796
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009797 // If L is the addrec's loop, it's computable.
9798 if (AR->getLoop() == L)
9799 return LoopComputable;
9800
Dan Gohmanafd6db92010-11-17 21:23:15 +00009801 // Add recurrences are never invariant in the function-body (null loop).
9802 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009803 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009804
9805 // This recurrence is variant w.r.t. L if L contains AR's loop.
9806 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009807 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009808
9809 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9810 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009811 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009812
9813 // This recurrence is variant w.r.t. L if any of its operands
9814 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009815 for (auto *Op : AR->operands())
9816 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009817 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009818
9819 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009820 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009821 }
9822 case scAddExpr:
9823 case scMulExpr:
9824 case scUMaxExpr:
9825 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009826 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009827 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9828 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009829 if (D == LoopVariant)
9830 return LoopVariant;
9831 if (D == LoopComputable)
9832 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009833 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009834 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009835 }
9836 case scUDivExpr: {
9837 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009838 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9839 if (LD == LoopVariant)
9840 return LoopVariant;
9841 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9842 if (RD == LoopVariant)
9843 return LoopVariant;
9844 return (LD == LoopInvariant && RD == LoopInvariant) ?
9845 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009846 }
9847 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009848 // All non-instruction values are loop invariant. All instructions are loop
9849 // invariant if they are not contained in the specified loop.
9850 // Instructions are never considered invariant in the function body
9851 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009852 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009853 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9854 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009855 case scCouldNotCompute:
9856 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009857 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009858 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009859}
9860
9861bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9862 return getLoopDisposition(S, L) == LoopInvariant;
9863}
9864
9865bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9866 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009867}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009868
Dan Gohman8ea83d82010-11-18 00:34:22 +00009869ScalarEvolution::BlockDisposition
9870ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009871 auto &Values = BlockDispositions[S];
9872 for (auto &V : Values) {
9873 if (V.getPointer() == BB)
9874 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009875 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009876 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009877 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009878 auto &Values2 = BlockDispositions[S];
9879 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9880 if (V.getPointer() == BB) {
9881 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009882 break;
9883 }
9884 }
9885 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009886}
9887
Dan Gohman8ea83d82010-11-18 00:34:22 +00009888ScalarEvolution::BlockDisposition
9889ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009890 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009891 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009892 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009893 case scTruncate:
9894 case scZeroExtend:
9895 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009896 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009897 case scAddRecExpr: {
9898 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009899 // to test for proper dominance too, because the instruction which
9900 // produces the addrec's value is a PHI, and a PHI effectively properly
9901 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009902 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009903 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009904 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009905
9906 // Fall through into SCEVNAryExpr handling.
9907 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009908 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009909 case scAddExpr:
9910 case scMulExpr:
9911 case scUMaxExpr:
9912 case scSMaxExpr: {
9913 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009914 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009915 for (const SCEV *NAryOp : NAry->operands()) {
9916 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009917 if (D == DoesNotDominateBlock)
9918 return DoesNotDominateBlock;
9919 if (D == DominatesBlock)
9920 Proper = false;
9921 }
9922 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009923 }
9924 case scUDivExpr: {
9925 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009926 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9927 BlockDisposition LD = getBlockDisposition(LHS, BB);
9928 if (LD == DoesNotDominateBlock)
9929 return DoesNotDominateBlock;
9930 BlockDisposition RD = getBlockDisposition(RHS, BB);
9931 if (RD == DoesNotDominateBlock)
9932 return DoesNotDominateBlock;
9933 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9934 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009935 }
9936 case scUnknown:
9937 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009938 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9939 if (I->getParent() == BB)
9940 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009941 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009942 return ProperlyDominatesBlock;
9943 return DoesNotDominateBlock;
9944 }
9945 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009946 case scCouldNotCompute:
9947 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009948 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009949 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009950}
9951
9952bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9953 return getBlockDisposition(S, BB) >= DominatesBlock;
9954}
9955
9956bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9957 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009958}
Dan Gohman534749b2010-11-17 22:27:42 +00009959
9960bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009961 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +00009962}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009963
9964void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9965 ValuesAtScopes.erase(S);
9966 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009967 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009968 UnsignedRanges.erase(S);
9969 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009970 ExprValueMap.erase(S);
9971 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009972
Silviu Baranga6f444df2016-04-08 14:29:09 +00009973 auto RemoveSCEVFromBackedgeMap =
9974 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9975 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9976 BackedgeTakenInfo &BEInfo = I->second;
9977 if (BEInfo.hasOperand(S, this)) {
9978 BEInfo.clear();
9979 Map.erase(I++);
9980 } else
9981 ++I;
9982 }
9983 };
9984
9985 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9986 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009987}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009988
9989typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009990
Alp Tokercb402912014-01-24 17:20:08 +00009991/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009992static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9993 size_t Pos = 0;
9994 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9995 Str.replace(Pos, From.size(), To.data(), To.size());
9996 Pos += To.size();
9997 }
9998}
9999
Benjamin Kramer214935e2012-10-26 17:31:32 +000010000/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10001static void
10002getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010003 std::string &S = Map[L];
10004 if (S.empty()) {
10005 raw_string_ostream OS(S);
10006 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010007
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010008 // false and 0 are semantically equivalent. This can happen in dead loops.
10009 replaceSubString(OS.str(), "false", "0");
10010 // Remove wrap flags, their use in SCEV is highly fragile.
10011 // FIXME: Remove this when SCEV gets smarter about them.
10012 replaceSubString(OS.str(), "<nw>", "");
10013 replaceSubString(OS.str(), "<nsw>", "");
10014 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010015 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010016
JF Bastien61ad8b32015-12-23 18:18:53 +000010017 for (auto *R : reverse(*L))
10018 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010019}
10020
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010021void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010022 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10023
10024 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10025 // FIXME: It would be much better to store actual values instead of strings,
10026 // but SCEV pointers will change if we drop the caches.
10027 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010028 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010029 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10030
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010031 // Gather stringified backedge taken counts for all loops using a fresh
10032 // ScalarEvolution object.
Hal Finkel3ca4a6b2016-12-15 03:02:15 +000010033 ScalarEvolution SE2(F, TLI, DT, LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010034 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10035 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010036
10037 // Now compare whether they're the same with and without caches. This allows
10038 // verifying that no pass changed the cache.
10039 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10040 "New loops suddenly appeared!");
10041
10042 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10043 OldE = BackedgeDumpsOld.end(),
10044 NewI = BackedgeDumpsNew.begin();
10045 OldI != OldE; ++OldI, ++NewI) {
10046 assert(OldI->first == NewI->first && "Loop order changed!");
10047
10048 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10049 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010050 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010051 // means that a pass is buggy or SCEV has to learn a new pattern but is
10052 // usually not harmful.
10053 if (OldI->second != NewI->second &&
10054 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010055 NewI->second.find("undef") == std::string::npos &&
10056 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010057 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010058 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010059 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010060 << "' changed from '" << OldI->second
10061 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010062 std::abort();
10063 }
10064 }
10065
10066 // TODO: Verify more things.
10067}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010068
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010069AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010070
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010071ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010072 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010073 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010074 AM.getResult<DominatorTreeAnalysis>(F),
10075 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010076}
10077
10078PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010079ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010080 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010081 return PreservedAnalyses::all();
10082}
10083
10084INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10085 "Scalar Evolution Analysis", false, true)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010086INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10087INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10088INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10089INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10090 "Scalar Evolution Analysis", false, true)
10091char ScalarEvolutionWrapperPass::ID = 0;
10092
10093ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10094 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10095}
10096
10097bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10098 SE.reset(new ScalarEvolution(
10099 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010100 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10101 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10102 return false;
10103}
10104
10105void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10106
10107void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10108 SE->print(OS);
10109}
10110
10111void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10112 if (!VerifySCEV)
10113 return;
10114
10115 SE->verify();
10116}
10117
10118void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10119 AU.setPreservesAll();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010120 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10121 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10122 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10123}
Silviu Barangae3c05342015-11-02 14:41:02 +000010124
10125const SCEVPredicate *
10126ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10127 const SCEVConstant *RHS) {
10128 FoldingSetNodeID ID;
10129 // Unique this node based on the arguments
10130 ID.AddInteger(SCEVPredicate::P_Equal);
10131 ID.AddPointer(LHS);
10132 ID.AddPointer(RHS);
10133 void *IP = nullptr;
10134 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10135 return S;
10136 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10137 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10138 UniquePreds.InsertNode(Eq, IP);
10139 return Eq;
10140}
10141
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010142const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10143 const SCEVAddRecExpr *AR,
10144 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10145 FoldingSetNodeID ID;
10146 // Unique this node based on the arguments
10147 ID.AddInteger(SCEVPredicate::P_Wrap);
10148 ID.AddPointer(AR);
10149 ID.AddInteger(AddedFlags);
10150 void *IP = nullptr;
10151 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10152 return S;
10153 auto *OF = new (SCEVAllocator)
10154 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10155 UniquePreds.InsertNode(OF, IP);
10156 return OF;
10157}
10158
Benjamin Kramer83709b12015-11-16 09:01:28 +000010159namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010160
Silviu Barangae3c05342015-11-02 14:41:02 +000010161class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10162public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010163 /// Rewrites \p S in the context of a loop L and the SCEV predication
10164 /// infrastructure.
10165 ///
10166 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10167 /// equivalences present in \p Pred.
10168 ///
10169 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10170 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010171 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010172 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10173 SCEVUnionPredicate *Pred) {
10174 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010175 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010176 }
10177
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010178 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010179 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10180 SCEVUnionPredicate *Pred)
10181 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010182
10183 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010184 if (Pred) {
10185 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10186 for (auto *Pred : ExprPreds)
10187 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10188 if (IPred->getLHS() == Expr)
10189 return IPred->getRHS();
10190 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010191
10192 return Expr;
10193 }
10194
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010195 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10196 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010197 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010198 if (AR && AR->getLoop() == L && AR->isAffine()) {
10199 // This couldn't be folded because the operand didn't have the nuw
10200 // flag. Add the nusw flag as an assumption that we could make.
10201 const SCEV *Step = AR->getStepRecurrence(SE);
10202 Type *Ty = Expr->getType();
10203 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10204 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10205 SE.getSignExtendExpr(Step, Ty), L,
10206 AR->getNoWrapFlags());
10207 }
10208 return SE.getZeroExtendExpr(Operand, Expr->getType());
10209 }
10210
10211 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10212 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010213 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010214 if (AR && AR->getLoop() == L && AR->isAffine()) {
10215 // This couldn't be folded because the operand didn't have the nsw
10216 // flag. Add the nssw flag as an assumption that we could make.
10217 const SCEV *Step = AR->getStepRecurrence(SE);
10218 Type *Ty = Expr->getType();
10219 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10220 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10221 SE.getSignExtendExpr(Step, Ty), L,
10222 AR->getNoWrapFlags());
10223 }
10224 return SE.getSignExtendExpr(Operand, Expr->getType());
10225 }
10226
Silviu Barangae3c05342015-11-02 14:41:02 +000010227private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010228 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10229 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10230 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010231 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010232 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010233 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010234 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010235 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010236 return true;
10237 }
10238
Sanjoy Dasf0022122016-09-28 17:14:58 +000010239 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10240 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010241 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010242};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010243} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010244
Sanjoy Das807d33d2016-02-20 01:44:10 +000010245const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010246 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010247 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010248}
10249
Sanjoy Dasf0022122016-09-28 17:14:58 +000010250const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10251 const SCEV *S, const Loop *L,
10252 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10253
10254 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10255 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010256 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10257
10258 if (!AddRec)
10259 return nullptr;
10260
10261 // Since the transformation was successful, we can now transfer the SCEV
10262 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010263 for (auto *P : TransformPreds)
10264 Preds.insert(P);
10265
Silviu Barangad68ed852016-03-23 15:29:30 +000010266 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010267}
10268
10269/// SCEV predicates
10270SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10271 SCEVPredicateKind Kind)
10272 : FastID(ID), Kind(Kind) {}
10273
10274SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10275 const SCEVUnknown *LHS,
10276 const SCEVConstant *RHS)
10277 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10278
10279bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010280 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010281
10282 if (!Op)
10283 return false;
10284
10285 return Op->LHS == LHS && Op->RHS == RHS;
10286}
10287
10288bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10289
10290const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10291
10292void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10293 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10294}
10295
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010296SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10297 const SCEVAddRecExpr *AR,
10298 IncrementWrapFlags Flags)
10299 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10300
10301const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10302
10303bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10304 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10305
10306 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10307}
10308
10309bool SCEVWrapPredicate::isAlwaysTrue() const {
10310 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10311 IncrementWrapFlags IFlags = Flags;
10312
10313 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10314 IFlags = clearFlags(IFlags, IncrementNSSW);
10315
10316 return IFlags == IncrementAnyWrap;
10317}
10318
10319void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10320 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10321 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10322 OS << "<nusw>";
10323 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10324 OS << "<nssw>";
10325 OS << "\n";
10326}
10327
10328SCEVWrapPredicate::IncrementWrapFlags
10329SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10330 ScalarEvolution &SE) {
10331 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10332 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10333
10334 // We can safely transfer the NSW flag as NSSW.
10335 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10336 ImpliedFlags = IncrementNSSW;
10337
10338 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10339 // If the increment is positive, the SCEV NUW flag will also imply the
10340 // WrapPredicate NUSW flag.
10341 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10342 if (Step->getValue()->getValue().isNonNegative())
10343 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10344 }
10345
10346 return ImpliedFlags;
10347}
10348
Silviu Barangae3c05342015-11-02 14:41:02 +000010349/// Union predicates don't get cached so create a dummy set ID for it.
10350SCEVUnionPredicate::SCEVUnionPredicate()
10351 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10352
10353bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010354 return all_of(Preds,
10355 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010356}
10357
10358ArrayRef<const SCEVPredicate *>
10359SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10360 auto I = SCEVToPreds.find(Expr);
10361 if (I == SCEVToPreds.end())
10362 return ArrayRef<const SCEVPredicate *>();
10363 return I->second;
10364}
10365
10366bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010367 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010368 return all_of(Set->Preds,
10369 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010370
10371 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10372 if (ScevPredsIt == SCEVToPreds.end())
10373 return false;
10374 auto &SCEVPreds = ScevPredsIt->second;
10375
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010376 return any_of(SCEVPreds,
10377 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010378}
10379
10380const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10381
10382void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10383 for (auto Pred : Preds)
10384 Pred->print(OS, Depth);
10385}
10386
10387void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010388 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010389 for (auto Pred : Set->Preds)
10390 add(Pred);
10391 return;
10392 }
10393
10394 if (implies(N))
10395 return;
10396
10397 const SCEV *Key = N->getExpr();
10398 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10399 " associated expression!");
10400
10401 SCEVToPreds[Key].push_back(N);
10402 Preds.push_back(N);
10403}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010404
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010405PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10406 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010407 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010408
10409const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10410 const SCEV *Expr = SE.getSCEV(V);
10411 RewriteEntry &Entry = RewriteMap[Expr];
10412
10413 // If we already have an entry and the version matches, return it.
10414 if (Entry.second && Generation == Entry.first)
10415 return Entry.second;
10416
10417 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010418 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010419 if (Entry.second)
10420 Expr = Entry.second;
10421
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010422 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010423 Entry = {Generation, NewSCEV};
10424
10425 return NewSCEV;
10426}
10427
Silviu Baranga6f444df2016-04-08 14:29:09 +000010428const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10429 if (!BackedgeCount) {
10430 SCEVUnionPredicate BackedgePred;
10431 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10432 addPredicate(BackedgePred);
10433 }
10434 return BackedgeCount;
10435}
10436
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010437void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10438 if (Preds.implies(&Pred))
10439 return;
10440 Preds.add(&Pred);
10441 updateGeneration();
10442}
10443
10444const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10445 return Preds;
10446}
10447
10448void PredicatedScalarEvolution::updateGeneration() {
10449 // If the generation number wrapped recompute everything.
10450 if (++Generation == 0) {
10451 for (auto &II : RewriteMap) {
10452 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010453 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010454 }
10455 }
10456}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010457
10458void PredicatedScalarEvolution::setNoOverflow(
10459 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10460 const SCEV *Expr = getSCEV(V);
10461 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10462
10463 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10464
10465 // Clear the statically implied flags.
10466 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10467 addPredicate(*SE.getWrapPredicate(AR, Flags));
10468
10469 auto II = FlagsMap.insert({V, Flags});
10470 if (!II.second)
10471 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10472}
10473
10474bool PredicatedScalarEvolution::hasNoOverflow(
10475 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10476 const SCEV *Expr = getSCEV(V);
10477 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10478
10479 Flags = SCEVWrapPredicate::clearFlags(
10480 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10481
10482 auto II = FlagsMap.find(V);
10483
10484 if (II != FlagsMap.end())
10485 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10486
10487 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10488}
10489
Silviu Barangad68ed852016-03-23 15:29:30 +000010490const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010491 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010492 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10493 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010494
10495 if (!New)
10496 return nullptr;
10497
Sanjoy Dasf0022122016-09-28 17:14:58 +000010498 for (auto *P : NewPreds)
10499 Preds.add(P);
10500
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010501 updateGeneration();
10502 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10503 return New;
10504}
10505
Silviu Baranga6f444df2016-04-08 14:29:09 +000010506PredicatedScalarEvolution::PredicatedScalarEvolution(
10507 const PredicatedScalarEvolution &Init)
10508 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10509 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010510 for (const auto &I : Init.FlagsMap)
10511 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010512}
Silviu Barangab77365b2016-04-14 16:08:45 +000010513
10514void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10515 // For each block.
10516 for (auto *BB : L.getBlocks())
10517 for (auto &I : *BB) {
10518 if (!SE.isSCEVable(I.getType()))
10519 continue;
10520
10521 auto *Expr = SE.getSCEV(&I);
10522 auto II = RewriteMap.find(Expr);
10523
10524 if (II == RewriteMap.end())
10525 continue;
10526
10527 // Don't print things that are not interesting.
10528 if (II->second.second == Expr)
10529 continue;
10530
10531 OS.indent(Depth) << "[PSE]" << I << ":\n";
10532 OS.indent(Depth + 2) << *Expr << "\n";
10533 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10534 }
10535}