blob: cd82a317355e34e4ee6eb1d701685af1551f8bb7 [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"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000066#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000068#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000071#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000073#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000074#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000077#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000078#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000079#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000081#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000082#include "llvm/IR/Instructions.h"
83#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000084#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000085#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000086#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000087#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000088#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000089#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000090#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000091#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000092#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000093#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000094using namespace llvm;
95
Chandler Carruthf1221bd2014-04-22 02:48:03 +000096#define DEBUG_TYPE "scalar-evolution"
97
Chris Lattner57ef9422006-12-19 22:30:33 +000098STATISTIC(NumArrayLenItCounts,
99 "Number of trip counts computed with array length");
100STATISTIC(NumTripCountsComputed,
101 "Number of loops with predictable loop counts");
102STATISTIC(NumTripCountsNotComputed,
103 "Number of loops without predictable loop counts");
104STATISTIC(NumBruteForceTripCountsComputed,
105 "Number of loops with trip counts computed by force");
106
Dan Gohmand78c4002008-05-13 00:00:25 +0000107static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000108MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
109 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000110 "symbolically execute a constant "
111 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000112 cl::init(100));
113
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000114// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Benjamin Kramer214935e2012-10-26 17:31:32 +0000115static cl::opt<bool>
116VerifySCEV("verify-scev",
117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000118static cl::opt<bool>
119 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000120 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000121 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000122
Chris Lattnerd934c702004-04-02 20:23:17 +0000123//===----------------------------------------------------------------------===//
124// SCEV class definitions
125//===----------------------------------------------------------------------===//
126
127//===----------------------------------------------------------------------===//
128// Implementation of the SCEV class.
129//
Dan Gohman3423e722009-06-30 20:13:32 +0000130
Davide Italiano2071f4c2015-10-25 19:55:24 +0000131LLVM_DUMP_METHOD
132void SCEV::dump() const {
133 print(dbgs());
134 dbgs() << '\n';
135}
136
Dan Gohman534749b2010-11-17 22:27:42 +0000137void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000138 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000139 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000141 return;
142 case scTruncate: {
143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
144 const SCEV *Op = Trunc->getOperand();
145 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
146 << *Trunc->getType() << ")";
147 return;
148 }
149 case scZeroExtend: {
150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
151 const SCEV *Op = ZExt->getOperand();
152 OS << "(zext " << *Op->getType() << " " << *Op << " to "
153 << *ZExt->getType() << ")";
154 return;
155 }
156 case scSignExtend: {
157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
158 const SCEV *Op = SExt->getOperand();
159 OS << "(sext " << *Op->getType() << " " << *Op << " to "
160 << *SExt->getType() << ")";
161 return;
162 }
163 case scAddRecExpr: {
164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
165 OS << "{" << *AR->getOperand(0);
166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
167 OS << ",+," << *AR->getOperand(i);
168 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000169 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000170 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000171 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000172 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000173 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
175 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000177 OS << ">";
178 return;
179 }
180 case scAddExpr:
181 case scMulExpr:
182 case scUMaxExpr:
183 case scSMaxExpr: {
184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000185 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000186 switch (NAry->getSCEVType()) {
187 case scAddExpr: OpStr = " + "; break;
188 case scMulExpr: OpStr = " * "; break;
189 case scUMaxExpr: OpStr = " umax "; break;
190 case scSMaxExpr: OpStr = " smax "; break;
191 }
192 OS << "(";
193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
194 I != E; ++I) {
195 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000196 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000197 OS << OpStr;
198 }
199 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000200 switch (NAry->getSCEVType()) {
201 case scAddExpr:
202 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000203 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000204 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000205 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000206 OS << "<nsw>";
207 }
Dan Gohman534749b2010-11-17 22:27:42 +0000208 return;
209 }
210 case scUDivExpr: {
211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
213 return;
214 }
215 case scUnknown: {
216 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000217 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000218 if (U->isSizeOf(AllocTy)) {
219 OS << "sizeof(" << *AllocTy << ")";
220 return;
221 }
222 if (U->isAlignOf(AllocTy)) {
223 OS << "alignof(" << *AllocTy << ")";
224 return;
225 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000228 Constant *FieldNo;
229 if (U->isOffsetOf(CTy, FieldNo)) {
230 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000231 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000232 OS << ")";
233 return;
234 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000235
Dan Gohman534749b2010-11-17 22:27:42 +0000236 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000237 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000238 return;
239 }
240 case scCouldNotCompute:
241 OS << "***COULDNOTCOMPUTE***";
242 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000243 }
244 llvm_unreachable("Unknown SCEV kind!");
245}
246
Chris Lattner229907c2011-07-18 04:54:35 +0000247Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000248 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000249 case scConstant:
250 return cast<SCEVConstant>(this)->getType();
251 case scTruncate:
252 case scZeroExtend:
253 case scSignExtend:
254 return cast<SCEVCastExpr>(this)->getType();
255 case scAddRecExpr:
256 case scMulExpr:
257 case scUMaxExpr:
258 case scSMaxExpr:
259 return cast<SCEVNAryExpr>(this)->getType();
260 case scAddExpr:
261 return cast<SCEVAddExpr>(this)->getType();
262 case scUDivExpr:
263 return cast<SCEVUDivExpr>(this)->getType();
264 case scUnknown:
265 return cast<SCEVUnknown>(this)->getType();
266 case scCouldNotCompute:
267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000268 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000269 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000270}
271
Dan Gohmanbe928e32008-06-18 16:23:07 +0000272bool SCEV::isZero() const {
273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
274 return SC->getValue()->isZero();
275 return false;
276}
277
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000278bool SCEV::isOne() const {
279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280 return SC->getValue()->isOne();
281 return false;
282}
Chris Lattnerd934c702004-04-02 20:23:17 +0000283
Dan Gohman18a96bb2009-06-24 00:30:26 +0000284bool SCEV::isAllOnesValue() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isAllOnesValue();
287 return false;
288}
289
Andrew Trick881a7762012-01-07 00:27:31 +0000290/// isNonConstantNegative - Return true if the specified scev is negated, but
291/// not a constant.
292bool SCEV::isNonConstantNegative() const {
293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
294 if (!Mul) return false;
295
296 // If there is a constant factor, it will be first.
297 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
298 if (!SC) return false;
299
300 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000301 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000302}
303
Owen Anderson04052ec2009-06-22 21:57:23 +0000304SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000305 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000306
Chris Lattnerd934c702004-04-02 20:23:17 +0000307bool SCEVCouldNotCompute::classof(const SCEV *S) {
308 return S->getSCEVType() == scCouldNotCompute;
309}
310
Dan Gohmanaf752342009-07-07 17:06:11 +0000311const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000312 FoldingSetNodeID ID;
313 ID.AddInteger(scConstant);
314 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000315 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000317 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000318 UniqueSCEVs.InsertNode(S, IP);
319 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Nick Lewycky31eaca52014-01-27 10:04:03 +0000322const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000323 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000324}
325
Dan Gohmanaf752342009-07-07 17:06:11 +0000326const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000327ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
328 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000329 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000330}
331
Dan Gohman24ceda82010-06-18 19:54:20 +0000332SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000333 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000334 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000335
Dan Gohman24ceda82010-06-18 19:54:20 +0000336SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000337 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000338 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000339 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
340 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000341 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000342}
Chris Lattnerd934c702004-04-02 20:23:17 +0000343
Dan Gohman24ceda82010-06-18 19:54:20 +0000344SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000345 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000346 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
348 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350}
351
Dan Gohman24ceda82010-06-18 19:54:20 +0000352SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000353 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000354 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000355 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
356 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000357 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000358}
359
Dan Gohman7cac9572010-08-02 23:49:30 +0000360void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000361 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000362 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000363
364 // Remove this SCEVUnknown from the uniquing map.
365 SE->UniqueSCEVs.RemoveNode(this);
366
367 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000368 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000369}
370
371void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000372 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000373 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374
375 // Remove this SCEVUnknown from the uniquing map.
376 SE->UniqueSCEVs.RemoveNode(this);
377
378 // Update this SCEVUnknown to point to the new value. This is needed
379 // because there may still be outstanding SCEVs which still point to
380 // this SCEVUnknown.
381 setValPtr(New);
382}
383
Chris Lattner229907c2011-07-18 04:54:35 +0000384bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000386 if (VCE->getOpcode() == Instruction::PtrToInt)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000388 if (CE->getOpcode() == Instruction::GetElementPtr &&
389 CE->getOperand(0)->isNullValue() &&
390 CE->getNumOperands() == 2)
391 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
392 if (CI->isOne()) {
393 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
394 ->getElementType();
395 return true;
396 }
Dan Gohmancf913832010-01-28 02:15:55 +0000397
398 return false;
399}
400
Chris Lattner229907c2011-07-18 04:54:35 +0000401bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000402 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000403 if (VCE->getOpcode() == Instruction::PtrToInt)
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000405 if (CE->getOpcode() == Instruction::GetElementPtr &&
406 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000409 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (!STy->isPacked() &&
411 CE->getNumOperands() == 3 &&
412 CE->getOperand(1)->isNullValue()) {
413 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
414 if (CI->isOne() &&
415 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000416 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000417 AllocTy = STy->getElementType(1);
418 return true;
419 }
420 }
421 }
Dan Gohmancf913832010-01-28 02:15:55 +0000422
423 return false;
424}
425
Chris Lattner229907c2011-07-18 04:54:35 +0000426bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000428 if (VCE->getOpcode() == Instruction::PtrToInt)
429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
430 if (CE->getOpcode() == Instruction::GetElementPtr &&
431 CE->getNumOperands() == 3 &&
432 CE->getOperand(0)->isNullValue() &&
433 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000434 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000435 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
436 // Ignore vector types here so that ScalarEvolutionExpander doesn't
437 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000438 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000439 CTy = Ty;
440 FieldNo = CE->getOperand(2);
441 return true;
442 }
443 }
444
445 return false;
446}
447
Chris Lattnereb3e8402004-06-20 06:23:15 +0000448//===----------------------------------------------------------------------===//
449// SCEV Utilities
450//===----------------------------------------------------------------------===//
451
452namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000453/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454/// than the complexity of the RHS. This comparator is used to canonicalize
455/// expressions.
456class SCEVComplexityCompare {
457 const LoopInfo *const LI;
458public:
459 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000460
Sanjoy Das7881abd2015-12-08 04:32:51 +0000461 // Return true or false if LHS is less than, or at least RHS, respectively.
462 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
463 return compare(LHS, RHS) < 0;
464 }
Dan Gohman27065672010-08-27 15:26:01 +0000465
Sanjoy Das7881abd2015-12-08 04:32:51 +0000466 // Return negative, zero, or positive, if LHS is less than, equal to, or
467 // greater than RHS, respectively. A three-way result allows recursive
468 // comparisons to be more efficient.
469 int compare(const SCEV *LHS, const SCEV *RHS) const {
470 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
471 if (LHS == RHS)
472 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000473
Sanjoy Das7881abd2015-12-08 04:32:51 +0000474 // Primarily, sort the SCEVs by their getSCEVType().
475 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
476 if (LType != RType)
477 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000478
Sanjoy Das7881abd2015-12-08 04:32:51 +0000479 // Aside from the getSCEVType() ordering, the particular ordering
480 // isn't very important except that it's beneficial to be consistent,
481 // so that (a + b) and (b + a) don't end up as different expressions.
482 switch (static_cast<SCEVTypes>(LType)) {
483 case scUnknown: {
484 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
485 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000486
Sanjoy Das7881abd2015-12-08 04:32:51 +0000487 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
488 // not as complete as it could be.
489 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000490
Sanjoy Das7881abd2015-12-08 04:32:51 +0000491 // Order pointer values after integer values. This helps SCEVExpander
492 // form GEPs.
493 bool LIsPointer = LV->getType()->isPointerTy(),
494 RIsPointer = RV->getType()->isPointerTy();
495 if (LIsPointer != RIsPointer)
496 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000497
Sanjoy Das7881abd2015-12-08 04:32:51 +0000498 // Compare getValueID values.
499 unsigned LID = LV->getValueID(),
500 RID = RV->getValueID();
501 if (LID != RID)
502 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000503
Sanjoy Das7881abd2015-12-08 04:32:51 +0000504 // Sort arguments by their position.
505 if (const Argument *LA = dyn_cast<Argument>(LV)) {
506 const Argument *RA = cast<Argument>(RV);
507 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
508 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000509 }
510
Sanjoy Das7881abd2015-12-08 04:32:51 +0000511 // For instructions, compare their loop depth, and their operand
512 // count. This is pretty loose.
513 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
514 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000515
Sanjoy Das7881abd2015-12-08 04:32:51 +0000516 // Compare loop depths.
517 const BasicBlock *LParent = LInst->getParent(),
518 *RParent = RInst->getParent();
519 if (LParent != RParent) {
520 unsigned LDepth = LI->getLoopDepth(LParent),
521 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000523 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000524 }
Dan Gohman27065672010-08-27 15:26:01 +0000525
Sanjoy Das7881abd2015-12-08 04:32:51 +0000526 // Compare the number of operands.
527 unsigned LNumOps = LInst->getNumOperands(),
528 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000529 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000530 }
531
Sanjoy Das7881abd2015-12-08 04:32:51 +0000532 return 0;
533 }
Dan Gohman27065672010-08-27 15:26:01 +0000534
Sanjoy Das7881abd2015-12-08 04:32:51 +0000535 case scConstant: {
536 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
537 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
538
539 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000540 const APInt &LA = LC->getAPInt();
541 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000542 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
543 if (LBitWidth != RBitWidth)
544 return (int)LBitWidth - (int)RBitWidth;
545 return LA.ult(RA) ? -1 : 1;
546 }
547
548 case scAddRecExpr: {
549 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
550 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
551
552 // Compare addrec loop depths.
553 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
554 if (LLoop != RLoop) {
555 unsigned LDepth = LLoop->getLoopDepth(),
556 RDepth = RLoop->getLoopDepth();
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Addrec complexity grows with operand count.
562 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
563 if (LNumOps != RNumOps)
564 return (int)LNumOps - (int)RNumOps;
565
566 // Lexicographically compare.
567 for (unsigned i = 0; i != LNumOps; ++i) {
568 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000569 if (X != 0)
570 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000571 }
572
Sanjoy Das7881abd2015-12-08 04:32:51 +0000573 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000574 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000575
576 case scAddExpr:
577 case scMulExpr:
578 case scSMaxExpr:
579 case scUMaxExpr: {
580 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
581 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
582
583 // Lexicographically compare n-ary expressions.
584 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
585 if (LNumOps != RNumOps)
586 return (int)LNumOps - (int)RNumOps;
587
588 for (unsigned i = 0; i != LNumOps; ++i) {
589 if (i >= RNumOps)
590 return 1;
591 long X = compare(LC->getOperand(i), RC->getOperand(i));
592 if (X != 0)
593 return X;
594 }
595 return (int)LNumOps - (int)RNumOps;
596 }
597
598 case scUDivExpr: {
599 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601
602 // Lexicographically compare udiv expressions.
603 long X = compare(LC->getLHS(), RC->getLHS());
604 if (X != 0)
605 return X;
606 return compare(LC->getRHS(), RC->getRHS());
607 }
608
609 case scTruncate:
610 case scZeroExtend:
611 case scSignExtend: {
612 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
613 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
614
615 // Compare cast expressions by operand.
616 return compare(LC->getOperand(), RC->getOperand());
617 }
618
619 case scCouldNotCompute:
620 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
621 }
622 llvm_unreachable("Unknown SCEV kind!");
623 }
624};
625} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000626
627/// GroupByComplexity - Given a list of SCEV objects, order them by their
628/// complexity, and group objects of the same complexity together by value.
629/// When this routine is finished, we know that any duplicates in the vector are
630/// consecutive and that complexity is monotonically increasing.
631///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000632/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000633/// results from this routine. In other words, we don't want the results of
634/// this to depend on where the addresses of various SCEV objects happened to
635/// land in memory.
636///
Dan Gohmanaf752342009-07-07 17:06:11 +0000637static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000638 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000639 if (Ops.size() < 2) return; // Noop
640 if (Ops.size() == 2) {
641 // This is the common case, which also happens to be trivially simple.
642 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000643 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
644 if (SCEVComplexityCompare(LI)(RHS, LHS))
645 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000646 return;
647 }
648
Dan Gohman24ceda82010-06-18 19:54:20 +0000649 // Do the rough sort by complexity.
650 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
651
652 // Now that we are sorted by complexity, group elements of the same
653 // complexity. Note that this is, at worst, N^2, but the vector is likely to
654 // be extremely short in practice. Note that we take this approach because we
655 // do not want to depend on the addresses of the objects we are grouping.
656 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
657 const SCEV *S = Ops[i];
658 unsigned Complexity = S->getSCEVType();
659
660 // If there are any objects of the same complexity and same value as this
661 // one, group them.
662 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
663 if (Ops[j] == S) { // Found a duplicate.
664 // Move it to immediately after i'th element.
665 std::swap(Ops[i+1], Ops[j]);
666 ++i; // no need to rescan it.
667 if (i == e-2) return; // Done!
668 }
669 }
670 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000671}
672
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000673// Returns the size of the SCEV S.
674static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000675 struct FindSCEVSize {
676 int Size;
677 FindSCEVSize() : Size(0) {}
678
679 bool follow(const SCEV *S) {
680 ++Size;
681 // Keep looking at all operands of S.
682 return true;
683 }
684 bool isDone() const {
685 return false;
686 }
687 };
688
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000689 FindSCEVSize F;
690 SCEVTraversal<FindSCEVSize> ST(F);
691 ST.visitAll(S);
692 return F.Size;
693}
694
695namespace {
696
David Majnemer4e879362014-12-14 09:12:33 +0000697struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000698public:
699 // Computes the Quotient and Remainder of the division of Numerator by
700 // Denominator.
701 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
702 const SCEV *Denominator, const SCEV **Quotient,
703 const SCEV **Remainder) {
704 assert(Numerator && Denominator && "Uninitialized SCEV");
705
David Majnemer4e879362014-12-14 09:12:33 +0000706 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000707
708 // Check for the trivial case here to avoid having to check for it in the
709 // rest of the code.
710 if (Numerator == Denominator) {
711 *Quotient = D.One;
712 *Remainder = D.Zero;
713 return;
714 }
715
716 if (Numerator->isZero()) {
717 *Quotient = D.Zero;
718 *Remainder = D.Zero;
719 return;
720 }
721
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000722 // A simple case when N/1. The quotient is N.
723 if (Denominator->isOne()) {
724 *Quotient = Numerator;
725 *Remainder = D.Zero;
726 return;
727 }
728
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000729 // Split the Denominator when it is a product.
730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
731 const SCEV *Q, *R;
732 *Quotient = Numerator;
733 for (const SCEV *Op : T->operands()) {
734 divide(SE, *Quotient, Op, &Q, &R);
735 *Quotient = Q;
736
737 // Bail out when the Numerator is not divisible by one of the terms of
738 // the Denominator.
739 if (!R->isZero()) {
740 *Quotient = D.Zero;
741 *Remainder = Numerator;
742 return;
743 }
744 }
745 *Remainder = D.Zero;
746 return;
747 }
748
749 D.visit(Numerator);
750 *Quotient = D.Quotient;
751 *Remainder = D.Remainder;
752 }
753
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000754 // Except in the trivial case described above, we do not know how to divide
755 // Expr by Denominator for the following functions with empty implementation.
756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762 void visitUnknown(const SCEVUnknown *Numerator) {}
763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
764
David Majnemer4e879362014-12-14 09:12:33 +0000765 void visitConstant(const SCEVConstant *Numerator) {
766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000767 APInt NumeratorVal = Numerator->getAPInt();
768 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000769 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
771
772 if (NumeratorBW > DenominatorBW)
773 DenominatorVal = DenominatorVal.sext(NumeratorBW);
774 else if (NumeratorBW < DenominatorBW)
775 NumeratorVal = NumeratorVal.sext(DenominatorBW);
776
777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780 Quotient = SE.getConstant(QuotientVal);
781 Remainder = SE.getConstant(RemainderVal);
782 return;
783 }
784 }
785
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000788 if (!Numerator->isAffine())
789 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000790 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
791 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000792 // Bail out if the types do not match.
793 Type *Ty = Denominator->getType();
794 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000795 Ty != StepQ->getType() || Ty != StepR->getType())
796 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
800 Numerator->getNoWrapFlags());
801 }
802
803 void visitAddExpr(const SCEVAddExpr *Numerator) {
804 SmallVector<const SCEV *, 2> Qs, Rs;
805 Type *Ty = Denominator->getType();
806
807 for (const SCEV *Op : Numerator->operands()) {
808 const SCEV *Q, *R;
809 divide(SE, Op, Denominator, &Q, &R);
810
811 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000812 if (Ty != Q->getType() || Ty != R->getType())
813 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000814
815 Qs.push_back(Q);
816 Rs.push_back(R);
817 }
818
819 if (Qs.size() == 1) {
820 Quotient = Qs[0];
821 Remainder = Rs[0];
822 return;
823 }
824
825 Quotient = SE.getAddExpr(Qs);
826 Remainder = SE.getAddExpr(Rs);
827 }
828
829 void visitMulExpr(const SCEVMulExpr *Numerator) {
830 SmallVector<const SCEV *, 2> Qs;
831 Type *Ty = Denominator->getType();
832
833 bool FoundDenominatorTerm = false;
834 for (const SCEV *Op : Numerator->operands()) {
835 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000836 if (Ty != Op->getType())
837 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000838
839 if (FoundDenominatorTerm) {
840 Qs.push_back(Op);
841 continue;
842 }
843
844 // Check whether Denominator divides one of the product operands.
845 const SCEV *Q, *R;
846 divide(SE, Op, Denominator, &Q, &R);
847 if (!R->isZero()) {
848 Qs.push_back(Op);
849 continue;
850 }
851
852 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000853 if (Ty != Q->getType())
854 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000855
856 FoundDenominatorTerm = true;
857 Qs.push_back(Q);
858 }
859
860 if (FoundDenominatorTerm) {
861 Remainder = Zero;
862 if (Qs.size() == 1)
863 Quotient = Qs[0];
864 else
865 Quotient = SE.getMulExpr(Qs);
866 return;
867 }
868
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000869 if (!isa<SCEVUnknown>(Denominator))
870 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000871
872 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
873 ValueToValueMap RewriteMap;
874 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
875 cast<SCEVConstant>(Zero)->getValue();
876 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
877
878 if (Remainder->isZero()) {
879 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(One)->getValue();
882 Quotient =
883 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884 return;
885 }
886
887 // Quotient is (Numerator - Remainder) divided by Denominator.
888 const SCEV *Q, *R;
889 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 // This SCEV does not seem to simplify: fail the division here.
891 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
892 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000893 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000894 if (R != Zero)
895 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000896 Quotient = Q;
897 }
898
899private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000900 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
901 const SCEV *Denominator)
902 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000903 Zero = SE.getZero(Denominator->getType());
904 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000905
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000906 // We generally do not know how to divide Expr by Denominator. We
907 // initialize the division to a "cannot divide" state to simplify the rest
908 // of the code.
909 cannotDivide(Numerator);
910 }
911
912 // Convenience function for giving up on the division. We set the quotient to
913 // be equal to zero and the remainder to be equal to the numerator.
914 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000915 Quotient = Zero;
916 Remainder = Numerator;
917 }
918
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000919 ScalarEvolution &SE;
920 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000921};
922
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000923}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000924
Chris Lattnerd934c702004-04-02 20:23:17 +0000925//===----------------------------------------------------------------------===//
926// Simple SCEV method implementations
927//===----------------------------------------------------------------------===//
928
Eli Friedman61f67622008-08-04 23:49:06 +0000929/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000930/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000931static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000932 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000933 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000934 // Handle the simplest case efficiently.
935 if (K == 1)
936 return SE.getTruncateOrZeroExtend(It, ResultTy);
937
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000938 // We are using the following formula for BC(It, K):
939 //
940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
941 //
Eli Friedman61f67622008-08-04 23:49:06 +0000942 // Suppose, W is the bitwidth of the return value. We must be prepared for
943 // overflow. Hence, we must assure that the result of our computation is
944 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
945 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000946 //
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000948 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
950 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000953 //
Eli Friedman61f67622008-08-04 23:49:06 +0000954 // This formula is trivially equivalent to the previous formula. However,
955 // this formula can be implemented much more efficiently. The trick is that
956 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
957 // arithmetic. To do exact division in modular arithmetic, all we have
958 // to do is multiply by the inverse. Therefore, this step can be done at
959 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000960 //
Eli Friedman61f67622008-08-04 23:49:06 +0000961 // The next issue is how to safely do the division by 2^T. The way this
962 // is done is by doing the multiplication step at a width of at least W + T
963 // bits. This way, the bottom W+T bits of the product are accurate. Then,
964 // when we perform the division by 2^T (which is equivalent to a right shift
965 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
966 // truncated out after the division by 2^T.
967 //
968 // In comparison to just directly using the first formula, this technique
969 // is much more efficient; using the first formula requires W * K bits,
970 // but this formula less than W + K bits. Also, the first formula requires
971 // a division step, whereas this formula only requires multiplies and shifts.
972 //
973 // It doesn't matter whether the subtraction step is done in the calculation
974 // width or the input iteration count's width; if the subtraction overflows,
975 // the result must be zero anyway. We prefer here to do it in the width of
976 // the induction variable because it helps a lot for certain cases; CodeGen
977 // isn't smart enough to ignore the overflow, which leads to much less
978 // efficient code if the width of the subtraction is wider than the native
979 // register width.
980 //
981 // (It's possible to not widen at all by pulling out factors of 2 before
982 // the multiplication; for example, K=2 can be calculated as
983 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
984 // extra arithmetic, so it's not an obvious win, and it gets
985 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000986
Eli Friedman61f67622008-08-04 23:49:06 +0000987 // Protection from insane SCEVs; this bound is conservative,
988 // but it probably doesn't matter.
989 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000990 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000992 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000993
Eli Friedman61f67622008-08-04 23:49:06 +0000994 // Calculate K! / 2^T and T; we divide out the factors of two before
995 // multiplying for calculating K! / 2^T to avoid overflow.
996 // Other overflow doesn't matter because we only care about the bottom
997 // W bits of the result.
998 APInt OddFactorial(W, 1);
999 unsigned T = 1;
1000 for (unsigned i = 3; i <= K; ++i) {
1001 APInt Mult(W, i);
1002 unsigned TwoFactors = Mult.countTrailingZeros();
1003 T += TwoFactors;
1004 Mult = Mult.lshr(TwoFactors);
1005 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001006 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001007
Eli Friedman61f67622008-08-04 23:49:06 +00001008 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001009 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001010
Dan Gohman8b0a4192010-03-01 17:49:51 +00001011 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001012 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001013
1014 // Calculate the multiplicative inverse of K! / 2^T;
1015 // this multiplication factor will perform the exact division by
1016 // K! / 2^T.
1017 APInt Mod = APInt::getSignedMinValue(W+1);
1018 APInt MultiplyFactor = OddFactorial.zext(W+1);
1019 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1020 MultiplyFactor = MultiplyFactor.trunc(W);
1021
1022 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001023 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001024 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001025 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001026 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001027 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001028 Dividend = SE.getMulExpr(Dividend,
1029 SE.getTruncateOrZeroExtend(S, CalculationTy));
1030 }
1031
1032 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001033 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001034
1035 // Truncate the result, and divide by K! / 2^T.
1036
1037 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1038 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001039}
1040
Chris Lattnerd934c702004-04-02 20:23:17 +00001041/// evaluateAtIteration - Return the value of this chain of recurrences at
1042/// the specified iteration number. We can evaluate this recurrence by
1043/// multiplying each element in the chain by the binomial coefficient
1044/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001048/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001049///
Dan Gohmanaf752342009-07-07 17:06:11 +00001050const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001051 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001052 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001053 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001054 // The computation is correct in the face of overflow provided that the
1055 // multiplication is performed _after_ the evaluation of the binomial
1056 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001058 if (isa<SCEVCouldNotCompute>(Coeff))
1059 return Coeff;
1060
1061 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001062 }
1063 return Result;
1064}
1065
Chris Lattnerd934c702004-04-02 20:23:17 +00001066//===----------------------------------------------------------------------===//
1067// SCEV Expression folder implementations
1068//===----------------------------------------------------------------------===//
1069
Dan Gohmanaf752342009-07-07 17:06:11 +00001070const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001072 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001073 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001074 assert(isSCEVable(Ty) &&
1075 "This is not a conversion to a SCEVable type!");
1076 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001077
Dan Gohman3a302cb2009-07-13 20:50:19 +00001078 FoldingSetNodeID ID;
1079 ID.AddInteger(scTruncate);
1080 ID.AddPointer(Op);
1081 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001082 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1084
Dan Gohman3423e722009-06-30 20:13:32 +00001085 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001087 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001088 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001089
Dan Gohman79af8542009-04-22 16:20:48 +00001090 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001091 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001092 return getTruncateExpr(ST->getOperand(), Ty);
1093
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001095 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001096 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1097
1098 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001099 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001100 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1101
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001103 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001104 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1105 SmallVector<const SCEV *, 4> Operands;
1106 bool hasTrunc = false;
1107 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1108 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001109 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1110 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001111 Operands.push_back(S);
1112 }
1113 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001114 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001115 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001116 }
1117
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001119 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001120 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1121 SmallVector<const SCEV *, 4> Operands;
1122 bool hasTrunc = false;
1123 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1124 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001125 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001132 }
1133
Dan Gohman5a728c92009-06-18 16:24:47 +00001134 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001136 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001137 for (const SCEV *Op : AddRec->operands())
1138 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001140 }
1141
Dan Gohman89dd42a2010-06-25 18:47:08 +00001142 // The cast wasn't folded; create an explicit cast node. We can reuse
1143 // the existing insert position since if we get here, we won't have
1144 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1146 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001147 UniqueSCEVs.InsertNode(S, IP);
1148 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001149}
1150
Sanjoy Das4153f472015-02-18 01:47:07 +00001151// Get the limit of a recurrence such that incrementing by Step cannot cause
1152// signed overflow as long as the value of the recurrence within the
1153// loop does not exceed this limit before incrementing.
1154static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155 ICmpInst::Predicate *Pred,
1156 ScalarEvolution *SE) {
1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158 if (SE->isKnownPositive(Step)) {
1159 *Pred = ICmpInst::ICMP_SLT;
1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161 SE->getSignedRange(Step).getSignedMax());
1162 }
1163 if (SE->isKnownNegative(Step)) {
1164 *Pred = ICmpInst::ICMP_SGT;
1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166 SE->getSignedRange(Step).getSignedMin());
1167 }
1168 return nullptr;
1169}
1170
1171// Get the limit of a recurrence such that incrementing by Step cannot cause
1172// unsigned overflow as long as the value of the recurrence within the loop does
1173// not exceed this limit before incrementing.
1174static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175 ICmpInst::Predicate *Pred,
1176 ScalarEvolution *SE) {
1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178 *Pred = ICmpInst::ICMP_ULT;
1179
1180 return SE->getConstant(APInt::getMinValue(BitWidth) -
1181 SE->getUnsignedRange(Step).getUnsignedMax());
1182}
1183
1184namespace {
1185
1186struct ExtendOpTraitsBase {
1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1188};
1189
1190// Used to make code generic over signed and unsigned overflow.
1191template <typename ExtendOp> struct ExtendOpTraits {
1192 // Members present:
1193 //
1194 // static const SCEV::NoWrapFlags WrapType;
1195 //
1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1197 //
1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199 // ICmpInst::Predicate *Pred,
1200 // ScalarEvolution *SE);
1201};
1202
1203template <>
1204struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1206
1207 static const GetExtendExprTy GetExtendExpr;
1208
1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 return getSignedOverflowLimitForStep(Step, Pred, SE);
1213 }
1214};
1215
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001216const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1218
1219template <>
1220struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1222
1223 static const GetExtendExprTy GetExtendExpr;
1224
1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226 ICmpInst::Predicate *Pred,
1227 ScalarEvolution *SE) {
1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1229 }
1230};
1231
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001232const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001234}
Sanjoy Das4153f472015-02-18 01:47:07 +00001235
1236// The recurrence AR has been shown to have no signed/unsigned wrap or something
1237// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241// expression "Step + sext/zext(PreIncAR)" is congruent with
1242// "sext/zext(PostIncAR)"
1243template <typename ExtendOpTy>
1244static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245 ScalarEvolution *SE) {
1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1248
1249 const Loop *L = AR->getLoop();
1250 const SCEV *Start = AR->getStart();
1251 const SCEV *Step = AR->getStepRecurrence(*SE);
1252
1253 // Check for a simple looking step prior to loop entry.
1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1255 if (!SA)
1256 return nullptr;
1257
1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259 // subtraction is expensive. For this purpose, perform a quick and dirty
1260 // difference, by checking for Step in the operand list.
1261 SmallVector<const SCEV *, 4> DiffOps;
1262 for (const SCEV *Op : SA->operands())
1263 if (Op != Step)
1264 DiffOps.push_back(Op);
1265
1266 if (DiffOps.size() == SA->getNumOperands())
1267 return nullptr;
1268
1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1270 // `Step`:
1271
1272 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001273 auto PreStartFlags =
1274 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1275 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001276 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1277 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1278
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001279 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1280 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001281 //
1282
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001283 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1284 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1285 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001286 return PreStart;
1287
1288 // 2. Direct overflow check on the step operation's expression.
1289 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1290 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1291 const SCEV *OperandExtendedStart =
1292 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1293 (SE->*GetExtendExpr)(Step, WideTy));
1294 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1295 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1296 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1297 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1298 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1299 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1300 }
1301 return PreStart;
1302 }
1303
1304 // 3. Loop precondition.
1305 ICmpInst::Predicate Pred;
1306 const SCEV *OverflowLimit =
1307 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1308
1309 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001312
Sanjoy Das4153f472015-02-18 01:47:07 +00001313 return nullptr;
1314}
1315
1316// Get the normalized zero or sign extended expression for this AddRec's Start.
1317template <typename ExtendOpTy>
1318static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1319 ScalarEvolution *SE) {
1320 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1321
1322 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1323 if (!PreStart)
1324 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1325
1326 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1327 (SE->*GetExtendExpr)(PreStart, Ty));
1328}
1329
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001330// Try to prove away overflow by looking at "nearby" add recurrences. A
1331// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1332// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1333//
1334// Formally:
1335//
1336// {S,+,X} == {S-T,+,X} + T
1337// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1338//
1339// If ({S-T,+,X} + T) does not overflow ... (1)
1340//
1341// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1342//
1343// If {S-T,+,X} does not overflow ... (2)
1344//
1345// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1346// == {Ext(S-T)+Ext(T),+,Ext(X)}
1347//
1348// If (S-T)+T does not overflow ... (3)
1349//
1350// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1351// == {Ext(S),+,Ext(X)} == LHS
1352//
1353// Thus, if (1), (2) and (3) are true for some T, then
1354// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1355//
1356// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1357// does not overflow" restricted to the 0th iteration. Therefore we only need
1358// to check for (1) and (2).
1359//
1360// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1361// is `Delta` (defined below).
1362//
1363template <typename ExtendOpTy>
1364bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1365 const SCEV *Step,
1366 const Loop *L) {
1367 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368
1369 // We restrict `Start` to a constant to prevent SCEV from spending too much
1370 // time here. It is correct (but more expensive) to continue with a
1371 // non-constant `Start` and do a general SCEV subtraction to compute
1372 // `PreStart` below.
1373 //
1374 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1375 if (!StartC)
1376 return false;
1377
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001378 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001379
1380 for (unsigned Delta : {-2, -1, 1, 2}) {
1381 const SCEV *PreStart = getConstant(StartAI - Delta);
1382
Sanjoy Das42801102015-10-23 06:57:21 +00001383 FoldingSetNodeID ID;
1384 ID.AddInteger(scAddRecExpr);
1385 ID.AddPointer(PreStart);
1386 ID.AddPointer(Step);
1387 ID.AddPointer(L);
1388 void *IP = nullptr;
1389 const auto *PreAR =
1390 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1391
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 // Give up if we don't already have the add recurrence we need because
1393 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001394 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1395 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1396 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1397 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1398 DeltaS, &Pred, this);
1399 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1400 return true;
1401 }
1402 }
1403
1404 return false;
1405}
1406
Dan Gohmanaf752342009-07-07 17:06:11 +00001407const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001408 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001409 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001410 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001411 assert(isSCEVable(Ty) &&
1412 "This is not a conversion to a SCEVable type!");
1413 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001414
Dan Gohman3423e722009-06-30 20:13:32 +00001415 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1417 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001418 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001419
Dan Gohman79af8542009-04-22 16:20:48 +00001420 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001421 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001422 return getZeroExtendExpr(SZ->getOperand(), Ty);
1423
Dan Gohman74a0ba12009-07-13 20:55:53 +00001424 // Before doing any expensive analysis, check to see if we've already
1425 // computed a SCEV for this Op and Ty.
1426 FoldingSetNodeID ID;
1427 ID.AddInteger(scZeroExtend);
1428 ID.AddPointer(Op);
1429 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001430 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1432
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001433 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1434 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1435 // It's possible the bits taken off by the truncate were all zero bits. If
1436 // so, we should be able to simplify this further.
1437 const SCEV *X = ST->getOperand();
1438 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001439 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1440 unsigned NewBits = getTypeSizeInBits(Ty);
1441 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001442 CR.zextOrTrunc(NewBits)))
1443 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001444 }
1445
Dan Gohman76466372009-04-27 20:16:15 +00001446 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001447 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001448 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001449 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001450 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001451 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001452 const SCEV *Start = AR->getStart();
1453 const SCEV *Step = AR->getStepRecurrence(*this);
1454 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1455 const Loop *L = AR->getLoop();
1456
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001457 if (!AR->hasNoUnsignedWrap()) {
1458 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1459 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1460 }
1461
Dan Gohman62ef6a72009-07-25 01:22:26 +00001462 // If we have special knowledge that this addrec won't overflow,
1463 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001464 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001465 return getAddRecExpr(
1466 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1467 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001468
Dan Gohman76466372009-04-27 20:16:15 +00001469 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1470 // Note that this serves two purposes: It filters out loops that are
1471 // simply not analyzable, and it covers the case where this code is
1472 // being called from within backedge-taken count analysis, such that
1473 // attempting to ask for the backedge-taken count would likely result
1474 // in infinite recursion. In the later case, the analysis code will
1475 // cope with a conservative value, and it will take care to purge
1476 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001477 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001478 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001479 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001480 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001481
1482 // Check whether the backedge-taken count can be losslessly casted to
1483 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001484 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001485 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001486 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001487 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1488 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001489 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001490 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001491 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001492 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1493 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1494 const SCEV *WideMaxBECount =
1495 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001496 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001497 getAddExpr(WideStart,
1498 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001499 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001500 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001501 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1502 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001503 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001504 return getAddRecExpr(
1505 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1506 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001507 }
Dan Gohman76466372009-04-27 20:16:15 +00001508 // Similar to above, only this time treat the step value as signed.
1509 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001510 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001511 getAddExpr(WideStart,
1512 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001513 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001514 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001515 // Cache knowledge of AR NW, which is propagated to this AddRec.
1516 // Negative step causes unsigned wrap, but it still can't self-wrap.
1517 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001518 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001519 return getAddRecExpr(
1520 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1521 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001522 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001523 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001524 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001525
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001526 // Normally, in the cases we can prove no-overflow via a
1527 // backedge guarding condition, we can also compute a backedge
1528 // taken count for the loop. The exceptions are assumptions and
1529 // guards present in the loop -- SCEV is not great at exploiting
1530 // these to compute max backedge taken counts, but can still use
1531 // these to prove lack of overflow. Use this fact to avoid
1532 // doing extra work that may not pay off.
1533 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1534 !AC.assumptions().empty()) {
1535 // If the backedge is guarded by a comparison with the pre-inc
1536 // value the addrec is safe. Also, if the entry is guarded by
1537 // a comparison with the start value and the backedge is
1538 // guarded by a comparison with the post-inc value, the addrec
1539 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001540 if (isKnownPositive(Step)) {
1541 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1542 getUnsignedRange(Step).getUnsignedMax());
1543 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001544 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001545 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001546 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001547 // Cache knowledge of AR NUW, which is propagated to this
1548 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001549 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001550 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001551 return getAddRecExpr(
1552 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1553 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001554 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001555 } else if (isKnownNegative(Step)) {
1556 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1557 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001558 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1559 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001560 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001561 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001562 // Cache knowledge of AR NW, which is propagated to this
1563 // AddRec. Negative step causes unsigned wrap, but it
1564 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001565 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1566 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001567 return getAddRecExpr(
1568 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1569 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001570 }
Dan Gohman76466372009-04-27 20:16:15 +00001571 }
1572 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001573
1574 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1575 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1576 return getAddRecExpr(
1577 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1578 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1579 }
Dan Gohman76466372009-04-27 20:16:15 +00001580 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001581
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001582 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1583 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001584 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001585 // If the addition does not unsign overflow then we can, by definition,
1586 // commute the zero extension with the addition operation.
1587 SmallVector<const SCEV *, 4> Ops;
1588 for (const auto *Op : SA->operands())
1589 Ops.push_back(getZeroExtendExpr(Op, Ty));
1590 return getAddExpr(Ops, SCEV::FlagNUW);
1591 }
1592 }
1593
Dan Gohman74a0ba12009-07-13 20:55:53 +00001594 // The cast wasn't folded; create an explicit cast node.
1595 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001597 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1598 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001599 UniqueSCEVs.InsertNode(S, IP);
1600 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001601}
1602
Dan Gohmanaf752342009-07-07 17:06:11 +00001603const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001604 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001605 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001606 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001607 assert(isSCEVable(Ty) &&
1608 "This is not a conversion to a SCEVable type!");
1609 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001610
Dan Gohman3423e722009-06-30 20:13:32 +00001611 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001612 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1613 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001614 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001615
Dan Gohman79af8542009-04-22 16:20:48 +00001616 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001617 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001618 return getSignExtendExpr(SS->getOperand(), Ty);
1619
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001620 // sext(zext(x)) --> zext(x)
1621 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1622 return getZeroExtendExpr(SZ->getOperand(), Ty);
1623
Dan Gohman74a0ba12009-07-13 20:55:53 +00001624 // Before doing any expensive analysis, check to see if we've already
1625 // computed a SCEV for this Op and Ty.
1626 FoldingSetNodeID ID;
1627 ID.AddInteger(scSignExtend);
1628 ID.AddPointer(Op);
1629 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001630 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001631 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1632
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001633 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1634 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1635 // It's possible the bits taken off by the truncate were all sign bits. If
1636 // so, we should be able to simplify this further.
1637 const SCEV *X = ST->getOperand();
1638 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001639 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1640 unsigned NewBits = getTypeSizeInBits(Ty);
1641 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001642 CR.sextOrTrunc(NewBits)))
1643 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001644 }
1645
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001646 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001647 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001648 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001649 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1650 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001651 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001652 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001653 const APInt &C1 = SC1->getAPInt();
1654 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001655 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001656 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001657 return getAddExpr(getSignExtendExpr(SC1, Ty),
1658 getSignExtendExpr(SMul, Ty));
1659 }
1660 }
1661 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001662
1663 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001664 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001665 // If the addition does not sign overflow then we can, by definition,
1666 // commute the sign extension with the addition operation.
1667 SmallVector<const SCEV *, 4> Ops;
1668 for (const auto *Op : SA->operands())
1669 Ops.push_back(getSignExtendExpr(Op, Ty));
1670 return getAddExpr(Ops, SCEV::FlagNSW);
1671 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001672 }
Dan Gohman76466372009-04-27 20:16:15 +00001673 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001674 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001675 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001676 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001677 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001678 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001679 const SCEV *Start = AR->getStart();
1680 const SCEV *Step = AR->getStepRecurrence(*this);
1681 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1682 const Loop *L = AR->getLoop();
1683
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001684 if (!AR->hasNoSignedWrap()) {
1685 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1686 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1687 }
1688
Dan Gohman62ef6a72009-07-25 01:22:26 +00001689 // If we have special knowledge that this addrec won't overflow,
1690 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001691 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001692 return getAddRecExpr(
1693 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1694 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001695
Dan Gohman76466372009-04-27 20:16:15 +00001696 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1697 // Note that this serves two purposes: It filters out loops that are
1698 // simply not analyzable, and it covers the case where this code is
1699 // being called from within backedge-taken count analysis, such that
1700 // attempting to ask for the backedge-taken count would likely result
1701 // in infinite recursion. In the later case, the analysis code will
1702 // cope with a conservative value, and it will take care to purge
1703 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001704 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001705 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001706 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001707 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001708
1709 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001710 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001711 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001712 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001713 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001714 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1715 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001716 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001717 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001718 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001719 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1720 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1721 const SCEV *WideMaxBECount =
1722 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001723 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001724 getAddExpr(WideStart,
1725 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001726 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001727 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001728 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1729 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001730 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001731 return getAddRecExpr(
1732 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1733 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001734 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001735 // Similar to above, only this time treat the step value as unsigned.
1736 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001737 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001738 getAddExpr(WideStart,
1739 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001740 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001741 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001742 // If AR wraps around then
1743 //
1744 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1745 // => SAdd != OperandExtendedAdd
1746 //
1747 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1748 // (SAdd == OperandExtendedAdd => AR is NW)
1749
1750 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1751
Dan Gohman8c129d72009-07-16 17:34:36 +00001752 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001753 return getAddRecExpr(
1754 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1755 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001756 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001757 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001758 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001759
Sanjoy Das787c2462016-05-11 17:41:26 +00001760 // Normally, in the cases we can prove no-overflow via a
1761 // backedge guarding condition, we can also compute a backedge
1762 // taken count for the loop. The exceptions are assumptions and
1763 // guards present in the loop -- SCEV is not great at exploiting
1764 // these to compute max backedge taken counts, but can still use
1765 // these to prove lack of overflow. Use this fact to avoid
1766 // doing extra work that may not pay off.
1767
1768 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1769 !AC.assumptions().empty()) {
1770 // If the backedge is guarded by a comparison with the pre-inc
1771 // value the addrec is safe. Also, if the entry is guarded by
1772 // a comparison with the start value and the backedge is
1773 // guarded by a comparison with the post-inc value, the addrec
1774 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001775 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001776 const SCEV *OverflowLimit =
1777 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001778 if (OverflowLimit &&
1779 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1780 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1781 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1782 OverflowLimit)))) {
1783 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1784 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001785 return getAddRecExpr(
1786 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1787 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001788 }
1789 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001790
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001791 // If Start and Step are constants, check if we can apply this
1792 // transformation:
1793 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001794 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1795 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001796 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001797 const APInt &C1 = SC1->getAPInt();
1798 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001799 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1800 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001801 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001802 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1803 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001804 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1805 }
1806 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001807
1808 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1809 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1810 return getAddRecExpr(
1811 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1812 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1813 }
Dan Gohman76466372009-04-27 20:16:15 +00001814 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001815
Sanjoy Das11ef6062016-03-03 18:31:23 +00001816 // If the input value is provably positive and we could not simplify
1817 // away the sext build a zext instead.
1818 if (isKnownNonNegative(Op))
1819 return getZeroExtendExpr(Op, Ty);
1820
Dan Gohman74a0ba12009-07-13 20:55:53 +00001821 // The cast wasn't folded; create an explicit cast node.
1822 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001823 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001824 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1825 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001826 UniqueSCEVs.InsertNode(S, IP);
1827 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001828}
1829
Dan Gohman8db2edc2009-06-13 15:56:47 +00001830/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1831/// unspecified bits out to the given type.
1832///
Dan Gohmanaf752342009-07-07 17:06:11 +00001833const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001834 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001835 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1836 "This is not an extending conversion!");
1837 assert(isSCEVable(Ty) &&
1838 "This is not a conversion to a SCEVable type!");
1839 Ty = getEffectiveSCEVType(Ty);
1840
1841 // Sign-extend negative constants.
1842 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001843 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001844 return getSignExtendExpr(Op, Ty);
1845
1846 // Peel off a truncate cast.
1847 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001848 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001849 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1850 return getAnyExtendExpr(NewOp, Ty);
1851 return getTruncateOrNoop(NewOp, Ty);
1852 }
1853
1854 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001855 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001856 if (!isa<SCEVZeroExtendExpr>(ZExt))
1857 return ZExt;
1858
1859 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001860 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001861 if (!isa<SCEVSignExtendExpr>(SExt))
1862 return SExt;
1863
Dan Gohman51ad99d2010-01-21 02:09:26 +00001864 // Force the cast to be folded into the operands of an addrec.
1865 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1866 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001867 for (const SCEV *Op : AR->operands())
1868 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001869 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001870 }
1871
Dan Gohman8db2edc2009-06-13 15:56:47 +00001872 // If the expression is obviously signed, use the sext cast value.
1873 if (isa<SCEVSMaxExpr>(Op))
1874 return SExt;
1875
1876 // Absent any other information, use the zext cast value.
1877 return ZExt;
1878}
1879
Dan Gohman038d02e2009-06-14 22:58:51 +00001880/// CollectAddOperandsWithScales - Process the given Ops list, which is
1881/// a list of operands to be added under the given scale, update the given
1882/// map. This is a helper function for getAddRecExpr. As an example of
1883/// what it does, given a sequence of operands that would form an add
1884/// expression like this:
1885///
Tobias Grosserba49e422014-03-05 10:37:17 +00001886/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001887///
1888/// where A and B are constants, update the map with these values:
1889///
1890/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1891///
1892/// and add 13 + A*B*29 to AccumulatedConstant.
1893/// This will allow getAddRecExpr to produce this:
1894///
1895/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1896///
1897/// This form often exposes folding opportunities that are hidden in
1898/// the original operand list.
1899///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001900/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001901/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1902/// the common case where no interesting opportunities are present, and
1903/// is also used as a check to avoid infinite recursion.
1904///
1905static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001906CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001907 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001908 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001909 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001910 const APInt &Scale,
1911 ScalarEvolution &SE) {
1912 bool Interesting = false;
1913
Dan Gohman45073042010-06-18 19:12:32 +00001914 // Iterate over the add operands. They are sorted, with constants first.
1915 unsigned i = 0;
1916 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1917 ++i;
1918 // Pull a buried constant out to the outside.
1919 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1920 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001921 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001922 }
1923
1924 // Next comes everything else. We're especially interested in multiplies
1925 // here, but they're in the middle, so just visit the rest with one loop.
1926 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001927 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1928 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1929 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001930 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001931 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1932 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001933 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001934 Interesting |=
1935 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001936 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001937 NewScale, SE);
1938 } else {
1939 // A multiplication of a constant with some other value. Update
1940 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001941 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1942 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001943 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001944 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001945 NewOps.push_back(Pair.first->first);
1946 } else {
1947 Pair.first->second += NewScale;
1948 // The map already had an entry for this value, which may indicate
1949 // a folding opportunity.
1950 Interesting = true;
1951 }
1952 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001953 } else {
1954 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001955 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001956 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001957 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001958 NewOps.push_back(Pair.first->first);
1959 } else {
1960 Pair.first->second += Scale;
1961 // The map already had an entry for this value, which may indicate
1962 // a folding opportunity.
1963 Interesting = true;
1964 }
1965 }
1966 }
1967
1968 return Interesting;
1969}
1970
Sanjoy Das81401d42015-01-10 23:41:24 +00001971// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1972// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1973// can't-overflow flags for the operation if possible.
1974static SCEV::NoWrapFlags
1975StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1976 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001977 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001978 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001979 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001980
1981 bool CanAnalyze =
1982 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1983 (void)CanAnalyze;
1984 assert(CanAnalyze && "don't call from other places!");
1985
1986 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1987 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001988 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001989
1990 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001991 auto IsKnownNonNegative = [&](const SCEV *S) {
1992 return SE->isKnownNonNegative(S);
1993 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001994
Sanjoy Das3b827c72015-11-29 23:40:53 +00001995 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001996 Flags =
1997 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001998
Sanjoy Das8f274152015-10-22 19:57:19 +00001999 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2000
2001 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2002 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2003
2004 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2005 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2006
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002007 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002008 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002009 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2010 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002011 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2012 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2013 }
2014 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002015 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2016 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002017 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2018 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2019 }
2020 }
2021
2022 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002023}
2024
Dan Gohman4d5435d2009-05-24 23:45:28 +00002025/// getAddExpr - Get a canonical add expression, or something simpler if
2026/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002027const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002028 SCEV::NoWrapFlags Flags) {
2029 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2030 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002031 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002032 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002033#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002034 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002035 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002036 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002037 "SCEVAddExpr operand types don't match!");
2038#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002039
2040 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002041 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002042
Sanjoy Das64895612015-10-09 02:44:45 +00002043 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2044
Chris Lattnerd934c702004-04-02 20:23:17 +00002045 // If there are any constants, fold them together.
2046 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002047 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002048 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002049 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002050 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002051 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002052 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002053 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002054 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002055 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002056 }
2057
2058 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002059 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002060 Ops.erase(Ops.begin());
2061 --Idx;
2062 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002063
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002064 if (Ops.size() == 1) return Ops[0];
2065 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002066
Dan Gohman15871f22010-08-27 21:39:59 +00002067 // Okay, check to see if the same value occurs in the operand list more than
2068 // once. If so, merge them together into an multiply expression. Since we
2069 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002070 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002071 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002072 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002073 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002074 // Scan ahead to count how many equal operands there are.
2075 unsigned Count = 2;
2076 while (i+Count != e && Ops[i+Count] == Ops[i])
2077 ++Count;
2078 // Merge the values into a multiply.
2079 const SCEV *Scale = getConstant(Ty, Count);
2080 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2081 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002082 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002083 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002084 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002085 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002086 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002087 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002088 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002089 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002090
Dan Gohman2e55cc52009-05-08 21:03:19 +00002091 // Check for truncates. If all the operands are truncated from the same
2092 // type, see if factoring out the truncate would permit the result to be
2093 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2094 // if the contents of the resulting outer trunc fold to something simple.
2095 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2096 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002097 Type *DstType = Trunc->getType();
2098 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002099 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002100 bool Ok = true;
2101 // Check all the operands to see if they can be represented in the
2102 // source type of the truncate.
2103 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2104 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2105 if (T->getOperand()->getType() != SrcType) {
2106 Ok = false;
2107 break;
2108 }
2109 LargeOps.push_back(T->getOperand());
2110 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002111 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002112 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002113 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002114 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2115 if (const SCEVTruncateExpr *T =
2116 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2117 if (T->getOperand()->getType() != SrcType) {
2118 Ok = false;
2119 break;
2120 }
2121 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002122 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002123 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002124 } else {
2125 Ok = false;
2126 break;
2127 }
2128 }
2129 if (Ok)
2130 LargeOps.push_back(getMulExpr(LargeMulOps));
2131 } else {
2132 Ok = false;
2133 break;
2134 }
2135 }
2136 if (Ok) {
2137 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002138 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002139 // If it folds to something simple, use it. Otherwise, don't.
2140 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2141 return getTruncateExpr(Fold, DstType);
2142 }
2143 }
2144
2145 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002146 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2147 ++Idx;
2148
2149 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002150 if (Idx < Ops.size()) {
2151 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002152 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002153 // If we have an add, expand the add operands onto the end of the operands
2154 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002155 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002156 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002157 DeletedAdd = true;
2158 }
2159
2160 // If we deleted at least one add, we added operands to the end of the list,
2161 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002162 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002163 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002164 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002165 }
2166
2167 // Skip over the add expression until we get to a multiply.
2168 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2169 ++Idx;
2170
Dan Gohman038d02e2009-06-14 22:58:51 +00002171 // Check to see if there are any folding opportunities present with
2172 // operands multiplied by constant values.
2173 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2174 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002175 DenseMap<const SCEV *, APInt> M;
2176 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002177 APInt AccumulatedConstant(BitWidth, 0);
2178 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002179 Ops.data(), Ops.size(),
2180 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002181 struct APIntCompare {
2182 bool operator()(const APInt &LHS, const APInt &RHS) const {
2183 return LHS.ult(RHS);
2184 }
2185 };
2186
Dan Gohman038d02e2009-06-14 22:58:51 +00002187 // Some interesting folding opportunity is present, so its worthwhile to
2188 // re-generate the operands list. Group the operands by constant scale,
2189 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002190 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002191 for (const SCEV *NewOp : NewOps)
2192 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002193 // Re-generate the operands list.
2194 Ops.clear();
2195 if (AccumulatedConstant != 0)
2196 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002197 for (auto &MulOp : MulOpLists)
2198 if (MulOp.first != 0)
2199 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2200 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002201 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002202 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002203 if (Ops.size() == 1)
2204 return Ops[0];
2205 return getAddExpr(Ops);
2206 }
2207 }
2208
Chris Lattnerd934c702004-04-02 20:23:17 +00002209 // If we are adding something to a multiply expression, make sure the
2210 // something is not already an operand of the multiply. If so, merge it into
2211 // the multiply.
2212 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002213 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002214 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002215 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002216 if (isa<SCEVConstant>(MulOpSCEV))
2217 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002218 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002219 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002220 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002221 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002222 if (Mul->getNumOperands() != 2) {
2223 // If the multiply has more than two operands, we must get the
2224 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002225 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2226 Mul->op_begin()+MulOp);
2227 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002228 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002229 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002230 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002231 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002232 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002233 if (Ops.size() == 2) return OuterMul;
2234 if (AddOp < Idx) {
2235 Ops.erase(Ops.begin()+AddOp);
2236 Ops.erase(Ops.begin()+Idx-1);
2237 } else {
2238 Ops.erase(Ops.begin()+Idx);
2239 Ops.erase(Ops.begin()+AddOp-1);
2240 }
2241 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002242 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002243 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002244
Chris Lattnerd934c702004-04-02 20:23:17 +00002245 // Check this multiply against other multiplies being added together.
2246 for (unsigned OtherMulIdx = Idx+1;
2247 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2248 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002249 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002250 // If MulOp occurs in OtherMul, we can fold the two multiplies
2251 // together.
2252 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2253 OMulOp != e; ++OMulOp)
2254 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2255 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002256 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002257 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002258 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002259 Mul->op_begin()+MulOp);
2260 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002261 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002262 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002263 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002264 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002265 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002266 OtherMul->op_begin()+OMulOp);
2267 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002268 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002269 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002270 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2271 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002272 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002273 Ops.erase(Ops.begin()+Idx);
2274 Ops.erase(Ops.begin()+OtherMulIdx-1);
2275 Ops.push_back(OuterMul);
2276 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002277 }
2278 }
2279 }
2280 }
2281
2282 // If there are any add recurrences in the operands list, see if any other
2283 // added values are loop invariant. If so, we can fold them into the
2284 // recurrence.
2285 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2286 ++Idx;
2287
2288 // Scan over all recurrences, trying to fold loop invariants into them.
2289 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2290 // Scan all of the other operands to this add and add them to the vector if
2291 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002292 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002293 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002294 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002296 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002297 LIOps.push_back(Ops[i]);
2298 Ops.erase(Ops.begin()+i);
2299 --i; --e;
2300 }
2301
2302 // If we found some loop invariants, fold them into the recurrence.
2303 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002304 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002305 LIOps.push_back(AddRec->getStart());
2306
Dan Gohmanaf752342009-07-07 17:06:11 +00002307 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002308 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002309 // This follows from the fact that the no-wrap flags on the outer add
2310 // expression are applicable on the 0th iteration, when the add recurrence
2311 // will be equal to its start value.
2312 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002313
Dan Gohman16206132010-06-30 07:16:37 +00002314 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002315 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002316 // Always propagate NW.
2317 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002318 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002319
Chris Lattnerd934c702004-04-02 20:23:17 +00002320 // If all of the other operands were loop invariant, we are done.
2321 if (Ops.size() == 1) return NewRec;
2322
Nick Lewyckydb66b822011-09-06 05:08:09 +00002323 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002324 for (unsigned i = 0;; ++i)
2325 if (Ops[i] == AddRec) {
2326 Ops[i] = NewRec;
2327 break;
2328 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002329 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002330 }
2331
2332 // Okay, if there weren't any loop invariants to be folded, check to see if
2333 // there are multiple AddRec's with the same loop induction variable being
2334 // added together. If so, we can fold them.
2335 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002336 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2337 ++OtherIdx)
2338 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2339 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2340 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2341 AddRec->op_end());
2342 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2343 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002344 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002345 if (OtherAddRec->getLoop() == AddRecLoop) {
2346 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2347 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002348 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002349 AddRecOps.append(OtherAddRec->op_begin()+i,
2350 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002351 break;
2352 }
Dan Gohman028c1812010-08-29 14:53:34 +00002353 AddRecOps[i] = getAddExpr(AddRecOps[i],
2354 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002355 }
2356 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002357 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002358 // Step size has changed, so we cannot guarantee no self-wraparound.
2359 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002360 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002361 }
2362
2363 // Otherwise couldn't fold anything into this recurrence. Move onto the
2364 // next one.
2365 }
2366
2367 // Okay, it looks like we really DO need an add expr. Check to see if we
2368 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002369 FoldingSetNodeID ID;
2370 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002371 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2372 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002373 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002374 SCEVAddExpr *S =
2375 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2376 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002377 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2378 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002379 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2380 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002381 UniqueSCEVs.InsertNode(S, IP);
2382 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002383 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002384 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002385}
2386
Nick Lewycky287682e2011-10-04 06:51:26 +00002387static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2388 uint64_t k = i*j;
2389 if (j > 1 && k / j != i) Overflow = true;
2390 return k;
2391}
2392
2393/// Compute the result of "n choose k", the binomial coefficient. If an
2394/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002395/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002396static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2397 // We use the multiplicative formula:
2398 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2399 // At each iteration, we take the n-th term of the numeral and divide by the
2400 // (k-n)th term of the denominator. This division will always produce an
2401 // integral result, and helps reduce the chance of overflow in the
2402 // intermediate computations. However, we can still overflow even when the
2403 // final result would fit.
2404
2405 if (n == 0 || n == k) return 1;
2406 if (k > n) return 0;
2407
2408 if (k > n/2)
2409 k = n-k;
2410
2411 uint64_t r = 1;
2412 for (uint64_t i = 1; i <= k; ++i) {
2413 r = umul_ov(r, n-(i-1), Overflow);
2414 r /= i;
2415 }
2416 return r;
2417}
2418
Nick Lewycky05044c22014-12-06 00:45:50 +00002419/// Determine if any of the operands in this SCEV are a constant or if
2420/// any of the add or multiply expressions in this SCEV contain a constant.
2421static bool containsConstantSomewhere(const SCEV *StartExpr) {
2422 SmallVector<const SCEV *, 4> Ops;
2423 Ops.push_back(StartExpr);
2424 while (!Ops.empty()) {
2425 const SCEV *CurrentExpr = Ops.pop_back_val();
2426 if (isa<SCEVConstant>(*CurrentExpr))
2427 return true;
2428
2429 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2430 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002431 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002432 }
2433 }
2434 return false;
2435}
2436
Dan Gohman4d5435d2009-05-24 23:45:28 +00002437/// getMulExpr - Get a canonical multiply expression, or something simpler if
2438/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002439const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002440 SCEV::NoWrapFlags Flags) {
2441 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2442 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002443 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002444 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002445#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002446 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002447 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002448 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002449 "SCEVMulExpr operand types don't match!");
2450#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002451
2452 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002453 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002454
Sanjoy Das64895612015-10-09 02:44:45 +00002455 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2456
Chris Lattnerd934c702004-04-02 20:23:17 +00002457 // If there are any constants, fold them together.
2458 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002459 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002460
2461 // C1*(C2+V) -> C1*C2 + C1*V
2462 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002463 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2464 // If any of Add's ops are Adds or Muls with a constant,
2465 // apply this transformation as well.
2466 if (Add->getNumOperands() == 2)
2467 if (containsConstantSomewhere(Add))
2468 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2469 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002470
Chris Lattnerd934c702004-04-02 20:23:17 +00002471 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002472 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002473 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002474 ConstantInt *Fold =
2475 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002476 Ops[0] = getConstant(Fold);
2477 Ops.erase(Ops.begin()+1); // Erase the folded element
2478 if (Ops.size() == 1) return Ops[0];
2479 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002480 }
2481
2482 // If we are left with a constant one being multiplied, strip it off.
2483 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2484 Ops.erase(Ops.begin());
2485 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002486 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002487 // If we have a multiply of zero, it will always be zero.
2488 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002489 } else if (Ops[0]->isAllOnesValue()) {
2490 // If we have a mul by -1 of an add, try distributing the -1 among the
2491 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002492 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002493 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2494 SmallVector<const SCEV *, 4> NewOps;
2495 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002496 for (const SCEV *AddOp : Add->operands()) {
2497 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002498 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2499 NewOps.push_back(Mul);
2500 }
2501 if (AnyFolded)
2502 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002503 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002504 // Negation preserves a recurrence's no self-wrap property.
2505 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002506 for (const SCEV *AddRecOp : AddRec->operands())
2507 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2508
Andrew Tricke92dcce2011-03-14 17:38:54 +00002509 return getAddRecExpr(Operands, AddRec->getLoop(),
2510 AddRec->getNoWrapFlags(SCEV::FlagNW));
2511 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002512 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002513 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002514
2515 if (Ops.size() == 1)
2516 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002517 }
2518
2519 // Skip over the add expression until we get to a multiply.
2520 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2521 ++Idx;
2522
Chris Lattnerd934c702004-04-02 20:23:17 +00002523 // If there are mul operands inline them all into this expression.
2524 if (Idx < Ops.size()) {
2525 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002526 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002527 // If we have an mul, expand the mul operands onto the end of the operands
2528 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002529 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002530 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002531 DeletedMul = true;
2532 }
2533
2534 // If we deleted at least one mul, we added operands to the end of the list,
2535 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002536 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002537 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002538 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002539 }
2540
2541 // If there are any add recurrences in the operands list, see if any other
2542 // added values are loop invariant. If so, we can fold them into the
2543 // recurrence.
2544 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2545 ++Idx;
2546
2547 // Scan over all recurrences, trying to fold loop invariants into them.
2548 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2549 // Scan all of the other operands to this mul and add them to the vector if
2550 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002551 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002552 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002553 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002554 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002555 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002556 LIOps.push_back(Ops[i]);
2557 Ops.erase(Ops.begin()+i);
2558 --i; --e;
2559 }
2560
2561 // If we found some loop invariants, fold them into the recurrence.
2562 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002563 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002564 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002565 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002566 const SCEV *Scale = getMulExpr(LIOps);
2567 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2568 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002569
Dan Gohman16206132010-06-30 07:16:37 +00002570 // Build the new addrec. Propagate the NUW and NSW flags if both the
2571 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002572 //
2573 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002574 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002575 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2576 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002577
2578 // If all of the other operands were loop invariant, we are done.
2579 if (Ops.size() == 1) return NewRec;
2580
Nick Lewyckydb66b822011-09-06 05:08:09 +00002581 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002582 for (unsigned i = 0;; ++i)
2583 if (Ops[i] == AddRec) {
2584 Ops[i] = NewRec;
2585 break;
2586 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002587 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002588 }
2589
2590 // Okay, if there weren't any loop invariants to be folded, check to see if
2591 // there are multiple AddRec's with the same loop induction variable being
2592 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002593
2594 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2595 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2596 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2597 // ]]],+,...up to x=2n}.
2598 // Note that the arguments to choose() are always integers with values
2599 // known at compile time, never SCEV objects.
2600 //
2601 // The implementation avoids pointless extra computations when the two
2602 // addrec's are of different length (mathematically, it's equivalent to
2603 // an infinite stream of zeros on the right).
2604 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002605 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002606 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002607 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002608 const SCEVAddRecExpr *OtherAddRec =
2609 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2610 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002611 continue;
2612
Nick Lewycky97756402014-09-01 05:17:15 +00002613 bool Overflow = false;
2614 Type *Ty = AddRec->getType();
2615 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2616 SmallVector<const SCEV*, 7> AddRecOps;
2617 for (int x = 0, xe = AddRec->getNumOperands() +
2618 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002619 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002620 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2621 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2622 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2623 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2624 z < ze && !Overflow; ++z) {
2625 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2626 uint64_t Coeff;
2627 if (LargerThan64Bits)
2628 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2629 else
2630 Coeff = Coeff1*Coeff2;
2631 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2632 const SCEV *Term1 = AddRec->getOperand(y-z);
2633 const SCEV *Term2 = OtherAddRec->getOperand(z);
2634 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002635 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002636 }
Nick Lewycky97756402014-09-01 05:17:15 +00002637 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002638 }
Nick Lewycky97756402014-09-01 05:17:15 +00002639 if (!Overflow) {
2640 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2641 SCEV::FlagAnyWrap);
2642 if (Ops.size() == 2) return NewAddRec;
2643 Ops[Idx] = NewAddRec;
2644 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2645 OpsModified = true;
2646 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2647 if (!AddRec)
2648 break;
2649 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002650 }
Nick Lewycky97756402014-09-01 05:17:15 +00002651 if (OpsModified)
2652 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002653
2654 // Otherwise couldn't fold anything into this recurrence. Move onto the
2655 // next one.
2656 }
2657
2658 // Okay, it looks like we really DO need an mul expr. Check to see if we
2659 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002660 FoldingSetNodeID ID;
2661 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002662 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2663 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002664 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002665 SCEVMulExpr *S =
2666 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2667 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002668 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2669 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002670 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2671 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002672 UniqueSCEVs.InsertNode(S, IP);
2673 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002674 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002675 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002676}
2677
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002678/// getUDivExpr - Get a canonical unsigned division expression, or something
2679/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002680const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2681 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002682 assert(getEffectiveSCEVType(LHS->getType()) ==
2683 getEffectiveSCEVType(RHS->getType()) &&
2684 "SCEVUDivExpr operand types don't match!");
2685
Dan Gohmana30370b2009-05-04 22:02:23 +00002686 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002687 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002688 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002689 // If the denominator is zero, the result of the udiv is undefined. Don't
2690 // try to analyze it, because the resolution chosen here may differ from
2691 // the resolution chosen in other parts of the compiler.
2692 if (!RHSC->getValue()->isZero()) {
2693 // Determine if the division can be folded into the operands of
2694 // its operands.
2695 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002696 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002697 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002698 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002699 // For non-power-of-two values, effectively round the value up to the
2700 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002701 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002702 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002703 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002704 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002705 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2706 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002707 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2708 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002709 const APInt &StepInt = Step->getAPInt();
2710 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002711 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002712 getZeroExtendExpr(AR, ExtTy) ==
2713 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2714 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002715 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002716 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002717 for (const SCEV *Op : AR->operands())
2718 Operands.push_back(getUDivExpr(Op, RHS));
2719 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002720 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002721 /// Get a canonical UDivExpr for a recurrence.
2722 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2723 // We can currently only fold X%N if X is constant.
2724 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2725 if (StartC && !DivInt.urem(StepInt) &&
2726 getZeroExtendExpr(AR, ExtTy) ==
2727 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2728 getZeroExtendExpr(Step, ExtTy),
2729 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002730 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002731 const APInt &StartRem = StartInt.urem(StepInt);
2732 if (StartRem != 0)
2733 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2734 AR->getLoop(), SCEV::FlagNW);
2735 }
2736 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002737 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2738 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2739 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002740 for (const SCEV *Op : M->operands())
2741 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002742 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2743 // Find an operand that's safely divisible.
2744 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2745 const SCEV *Op = M->getOperand(i);
2746 const SCEV *Div = getUDivExpr(Op, RHSC);
2747 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2748 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2749 M->op_end());
2750 Operands[i] = Div;
2751 return getMulExpr(Operands);
2752 }
2753 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002754 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002755 // (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 +00002756 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002757 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002758 for (const SCEV *Op : A->operands())
2759 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002760 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2761 Operands.clear();
2762 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2763 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2764 if (isa<SCEVUDivExpr>(Op) ||
2765 getMulExpr(Op, RHS) != A->getOperand(i))
2766 break;
2767 Operands.push_back(Op);
2768 }
2769 if (Operands.size() == A->getNumOperands())
2770 return getAddExpr(Operands);
2771 }
2772 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002773
Dan Gohmanacd700a2010-04-22 01:35:11 +00002774 // Fold if both operands are constant.
2775 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2776 Constant *LHSCV = LHSC->getValue();
2777 Constant *RHSCV = RHSC->getValue();
2778 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2779 RHSCV)));
2780 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002781 }
2782 }
2783
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002784 FoldingSetNodeID ID;
2785 ID.AddInteger(scUDivExpr);
2786 ID.AddPointer(LHS);
2787 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002788 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002789 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002790 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2791 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002792 UniqueSCEVs.InsertNode(S, IP);
2793 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002794}
2795
Nick Lewycky31eaca52014-01-27 10:04:03 +00002796static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002797 APInt A = C1->getAPInt().abs();
2798 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002799 uint32_t ABW = A.getBitWidth();
2800 uint32_t BBW = B.getBitWidth();
2801
2802 if (ABW > BBW)
2803 B = B.zext(ABW);
2804 else if (ABW < BBW)
2805 A = A.zext(BBW);
2806
2807 return APIntOps::GreatestCommonDivisor(A, B);
2808}
2809
2810/// getUDivExactExpr - Get a canonical unsigned division expression, or
2811/// something simpler if possible. There is no representation for an exact udiv
2812/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2813/// We can't do this when it's not exact because the udiv may be clearing bits.
2814const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2815 const SCEV *RHS) {
2816 // TODO: we could try to find factors in all sorts of things, but for now we
2817 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2818 // end of this file for inspiration.
2819
2820 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2821 if (!Mul)
2822 return getUDivExpr(LHS, RHS);
2823
2824 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2825 // If the mulexpr multiplies by a constant, then that constant must be the
2826 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002827 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002828 if (LHSCst == RHSCst) {
2829 SmallVector<const SCEV *, 2> Operands;
2830 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2831 return getMulExpr(Operands);
2832 }
2833
2834 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2835 // that there's a factor provided by one of the other terms. We need to
2836 // check.
2837 APInt Factor = gcd(LHSCst, RHSCst);
2838 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002839 LHSCst =
2840 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2841 RHSCst =
2842 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002843 SmallVector<const SCEV *, 2> Operands;
2844 Operands.push_back(LHSCst);
2845 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2846 LHS = getMulExpr(Operands);
2847 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002848 Mul = dyn_cast<SCEVMulExpr>(LHS);
2849 if (!Mul)
2850 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002851 }
2852 }
2853 }
2854
2855 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2856 if (Mul->getOperand(i) == RHS) {
2857 SmallVector<const SCEV *, 2> Operands;
2858 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2859 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2860 return getMulExpr(Operands);
2861 }
2862 }
2863
2864 return getUDivExpr(LHS, RHS);
2865}
Chris Lattnerd934c702004-04-02 20:23:17 +00002866
Dan Gohman4d5435d2009-05-24 23:45:28 +00002867/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2868/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002869const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2870 const Loop *L,
2871 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002872 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002873 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002874 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002875 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002876 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002877 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002878 }
2879
2880 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002881 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002882}
2883
Dan Gohman4d5435d2009-05-24 23:45:28 +00002884/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2885/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002886const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002887ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002888 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002889 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002890#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002891 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002892 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002893 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002894 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002895 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002896 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002897 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002898#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002899
Dan Gohmanbe928e32008-06-18 16:23:07 +00002900 if (Operands.back()->isZero()) {
2901 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002902 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002903 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002904
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002905 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2906 // use that information to infer NUW and NSW flags. However, computing a
2907 // BE count requires calling getAddRecExpr, so we may not yet have a
2908 // meaningful BE count at this point (and if we don't, we'd be stuck
2909 // with a SCEVCouldNotCompute as the cached BE count).
2910
Sanjoy Das81401d42015-01-10 23:41:24 +00002911 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002912
Dan Gohman223a5d22008-08-08 18:33:12 +00002913 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002914 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002915 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002916 if (L->contains(NestedLoop)
2917 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2918 : (!NestedLoop->contains(L) &&
2919 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002920 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002921 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002922 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002923 // AddRecs require their operands be loop-invariant with respect to their
2924 // loops. Don't perform this transformation if it would break this
2925 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002926 bool AllInvariant = all_of(
2927 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002928
Dan Gohmancc030b72009-06-26 22:36:20 +00002929 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002930 // Create a recurrence for the outer loop with the same step size.
2931 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002932 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2933 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002934 SCEV::NoWrapFlags OuterFlags =
2935 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002936
2937 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002938 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2939 return isLoopInvariant(Op, NestedLoop);
2940 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002941
Andrew Trick8b55b732011-03-14 16:50:06 +00002942 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002943 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002944 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002945 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2946 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002947 SCEV::NoWrapFlags InnerFlags =
2948 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002949 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2950 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002951 }
2952 // Reset Operands to its original state.
2953 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002954 }
2955 }
2956
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002957 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2958 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002959 FoldingSetNodeID ID;
2960 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002961 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2962 ID.AddPointer(Operands[i]);
2963 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002964 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002965 SCEVAddRecExpr *S =
2966 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2967 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002968 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2969 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002970 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2971 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002972 UniqueSCEVs.InsertNode(S, IP);
2973 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002974 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002975 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002976}
2977
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002978const SCEV *
2979ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2980 const SmallVectorImpl<const SCEV *> &IndexExprs,
2981 bool InBounds) {
2982 // getSCEV(Base)->getType() has the same address space as Base->getType()
2983 // because SCEV::getType() preserves the address space.
2984 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2985 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2986 // instruction to its SCEV, because the Instruction may be guarded by control
2987 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002988 // context. This can be fixed similarly to how these flags are handled for
2989 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002990 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2991
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002992 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002993 // The address space is unimportant. The first thing we do on CurTy is getting
2994 // its element type.
2995 Type *CurTy = PointerType::getUnqual(PointeeType);
2996 for (const SCEV *IndexExpr : IndexExprs) {
2997 // Compute the (potentially symbolic) offset in bytes for this index.
2998 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2999 // For a struct, add the member offset.
3000 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3001 unsigned FieldNo = Index->getZExtValue();
3002 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3003
3004 // Add the field offset to the running total offset.
3005 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3006
3007 // Update CurTy to the type of the field at Index.
3008 CurTy = STy->getTypeAtIndex(Index);
3009 } else {
3010 // Update CurTy to its element type.
3011 CurTy = cast<SequentialType>(CurTy)->getElementType();
3012 // For an array, add the element offset, explicitly scaled.
3013 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3014 // Getelementptr indices are signed.
3015 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3016
3017 // Multiply the index by the element size to compute the element offset.
3018 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3019
3020 // Add the element offset to the running total offset.
3021 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3022 }
3023 }
3024
3025 // Add the total offset from all the GEP indices to the base.
3026 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3027}
3028
Dan Gohmanabd17092009-06-24 14:49:00 +00003029const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3030 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003031 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003032 Ops.push_back(LHS);
3033 Ops.push_back(RHS);
3034 return getSMaxExpr(Ops);
3035}
3036
Dan Gohmanaf752342009-07-07 17:06:11 +00003037const SCEV *
3038ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003039 assert(!Ops.empty() && "Cannot get empty smax!");
3040 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003041#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003042 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003043 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003044 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003045 "SCEVSMaxExpr operand types don't match!");
3046#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003047
3048 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003049 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003050
3051 // If there are any constants, fold them together.
3052 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003053 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003054 ++Idx;
3055 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003056 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003057 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003058 ConstantInt *Fold = ConstantInt::get(
3059 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003060 Ops[0] = getConstant(Fold);
3061 Ops.erase(Ops.begin()+1); // Erase the folded element
3062 if (Ops.size() == 1) return Ops[0];
3063 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003064 }
3065
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003066 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003067 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3068 Ops.erase(Ops.begin());
3069 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003070 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3071 // If we have an smax with a constant maximum-int, it will always be
3072 // maximum-int.
3073 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003074 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003075
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003076 if (Ops.size() == 1) return Ops[0];
3077 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003078
3079 // Find the first SMax
3080 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3081 ++Idx;
3082
3083 // Check to see if one of the operands is an SMax. If so, expand its operands
3084 // onto our operand list, and recurse to simplify.
3085 if (Idx < Ops.size()) {
3086 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003087 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003088 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003089 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003090 DeletedSMax = true;
3091 }
3092
3093 if (DeletedSMax)
3094 return getSMaxExpr(Ops);
3095 }
3096
3097 // Okay, check to see if the same value occurs in the operand list twice. If
3098 // so, delete one. Since we sorted the list, these values are required to
3099 // be adjacent.
3100 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003101 // X smax Y smax Y --> X smax Y
3102 // X smax Y --> X, if X is always greater than Y
3103 if (Ops[i] == Ops[i+1] ||
3104 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3105 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3106 --i; --e;
3107 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003108 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3109 --i; --e;
3110 }
3111
3112 if (Ops.size() == 1) return Ops[0];
3113
3114 assert(!Ops.empty() && "Reduced smax down to nothing!");
3115
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003116 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003117 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003118 FoldingSetNodeID ID;
3119 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003120 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3121 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003122 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003123 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003124 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3125 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003126 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3127 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003128 UniqueSCEVs.InsertNode(S, IP);
3129 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003130}
3131
Dan Gohmanabd17092009-06-24 14:49:00 +00003132const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3133 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003134 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003135 Ops.push_back(LHS);
3136 Ops.push_back(RHS);
3137 return getUMaxExpr(Ops);
3138}
3139
Dan Gohmanaf752342009-07-07 17:06:11 +00003140const SCEV *
3141ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003142 assert(!Ops.empty() && "Cannot get empty umax!");
3143 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003144#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003145 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003146 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003147 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003148 "SCEVUMaxExpr operand types don't match!");
3149#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003150
3151 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003152 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003153
3154 // If there are any constants, fold them together.
3155 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003156 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003157 ++Idx;
3158 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003159 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003160 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003161 ConstantInt *Fold = ConstantInt::get(
3162 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003163 Ops[0] = getConstant(Fold);
3164 Ops.erase(Ops.begin()+1); // Erase the folded element
3165 if (Ops.size() == 1) return Ops[0];
3166 LHSC = cast<SCEVConstant>(Ops[0]);
3167 }
3168
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003169 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003170 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3171 Ops.erase(Ops.begin());
3172 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003173 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3174 // If we have an umax with a constant maximum-int, it will always be
3175 // maximum-int.
3176 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003177 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003178
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003179 if (Ops.size() == 1) return Ops[0];
3180 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003181
3182 // Find the first UMax
3183 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3184 ++Idx;
3185
3186 // Check to see if one of the operands is a UMax. If so, expand its operands
3187 // onto our operand list, and recurse to simplify.
3188 if (Idx < Ops.size()) {
3189 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003190 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003191 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003192 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003193 DeletedUMax = true;
3194 }
3195
3196 if (DeletedUMax)
3197 return getUMaxExpr(Ops);
3198 }
3199
3200 // Okay, check to see if the same value occurs in the operand list twice. If
3201 // so, delete one. Since we sorted the list, these values are required to
3202 // be adjacent.
3203 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003204 // X umax Y umax Y --> X umax Y
3205 // X umax Y --> X, if X is always greater than Y
3206 if (Ops[i] == Ops[i+1] ||
3207 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3208 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3209 --i; --e;
3210 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003211 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3212 --i; --e;
3213 }
3214
3215 if (Ops.size() == 1) return Ops[0];
3216
3217 assert(!Ops.empty() && "Reduced umax down to nothing!");
3218
3219 // Okay, it looks like we really DO need a umax expr. Check to see if we
3220 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003221 FoldingSetNodeID ID;
3222 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003223 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3224 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003225 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003226 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003227 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3228 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003229 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3230 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003231 UniqueSCEVs.InsertNode(S, IP);
3232 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003233}
3234
Dan Gohmanabd17092009-06-24 14:49:00 +00003235const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3236 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003237 // ~smax(~x, ~y) == smin(x, y).
3238 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3239}
3240
Dan Gohmanabd17092009-06-24 14:49:00 +00003241const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3242 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003243 // ~umax(~x, ~y) == umin(x, y)
3244 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3245}
3246
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003247const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003248 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003249 // constant expression and then folding it back into a ConstantInt.
3250 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003251 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003252}
3253
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003254const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3255 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003256 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003257 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003258 // constant expression and then folding it back into a ConstantInt.
3259 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003260 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003261 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003262}
3263
Dan Gohmanaf752342009-07-07 17:06:11 +00003264const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003265 // Don't attempt to do anything other than create a SCEVUnknown object
3266 // here. createSCEV only calls getUnknown after checking for all other
3267 // interesting possibilities, and any other code that calls getUnknown
3268 // is doing so in order to hide a value from SCEV canonicalization.
3269
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003270 FoldingSetNodeID ID;
3271 ID.AddInteger(scUnknown);
3272 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003273 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003274 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3275 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3276 "Stale SCEVUnknown in uniquing map!");
3277 return S;
3278 }
3279 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3280 FirstUnknown);
3281 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003282 UniqueSCEVs.InsertNode(S, IP);
3283 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003284}
3285
Chris Lattnerd934c702004-04-02 20:23:17 +00003286//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003287// Basic SCEV Analysis and PHI Idiom Recognition Code
3288//
3289
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003290/// isSCEVable - Test if values of the given type are analyzable within
3291/// the SCEV framework. This primarily includes integer types, and it
3292/// can optionally include pointer types if the ScalarEvolution class
3293/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003294bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003295 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003296 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003297}
3298
3299/// getTypeSizeInBits - Return the size in bits of the specified type,
3300/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003301uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003302 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003303 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003304}
3305
3306/// getEffectiveSCEVType - Return a type with the same bitwidth as
3307/// the given type and which represents how SCEV will treat the given
3308/// type, for which isSCEVable must return true. For pointer types,
3309/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003310Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003311 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3312
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003313 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003314 return Ty;
3315
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003316 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003317 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003318 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003319}
Chris Lattnerd934c702004-04-02 20:23:17 +00003320
Dan Gohmanaf752342009-07-07 17:06:11 +00003321const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003322 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003323}
3324
Sanjoy Das7d752672015-12-08 04:32:54 +00003325
3326bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003327 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3328 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3329 // is set iff if find such SCEVUnknown.
3330 //
3331 struct FindInvalidSCEVUnknown {
3332 bool FindOne;
3333 FindInvalidSCEVUnknown() { FindOne = false; }
3334 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003335 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003336 case scConstant:
3337 return false;
3338 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003339 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003340 FindOne = true;
3341 return false;
3342 default:
3343 return true;
3344 }
3345 }
3346 bool isDone() const { return FindOne; }
3347 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003348
Shuxin Yangefc4c012013-07-08 17:33:13 +00003349 FindInvalidSCEVUnknown F;
3350 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3351 ST.visitAll(S);
3352
3353 return !F.FindOne;
3354}
3355
Wei Mia49559b2016-02-04 01:27:38 +00003356namespace {
3357// Helper class working with SCEVTraversal to figure out if a SCEV contains
3358// a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set
3359// iff if such sub scAddRecExpr type SCEV is found.
3360struct FindAddRecurrence {
3361 bool FoundOne;
3362 FindAddRecurrence() : FoundOne(false) {}
3363
3364 bool follow(const SCEV *S) {
3365 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3366 case scAddRecExpr:
3367 FoundOne = true;
3368 case scConstant:
3369 case scUnknown:
3370 case scCouldNotCompute:
3371 return false;
3372 default:
3373 return true;
3374 }
3375 }
3376 bool isDone() const { return FoundOne; }
3377};
3378}
3379
3380bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3381 HasRecMapType::iterator I = HasRecMap.find_as(S);
3382 if (I != HasRecMap.end())
3383 return I->second;
3384
3385 FindAddRecurrence F;
3386 SCEVTraversal<FindAddRecurrence> ST(F);
3387 ST.visitAll(S);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003388 HasRecMap.insert({S, F.FoundOne});
Wei Mia49559b2016-02-04 01:27:38 +00003389 return F.FoundOne;
3390}
3391
3392/// getSCEVValues - Return the Value set from S.
3393SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3394 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3395 if (SI == ExprValueMap.end())
3396 return nullptr;
3397#ifndef NDEBUG
3398 if (VerifySCEVMap) {
3399 // Check there is no dangling Value in the set returned.
3400 for (const auto &VE : SI->second)
3401 assert(ValueExprMap.count(VE));
3402 }
3403#endif
3404 return &SI->second;
3405}
3406
3407/// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap.
3408/// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S),
3409/// eraseValueFromMap should be used instead to ensure whenever V->S is removed
3410/// from ValueExprMap, V is also removed from the set of ExprValueMap[S].
3411void ScalarEvolution::eraseValueFromMap(Value *V) {
3412 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3413 if (I != ValueExprMap.end()) {
3414 const SCEV *S = I->second;
3415 SetVector<Value *> *SV = getSCEVValues(S);
3416 // Remove V from the set of ExprValueMap[S]
3417 if (SV)
3418 SV->remove(V);
3419 ValueExprMap.erase(V);
3420 }
3421}
3422
Chris Lattnerd934c702004-04-02 20:23:17 +00003423/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3424/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003425const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003426 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003427
Jingyue Wu42f1d672015-07-28 18:22:40 +00003428 const SCEV *S = getExistingSCEV(V);
3429 if (S == nullptr) {
3430 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003431 // During PHI resolution, it is possible to create two SCEVs for the same
3432 // V, so it is needed to double check whether V->S is inserted into
3433 // ValueExprMap before insert S->V into ExprValueMap.
3434 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003435 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mia49559b2016-02-04 01:27:38 +00003436 if (Pair.second)
3437 ExprValueMap[S].insert(V);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003438 }
3439 return S;
3440}
3441
3442const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3443 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3444
Shuxin Yangefc4c012013-07-08 17:33:13 +00003445 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3446 if (I != ValueExprMap.end()) {
3447 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003448 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003449 return S;
Wei Mia49559b2016-02-04 01:27:38 +00003450 forgetMemoizedResults(S);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003451 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003452 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003453 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003454}
3455
Dan Gohman0a40ad92009-04-16 03:18:22 +00003456/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3457///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003458const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3459 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003460 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003461 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003462 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003463
Chris Lattner229907c2011-07-18 04:54:35 +00003464 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003465 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003466 return getMulExpr(
3467 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003468}
3469
3470/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003471const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003472 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003473 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003474 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003475
Chris Lattner229907c2011-07-18 04:54:35 +00003476 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003477 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003478 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003479 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003480 return getMinusSCEV(AllOnes, V);
3481}
3482
Andrew Trick8b55b732011-03-14 16:50:06 +00003483/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003484const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003485 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003486 // Fast path: X - X --> 0.
3487 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003488 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003489
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003490 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3491 // makes it so that we cannot make much use of NUW.
3492 auto AddFlags = SCEV::FlagAnyWrap;
3493 const bool RHSIsNotMinSigned =
3494 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3495 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3496 // Let M be the minimum representable signed value. Then (-1)*RHS
3497 // signed-wraps if and only if RHS is M. That can happen even for
3498 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3499 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3500 // (-1)*RHS, we need to prove that RHS != M.
3501 //
3502 // If LHS is non-negative and we know that LHS - RHS does not
3503 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3504 // either by proving that RHS > M or that LHS >= 0.
3505 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3506 AddFlags = SCEV::FlagNSW;
3507 }
3508 }
3509
3510 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3511 // RHS is NSW and LHS >= 0.
3512 //
3513 // The difficulty here is that the NSW flag may have been proven
3514 // relative to a loop that is to be found in a recurrence in LHS and
3515 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3516 // larger scope than intended.
3517 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3518
3519 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003520}
3521
3522/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3523/// input value to the specified type. If the type must be extended, it is zero
3524/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003525const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003526ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3527 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003528 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3529 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003530 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003531 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003532 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003533 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003534 return getTruncateExpr(V, Ty);
3535 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003536}
3537
3538/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3539/// input value to the specified type. If the type must be extended, it is sign
3540/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003541const SCEV *
3542ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003543 Type *Ty) {
3544 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003545 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3546 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003547 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003548 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003549 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003550 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003551 return getTruncateExpr(V, Ty);
3552 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003553}
3554
Dan Gohmane712a2f2009-05-13 03:46:30 +00003555/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3556/// input value to the specified type. If the type must be extended, it is zero
3557/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003558const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003559ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3560 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003561 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3562 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003563 "Cannot noop or zero extend with non-integer arguments!");
3564 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3565 "getNoopOrZeroExtend cannot truncate!");
3566 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3567 return V; // No conversion
3568 return getZeroExtendExpr(V, Ty);
3569}
3570
3571/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3572/// input value to the specified type. If the type must be extended, it is sign
3573/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003574const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003575ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3576 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003577 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3578 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003579 "Cannot noop or sign extend with non-integer arguments!");
3580 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3581 "getNoopOrSignExtend cannot truncate!");
3582 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3583 return V; // No conversion
3584 return getSignExtendExpr(V, Ty);
3585}
3586
Dan Gohman8db2edc2009-06-13 15:56:47 +00003587/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3588/// the input value to the specified type. If the type must be extended,
3589/// it is extended with unspecified bits. The conversion must not be
3590/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003591const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003592ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3593 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003594 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3595 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003596 "Cannot noop or any extend with non-integer arguments!");
3597 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3598 "getNoopOrAnyExtend cannot truncate!");
3599 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3600 return V; // No conversion
3601 return getAnyExtendExpr(V, Ty);
3602}
3603
Dan Gohmane712a2f2009-05-13 03:46:30 +00003604/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3605/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003606const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003607ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3608 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003609 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3610 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003611 "Cannot truncate or noop with non-integer arguments!");
3612 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3613 "getTruncateOrNoop cannot extend!");
3614 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3615 return V; // No conversion
3616 return getTruncateExpr(V, Ty);
3617}
3618
Dan Gohman96212b62009-06-22 00:31:57 +00003619/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3620/// the types using zero-extension, and then perform a umax operation
3621/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003622const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3623 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003624 const SCEV *PromotedLHS = LHS;
3625 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003626
3627 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3628 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3629 else
3630 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3631
3632 return getUMaxExpr(PromotedLHS, PromotedRHS);
3633}
3634
Dan Gohman2bc22302009-06-22 15:03:27 +00003635/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3636/// the types using zero-extension, and then perform a umin operation
3637/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003638const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3639 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003640 const SCEV *PromotedLHS = LHS;
3641 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003642
3643 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3644 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3645 else
3646 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3647
3648 return getUMinExpr(PromotedLHS, PromotedRHS);
3649}
3650
Andrew Trick87716c92011-03-17 23:51:11 +00003651/// getPointerBase - Transitively follow the chain of pointer-type operands
3652/// until reaching a SCEV that does not have a single pointer operand. This
3653/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3654/// but corner cases do exist.
3655const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3656 // A pointer operand may evaluate to a nonpointer expression, such as null.
3657 if (!V->getType()->isPointerTy())
3658 return V;
3659
3660 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3661 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003662 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003663 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003664 for (const SCEV *NAryOp : NAry->operands()) {
3665 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003666 // Cannot find the base of an expression with multiple pointer operands.
3667 if (PtrOp)
3668 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003669 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003670 }
3671 }
3672 if (!PtrOp)
3673 return V;
3674 return getPointerBase(PtrOp);
3675 }
3676 return V;
3677}
3678
Dan Gohman0b89dff2009-07-25 01:13:03 +00003679/// PushDefUseChildren - Push users of the given Instruction
3680/// onto the given Worklist.
3681static void
3682PushDefUseChildren(Instruction *I,
3683 SmallVectorImpl<Instruction *> &Worklist) {
3684 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003685 for (User *U : I->users())
3686 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003687}
3688
3689/// ForgetSymbolicValue - This looks up computed SCEV values for all
3690/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003691/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003692/// resolution.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003693void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003694 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003695 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003696
Dan Gohman0b89dff2009-07-25 01:13:03 +00003697 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003698 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003699 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003700 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003701 if (!Visited.insert(I).second)
3702 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003703
Sanjoy Das63914592015-10-18 00:29:20 +00003704 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003705 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003706 const SCEV *Old = It->second;
3707
Dan Gohman0b89dff2009-07-25 01:13:03 +00003708 // Short-circuit the def-use traversal if the symbolic name
3709 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003710 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003711 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003712
Dan Gohman0b89dff2009-07-25 01:13:03 +00003713 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003714 // structure, it's a PHI that's in the progress of being computed
3715 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3716 // additional loop trip count information isn't going to change anything.
3717 // In the second case, createNodeForPHI will perform the necessary
3718 // updates on its own when it gets to that point. In the third, we do
3719 // want to forget the SCEVUnknown.
3720 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003721 !isa<SCEVUnknown>(Old) ||
3722 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003723 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003724 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003725 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003726 }
3727
3728 PushDefUseChildren(I, Worklist);
3729 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003730}
Chris Lattnerd934c702004-04-02 20:23:17 +00003731
Benjamin Kramer83709b12015-11-16 09:01:28 +00003732namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003733class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3734public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003735 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003736 ScalarEvolution &SE) {
3737 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003738 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003739 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3740 }
3741
3742 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3743 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3744
3745 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3746 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3747 Valid = false;
3748 return Expr;
3749 }
3750
3751 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3752 // Only allow AddRecExprs for this loop.
3753 if (Expr->getLoop() == L)
3754 return Expr->getStart();
3755 Valid = false;
3756 return Expr;
3757 }
3758
3759 bool isValid() { return Valid; }
3760
3761private:
3762 const Loop *L;
3763 bool Valid;
3764};
3765
3766class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3767public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003768 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003769 ScalarEvolution &SE) {
3770 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003771 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003772 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3773 }
3774
3775 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3776 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3777
3778 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3779 // Only allow AddRecExprs for this loop.
3780 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3781 Valid = false;
3782 return Expr;
3783 }
3784
3785 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3786 if (Expr->getLoop() == L && Expr->isAffine())
3787 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3788 Valid = false;
3789 return Expr;
3790 }
3791 bool isValid() { return Valid; }
3792
3793private:
3794 const Loop *L;
3795 bool Valid;
3796};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003797} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003798
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003799SCEV::NoWrapFlags
3800ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3801 if (!AR->isAffine())
3802 return SCEV::FlagAnyWrap;
3803
3804 typedef OverflowingBinaryOperator OBO;
3805 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3806
3807 if (!AR->hasNoSignedWrap()) {
3808 ConstantRange AddRecRange = getSignedRange(AR);
3809 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3810
3811 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3812 Instruction::Add, IncRange, OBO::NoSignedWrap);
3813 if (NSWRegion.contains(AddRecRange))
3814 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3815 }
3816
3817 if (!AR->hasNoUnsignedWrap()) {
3818 ConstantRange AddRecRange = getUnsignedRange(AR);
3819 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3820
3821 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3822 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3823 if (NUWRegion.contains(AddRecRange))
3824 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3825 }
3826
3827 return Result;
3828}
3829
Sanjoy Das118d9192016-03-31 05:14:22 +00003830namespace {
3831/// Represents an abstract binary operation. This may exist as a
3832/// normal instruction or constant expression, or may have been
3833/// derived from an expression tree.
3834struct BinaryOp {
3835 unsigned Opcode;
3836 Value *LHS;
3837 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003838 bool IsNSW;
3839 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003840
3841 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3842 /// constant expression.
3843 Operator *Op;
3844
3845 explicit BinaryOp(Operator *Op)
3846 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003847 IsNSW(false), IsNUW(false), Op(Op) {
3848 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3849 IsNSW = OBO->hasNoSignedWrap();
3850 IsNUW = OBO->hasNoUnsignedWrap();
3851 }
3852 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003853
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003854 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3855 bool IsNUW = false)
3856 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3857 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003858};
3859}
3860
3861
3862/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003863static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003864 auto *Op = dyn_cast<Operator>(V);
3865 if (!Op)
3866 return None;
3867
3868 // Implementation detail: all the cleverness here should happen without
3869 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3870 // SCEV expressions when possible, and we should not break that.
3871
3872 switch (Op->getOpcode()) {
3873 case Instruction::Add:
3874 case Instruction::Sub:
3875 case Instruction::Mul:
3876 case Instruction::UDiv:
3877 case Instruction::And:
3878 case Instruction::Or:
3879 case Instruction::AShr:
3880 case Instruction::Shl:
3881 return BinaryOp(Op);
3882
3883 case Instruction::Xor:
3884 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3885 // If the RHS of the xor is a signbit, then this is just an add.
3886 // Instcombine turns add of signbit into xor as a strength reduction step.
3887 if (RHSC->getValue().isSignBit())
3888 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3889 return BinaryOp(Op);
3890
3891 case Instruction::LShr:
3892 // Turn logical shift right of a constant into a unsigned divide.
3893 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3894 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3895
3896 // If the shift count is not less than the bitwidth, the result of
3897 // the shift is undefined. Don't try to analyze it, because the
3898 // resolution chosen here may differ from the resolution chosen in
3899 // other parts of the compiler.
3900 if (SA->getValue().ult(BitWidth)) {
3901 Constant *X =
3902 ConstantInt::get(SA->getContext(),
3903 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3904 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3905 }
3906 }
3907 return BinaryOp(Op);
3908
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003909 case Instruction::ExtractValue: {
3910 auto *EVI = cast<ExtractValueInst>(Op);
3911 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3912 break;
3913
3914 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3915 if (!CI)
3916 break;
3917
3918 if (auto *F = CI->getCalledFunction())
3919 switch (F->getIntrinsicID()) {
3920 case Intrinsic::sadd_with_overflow:
3921 case Intrinsic::uadd_with_overflow: {
3922 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3923 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3924 CI->getArgOperand(1));
3925
3926 // Now that we know that all uses of the arithmetic-result component of
3927 // CI are guarded by the overflow check, we can go ahead and pretend
3928 // that the arithmetic is non-overflowing.
3929 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3930 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3931 CI->getArgOperand(1), /* IsNSW = */ true,
3932 /* IsNUW = */ false);
3933 else
3934 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3935 CI->getArgOperand(1), /* IsNSW = */ false,
3936 /* IsNUW*/ true);
3937 }
3938
3939 case Intrinsic::ssub_with_overflow:
3940 case Intrinsic::usub_with_overflow:
3941 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3942 CI->getArgOperand(1));
3943
3944 case Intrinsic::smul_with_overflow:
3945 case Intrinsic::umul_with_overflow:
3946 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3947 CI->getArgOperand(1));
3948 default:
3949 break;
3950 }
3951 }
3952
Sanjoy Das118d9192016-03-31 05:14:22 +00003953 default:
3954 break;
3955 }
3956
3957 return None;
3958}
3959
Sanjoy Das55015d22015-10-02 23:09:44 +00003960const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3961 const Loop *L = LI.getLoopFor(PN->getParent());
3962 if (!L || L->getHeader() != PN->getParent())
3963 return nullptr;
3964
3965 // The loop may have multiple entrances or multiple exits; we can analyze
3966 // this phi as an addrec if it has a unique entry value and a unique
3967 // backedge value.
3968 Value *BEValueV = nullptr, *StartValueV = nullptr;
3969 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3970 Value *V = PN->getIncomingValue(i);
3971 if (L->contains(PN->getIncomingBlock(i))) {
3972 if (!BEValueV) {
3973 BEValueV = V;
3974 } else if (BEValueV != V) {
3975 BEValueV = nullptr;
3976 break;
3977 }
3978 } else if (!StartValueV) {
3979 StartValueV = V;
3980 } else if (StartValueV != V) {
3981 StartValueV = nullptr;
3982 break;
3983 }
3984 }
3985 if (BEValueV && StartValueV) {
3986 // While we are analyzing this PHI node, handle its value symbolically.
3987 const SCEV *SymbolicName = getUnknown(PN);
3988 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3989 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003990 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003991
3992 // Using this symbolic name for the PHI, analyze the value coming around
3993 // the back-edge.
3994 const SCEV *BEValue = getSCEV(BEValueV);
3995
3996 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3997 // has a special value for the first iteration of the loop.
3998
3999 // If the value coming around the backedge is an add with the symbolic
4000 // value we just inserted, then we found a simple induction variable!
4001 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4002 // If there is a single occurrence of the symbolic value, replace it
4003 // with a recurrence.
4004 unsigned FoundIndex = Add->getNumOperands();
4005 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4006 if (Add->getOperand(i) == SymbolicName)
4007 if (FoundIndex == e) {
4008 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004009 break;
4010 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004011
4012 if (FoundIndex != Add->getNumOperands()) {
4013 // Create an add with everything but the specified operand.
4014 SmallVector<const SCEV *, 8> Ops;
4015 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4016 if (i != FoundIndex)
4017 Ops.push_back(Add->getOperand(i));
4018 const SCEV *Accum = getAddExpr(Ops);
4019
4020 // This is not a valid addrec if the step amount is varying each
4021 // loop iteration, but is not itself an addrec in this loop.
4022 if (isLoopInvariant(Accum, L) ||
4023 (isa<SCEVAddRecExpr>(Accum) &&
4024 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4025 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4026
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004027 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004028 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4029 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004030 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004031 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004032 Flags = setFlags(Flags, SCEV::FlagNSW);
4033 }
4034 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4035 // If the increment is an inbounds GEP, then we know the address
4036 // space cannot be wrapped around. We cannot make any guarantee
4037 // about signed or unsigned overflow because pointers are
4038 // unsigned but we may have a negative index from the base
4039 // pointer. We can guarantee that no unsigned wrap occurs if the
4040 // indices form a positive value.
4041 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4042 Flags = setFlags(Flags, SCEV::FlagNW);
4043
4044 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4045 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4046 Flags = setFlags(Flags, SCEV::FlagNUW);
4047 }
4048
4049 // We cannot transfer nuw and nsw flags from subtraction
4050 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4051 // for instance.
4052 }
4053
4054 const SCEV *StartVal = getSCEV(StartValueV);
4055 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4056
Sanjoy Das55015d22015-10-02 23:09:44 +00004057 // Okay, for the entire analysis of this edge we assumed the PHI
4058 // to be symbolic. We now need to go back and purge all of the
4059 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004060 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004061 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004062
4063 // We can add Flags to the post-inc expression only if we
4064 // know that it us *undefined behavior* for BEValueV to
4065 // overflow.
4066 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4067 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4068 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4069
Sanjoy Das55015d22015-10-02 23:09:44 +00004070 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004071 }
4072 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004073 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004074 // Otherwise, this could be a loop like this:
4075 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4076 // In this case, j = {1,+,1} and BEValue is j.
4077 // Because the other in-value of i (0) fits the evolution of BEValue
4078 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004079 //
4080 // We can generalize this saying that i is the shifted value of BEValue
4081 // by one iteration:
4082 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4083 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4084 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4085 if (Shifted != getCouldNotCompute() &&
4086 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004087 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004088 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004089 // Okay, for the entire analysis of this edge we assumed the PHI
4090 // to be symbolic. We now need to go back and purge all of the
4091 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004092 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004093 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4094 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004095 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004096 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004097 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004098
4099 // Remove the temporary PHI node SCEV that has been inserted while intending
4100 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4101 // as it will prevent later (possibly simpler) SCEV expressions to be added
4102 // to the ValueExprMap.
4103 ValueExprMap.erase(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004104 }
4105
4106 return nullptr;
4107}
4108
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004109// Checks if the SCEV S is available at BB. S is considered available at BB
4110// if S can be materialized at BB without introducing a fault.
4111static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4112 BasicBlock *BB) {
4113 struct CheckAvailable {
4114 bool TraversalDone = false;
4115 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004116
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004117 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4118 BasicBlock *BB = nullptr;
4119 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004120
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004121 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4122 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004123
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004124 bool setUnavailable() {
4125 TraversalDone = true;
4126 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004127 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004128 }
4129
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004130 bool follow(const SCEV *S) {
4131 switch (S->getSCEVType()) {
4132 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4133 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004134 // These expressions are available if their operand(s) is/are.
4135 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004136
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004137 case scAddRecExpr: {
4138 // We allow add recurrences that are on the loop BB is in, or some
4139 // outer loop. This guarantees availability because the value of the
4140 // add recurrence at BB is simply the "current" value of the induction
4141 // variable. We can relax this in the future; for instance an add
4142 // recurrence on a sibling dominating loop is also available at BB.
4143 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4144 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004145 return true;
4146
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004147 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004148 }
4149
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004150 case scUnknown: {
4151 // For SCEVUnknown, we check for simple dominance.
4152 const auto *SU = cast<SCEVUnknown>(S);
4153 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004154
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004155 if (isa<Argument>(V))
4156 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004157
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004158 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4159 return false;
4160
4161 return setUnavailable();
4162 }
4163
4164 case scUDivExpr:
4165 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004166 // We do not try to smart about these at all.
4167 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004168 }
4169 llvm_unreachable("switch should be fully covered!");
4170 }
4171
4172 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004173 };
4174
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004175 CheckAvailable CA(L, BB, DT);
4176 SCEVTraversal<CheckAvailable> ST(CA);
4177
4178 ST.visitAll(S);
4179 return CA.Available;
4180}
4181
4182// Try to match a control flow sequence that branches out at BI and merges back
4183// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4184// match.
4185static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4186 Value *&C, Value *&LHS, Value *&RHS) {
4187 C = BI->getCondition();
4188
4189 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4190 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4191
4192 if (!LeftEdge.isSingleEdge())
4193 return false;
4194
4195 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4196
4197 Use &LeftUse = Merge->getOperandUse(0);
4198 Use &RightUse = Merge->getOperandUse(1);
4199
4200 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4201 LHS = LeftUse;
4202 RHS = RightUse;
4203 return true;
4204 }
4205
4206 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4207 LHS = RightUse;
4208 RHS = LeftUse;
4209 return true;
4210 }
4211
4212 return false;
4213}
4214
4215const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004216 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004217 const Loop *L = LI.getLoopFor(PN->getParent());
4218
Sanjoy Das337d4782015-10-31 23:21:40 +00004219 // We don't want to break LCSSA, even in a SCEV expression tree.
4220 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4221 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4222 return nullptr;
4223
Sanjoy Das55015d22015-10-02 23:09:44 +00004224 // Try to match
4225 //
4226 // br %cond, label %left, label %right
4227 // left:
4228 // br label %merge
4229 // right:
4230 // br label %merge
4231 // merge:
4232 // V = phi [ %x, %left ], [ %y, %right ]
4233 //
4234 // as "select %cond, %x, %y"
4235
4236 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4237 assert(IDom && "At least the entry block should dominate PN");
4238
4239 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4240 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4241
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004242 if (BI && BI->isConditional() &&
4243 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4244 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4245 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004246 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4247 }
4248
4249 return nullptr;
4250}
4251
4252const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4253 if (const SCEV *S = createAddRecFromPHI(PN))
4254 return S;
4255
4256 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4257 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004258
Dan Gohmana9c205c2010-02-25 06:57:05 +00004259 // If the PHI has a single incoming value, follow that value, unless the
4260 // PHI's incoming blocks are in a different loop, in which case doing so
4261 // risks breaking LCSSA form. Instcombine would normally zap these, but
4262 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004263 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004264 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004265 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004266
Chris Lattnerd934c702004-04-02 20:23:17 +00004267 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004268 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004269}
4270
Sanjoy Das55015d22015-10-02 23:09:44 +00004271const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4272 Value *Cond,
4273 Value *TrueVal,
4274 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004275 // Handle "constant" branch or select. This can occur for instance when a
4276 // loop pass transforms an inner loop and moves on to process the outer loop.
4277 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4278 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4279
Sanjoy Dasd0671342015-10-02 19:39:59 +00004280 // Try to match some simple smax or umax patterns.
4281 auto *ICI = dyn_cast<ICmpInst>(Cond);
4282 if (!ICI)
4283 return getUnknown(I);
4284
4285 Value *LHS = ICI->getOperand(0);
4286 Value *RHS = ICI->getOperand(1);
4287
4288 switch (ICI->getPredicate()) {
4289 case ICmpInst::ICMP_SLT:
4290 case ICmpInst::ICMP_SLE:
4291 std::swap(LHS, RHS);
4292 // fall through
4293 case ICmpInst::ICMP_SGT:
4294 case ICmpInst::ICMP_SGE:
4295 // a >s b ? a+x : b+x -> smax(a, b)+x
4296 // a >s b ? b+x : a+x -> smin(a, b)+x
4297 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4298 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4299 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4300 const SCEV *LA = getSCEV(TrueVal);
4301 const SCEV *RA = getSCEV(FalseVal);
4302 const SCEV *LDiff = getMinusSCEV(LA, LS);
4303 const SCEV *RDiff = getMinusSCEV(RA, RS);
4304 if (LDiff == RDiff)
4305 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4306 LDiff = getMinusSCEV(LA, RS);
4307 RDiff = getMinusSCEV(RA, LS);
4308 if (LDiff == RDiff)
4309 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4310 }
4311 break;
4312 case ICmpInst::ICMP_ULT:
4313 case ICmpInst::ICMP_ULE:
4314 std::swap(LHS, RHS);
4315 // fall through
4316 case ICmpInst::ICMP_UGT:
4317 case ICmpInst::ICMP_UGE:
4318 // a >u b ? a+x : b+x -> umax(a, b)+x
4319 // a >u b ? b+x : a+x -> umin(a, b)+x
4320 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4321 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4322 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4323 const SCEV *LA = getSCEV(TrueVal);
4324 const SCEV *RA = getSCEV(FalseVal);
4325 const SCEV *LDiff = getMinusSCEV(LA, LS);
4326 const SCEV *RDiff = getMinusSCEV(RA, RS);
4327 if (LDiff == RDiff)
4328 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4329 LDiff = getMinusSCEV(LA, RS);
4330 RDiff = getMinusSCEV(RA, LS);
4331 if (LDiff == RDiff)
4332 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4333 }
4334 break;
4335 case ICmpInst::ICMP_NE:
4336 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4337 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4338 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4339 const SCEV *One = getOne(I->getType());
4340 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4341 const SCEV *LA = getSCEV(TrueVal);
4342 const SCEV *RA = getSCEV(FalseVal);
4343 const SCEV *LDiff = getMinusSCEV(LA, LS);
4344 const SCEV *RDiff = getMinusSCEV(RA, One);
4345 if (LDiff == RDiff)
4346 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4347 }
4348 break;
4349 case ICmpInst::ICMP_EQ:
4350 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4351 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4352 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4353 const SCEV *One = getOne(I->getType());
4354 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4355 const SCEV *LA = getSCEV(TrueVal);
4356 const SCEV *RA = getSCEV(FalseVal);
4357 const SCEV *LDiff = getMinusSCEV(LA, One);
4358 const SCEV *RDiff = getMinusSCEV(RA, LS);
4359 if (LDiff == RDiff)
4360 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4361 }
4362 break;
4363 default:
4364 break;
4365 }
4366
4367 return getUnknown(I);
4368}
4369
Dan Gohmanee750d12009-05-08 20:26:55 +00004370/// createNodeForGEP - Expand GEP instructions into add and multiply
4371/// operations. This allows them to be analyzed by regular SCEV code.
4372///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004373const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004374 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004375 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004376 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004377
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004378 SmallVector<const SCEV *, 4> IndexExprs;
4379 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4380 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004381 return getGEPExpr(GEP->getSourceElementType(),
4382 getSCEV(GEP->getPointerOperand()),
4383 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004384}
4385
Nick Lewycky3783b462007-11-22 07:59:40 +00004386/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4387/// guaranteed to end in (at every loop iteration). It is, at the same time,
4388/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
4389/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004390uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004391ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004392 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004393 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004394
Dan Gohmana30370b2009-05-04 22:02:23 +00004395 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004396 return std::min(GetMinTrailingZeros(T->getOperand()),
4397 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004398
Dan Gohmana30370b2009-05-04 22:02:23 +00004399 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004400 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4401 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4402 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004403 }
4404
Dan Gohmana30370b2009-05-04 22:02:23 +00004405 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004406 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4407 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4408 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004409 }
4410
Dan Gohmana30370b2009-05-04 22:02:23 +00004411 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004412 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004413 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004414 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004415 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004416 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004417 }
4418
Dan Gohmana30370b2009-05-04 22:02:23 +00004419 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004420 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004421 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4422 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004423 for (unsigned i = 1, e = M->getNumOperands();
4424 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004425 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004426 BitWidth);
4427 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004428 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004429
Dan Gohmana30370b2009-05-04 22:02:23 +00004430 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004431 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004432 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004433 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004434 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004435 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004436 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004437
Dan Gohmana30370b2009-05-04 22:02:23 +00004438 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004439 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004440 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004441 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004442 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004443 return MinOpRes;
4444 }
4445
Dan Gohmana30370b2009-05-04 22:02:23 +00004446 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004447 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004448 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004449 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004450 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004451 return MinOpRes;
4452 }
4453
Dan Gohmanc702fc02009-06-19 23:29:04 +00004454 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4455 // For a SCEVUnknown, ask ValueTracking.
4456 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004457 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004458 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4459 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004460 return Zeros.countTrailingOnes();
4461 }
4462
4463 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004464 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004465}
Chris Lattnerd934c702004-04-02 20:23:17 +00004466
Sanjoy Das1f05c512014-10-10 21:22:34 +00004467/// GetRangeFromMetadata - Helper method to assign a range to V from
4468/// metadata present in the IR.
4469static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004470 if (Instruction *I = dyn_cast<Instruction>(V))
4471 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4472 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004473
4474 return None;
4475}
4476
Sanjoy Das91b54772015-03-09 21:43:43 +00004477/// getRange - Determine the range for a particular SCEV. If SignHint is
4478/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4479/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004480///
4481ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004482ScalarEvolution::getRange(const SCEV *S,
4483 ScalarEvolution::RangeSignHint SignHint) {
4484 DenseMap<const SCEV *, ConstantRange> &Cache =
4485 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4486 : SignedRanges;
4487
Dan Gohman761065e2010-11-17 02:44:44 +00004488 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004489 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4490 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004491 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004492
4493 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004494 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004495
Dan Gohman85be4332010-01-26 19:19:05 +00004496 unsigned BitWidth = getTypeSizeInBits(S->getType());
4497 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4498
Sanjoy Das91b54772015-03-09 21:43:43 +00004499 // If the value has known zeros, the maximum value will have those known zeros
4500 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004501 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004502 if (TZ != 0) {
4503 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4504 ConservativeResult =
4505 ConstantRange(APInt::getMinValue(BitWidth),
4506 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4507 else
4508 ConservativeResult = ConstantRange(
4509 APInt::getSignedMinValue(BitWidth),
4510 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4511 }
Dan Gohman85be4332010-01-26 19:19:05 +00004512
Dan Gohmane65c9172009-07-13 21:35:55 +00004513 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004514 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004515 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004516 X = X.add(getRange(Add->getOperand(i), SignHint));
4517 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004518 }
4519
4520 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004521 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004522 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004523 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4524 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004525 }
4526
4527 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004528 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004529 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004530 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4531 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004532 }
4533
4534 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004535 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004536 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004537 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4538 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004539 }
4540
4541 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004542 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4543 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4544 return setRange(UDiv, SignHint,
4545 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004546 }
4547
4548 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004549 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4550 return setRange(ZExt, SignHint,
4551 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004552 }
4553
4554 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004555 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4556 return setRange(SExt, SignHint,
4557 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004558 }
4559
4560 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004561 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4562 return setRange(Trunc, SignHint,
4563 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004564 }
4565
Dan Gohmane65c9172009-07-13 21:35:55 +00004566 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004567 // If there's no unsigned wrap, the value will never be less than its
4568 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004569 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004570 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004571 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004572 ConservativeResult = ConservativeResult.intersectWith(
4573 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004574
Dan Gohman51ad99d2010-01-21 02:09:26 +00004575 // If there's no signed wrap, and all the operands have the same sign or
4576 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004577 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004578 bool AllNonNeg = true;
4579 bool AllNonPos = true;
4580 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4581 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4582 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4583 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004584 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004585 ConservativeResult = ConservativeResult.intersectWith(
4586 ConstantRange(APInt(BitWidth, 0),
4587 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004588 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004589 ConservativeResult = ConservativeResult.intersectWith(
4590 ConstantRange(APInt::getSignedMinValue(BitWidth),
4591 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004592 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004593
4594 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004595 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004596 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004597 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4598 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004599 auto RangeFromAffine = getRangeForAffineAR(
4600 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4601 BitWidth);
4602 if (!RangeFromAffine.isFullSet())
4603 ConservativeResult =
4604 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004605
4606 auto RangeFromFactoring = getRangeViaFactoring(
4607 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4608 BitWidth);
4609 if (!RangeFromFactoring.isFullSet())
4610 ConservativeResult =
4611 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004612 }
Dan Gohmand261d272009-06-24 01:05:09 +00004613 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004614
Sanjoy Das91b54772015-03-09 21:43:43 +00004615 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004616 }
4617
Dan Gohmanc702fc02009-06-19 23:29:04 +00004618 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004619 // Check if the IR explicitly contains !range metadata.
4620 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4621 if (MDRange.hasValue())
4622 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4623
Sanjoy Das91b54772015-03-09 21:43:43 +00004624 // Split here to avoid paying the compile-time cost of calling both
4625 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4626 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004627 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004628 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4629 // For a SCEVUnknown, ask ValueTracking.
4630 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004631 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004632 if (Ones != ~Zeros + 1)
4633 ConservativeResult =
4634 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4635 } else {
4636 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4637 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004638 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004639 if (NS > 1)
4640 ConservativeResult = ConservativeResult.intersectWith(
4641 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4642 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004643 }
4644
4645 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004646 }
4647
Sanjoy Das91b54772015-03-09 21:43:43 +00004648 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004649}
4650
Sanjoy Dasb765b632016-03-02 00:57:39 +00004651ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4652 const SCEV *Step,
4653 const SCEV *MaxBECount,
4654 unsigned BitWidth) {
4655 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4656 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4657 "Precondition!");
4658
4659 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4660
4661 // Check for overflow. This must be done with ConstantRange arithmetic
4662 // because we could be called from within the ScalarEvolution overflow
4663 // checking code.
4664
4665 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4666 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4667 ConstantRange ZExtMaxBECountRange =
4668 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4669
4670 ConstantRange StepSRange = getSignedRange(Step);
4671 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4672
4673 ConstantRange StartURange = getUnsignedRange(Start);
4674 ConstantRange EndURange =
4675 StartURange.add(MaxBECountRange.multiply(StepSRange));
4676
4677 // Check for unsigned overflow.
4678 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4679 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4680 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4681 ZExtEndURange) {
4682 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4683 EndURange.getUnsignedMin());
4684 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4685 EndURange.getUnsignedMax());
4686 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4687 if (!IsFullRange)
4688 Result =
4689 Result.intersectWith(ConstantRange(Min, Max + 1));
4690 }
4691
4692 ConstantRange StartSRange = getSignedRange(Start);
4693 ConstantRange EndSRange =
4694 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4695
4696 // Check for signed overflow. This must be done with ConstantRange
4697 // arithmetic because we could be called from within the ScalarEvolution
4698 // overflow checking code.
4699 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4700 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4701 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4702 SExtEndSRange) {
4703 APInt Min =
4704 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4705 APInt Max =
4706 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4707 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4708 if (!IsFullRange)
4709 Result =
4710 Result.intersectWith(ConstantRange(Min, Max + 1));
4711 }
4712
4713 return Result;
4714}
4715
Sanjoy Dasbf730982016-03-02 00:57:54 +00004716ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4717 const SCEV *Step,
4718 const SCEV *MaxBECount,
4719 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004720 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4721 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4722
4723 struct SelectPattern {
4724 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004725 APInt TrueValue;
4726 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004727
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004728 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4729 const SCEV *S) {
4730 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004731 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004732
4733 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4734 "Should be!");
4735
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004736 // Peel off a constant offset:
4737 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4738 // In the future we could consider being smarter here and handle
4739 // {Start+Step,+,Step} too.
4740 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4741 return;
4742
4743 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4744 S = SA->getOperand(1);
4745 }
4746
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004747 // Peel off a cast operation
4748 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4749 CastOp = SCast->getSCEVType();
4750 S = SCast->getOperand();
4751 }
4752
Sanjoy Dasbf730982016-03-02 00:57:54 +00004753 using namespace llvm::PatternMatch;
4754
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004755 auto *SU = dyn_cast<SCEVUnknown>(S);
4756 const APInt *TrueVal, *FalseVal;
4757 if (!SU ||
4758 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4759 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004760 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004761 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004762 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004763
4764 TrueValue = *TrueVal;
4765 FalseValue = *FalseVal;
4766
4767 // Re-apply the cast we peeled off earlier
4768 if (CastOp.hasValue())
4769 switch (*CastOp) {
4770 default:
4771 llvm_unreachable("Unknown SCEV cast type!");
4772
4773 case scTruncate:
4774 TrueValue = TrueValue.trunc(BitWidth);
4775 FalseValue = FalseValue.trunc(BitWidth);
4776 break;
4777 case scZeroExtend:
4778 TrueValue = TrueValue.zext(BitWidth);
4779 FalseValue = FalseValue.zext(BitWidth);
4780 break;
4781 case scSignExtend:
4782 TrueValue = TrueValue.sext(BitWidth);
4783 FalseValue = FalseValue.sext(BitWidth);
4784 break;
4785 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004786
4787 // Re-apply the constant offset we peeled off earlier
4788 TrueValue += Offset;
4789 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004790 }
4791
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004792 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004793 };
4794
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004795 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004796 if (!StartPattern.isRecognized())
4797 return ConstantRange(BitWidth, /* isFullSet = */ true);
4798
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004799 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004800 if (!StepPattern.isRecognized())
4801 return ConstantRange(BitWidth, /* isFullSet = */ true);
4802
4803 if (StartPattern.Condition != StepPattern.Condition) {
4804 // We don't handle this case today; but we could, by considering four
4805 // possibilities below instead of two. I'm not sure if there are cases where
4806 // that will help over what getRange already does, though.
4807 return ConstantRange(BitWidth, /* isFullSet = */ true);
4808 }
4809
4810 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4811 // construct arbitrary general SCEV expressions here. This function is called
4812 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4813 // say) can end up caching a suboptimal value.
4814
Sanjoy Das6b017a12016-03-02 02:56:29 +00004815 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4816 // C2352 and C2512 (otherwise it isn't needed).
4817
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004818 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004819 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004820 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004821 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004822
Sanjoy Das1168f932016-03-02 02:34:20 +00004823 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004824 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004825 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004826 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004827
4828 return TrueRange.unionWith(FalseRange);
4829}
4830
Jingyue Wu42f1d672015-07-28 18:22:40 +00004831SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004832 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004833 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4834
4835 // Return early if there are no flags to propagate to the SCEV.
4836 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4837 if (BinOp->hasNoUnsignedWrap())
4838 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4839 if (BinOp->hasNoSignedWrap())
4840 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004841 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004842 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004843
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004844 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4845}
4846
4847bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4848 // Here we check that I is in the header of the innermost loop containing I,
4849 // since we only deal with instructions in the loop header. The actual loop we
4850 // need to check later will come from an add recurrence, but getting that
4851 // requires computing the SCEV of the operands, which can be expensive. This
4852 // check we can do cheaply to rule out some cases early.
4853 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004854 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004855 InnermostContainingLoop->getHeader() != I->getParent())
4856 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004857
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004858 // Only proceed if we can prove that I does not yield poison.
4859 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004860
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004861 // At this point we know that if I is executed, then it does not wrap
4862 // according to at least one of NSW or NUW. If I is not executed, then we do
4863 // not know if the calculation that I represents would wrap. Multiple
4864 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004865 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4866 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004867 // that guarantee for cases where I is not executed. So we need to find the
4868 // loop that I is considered in relation to and prove that I is executed for
4869 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004870 // calculates does not wrap anywhere in the loop, so then we can apply the
4871 // flags to the SCEV.
4872 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004873 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4874 // from different loops, so that we know which loop to prove that I is
4875 // executed in.
4876 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4877 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004878 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004879 bool AllOtherOpsLoopInvariant = true;
4880 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4881 ++OtherOpIndex) {
4882 if (OtherOpIndex != OpIndex) {
4883 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4884 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4885 AllOtherOpsLoopInvariant = false;
4886 break;
4887 }
4888 }
4889 }
4890 if (AllOtherOpsLoopInvariant &&
4891 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4892 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004893 }
4894 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004895 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004896}
4897
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004898bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4899 // If we know that \c I can never be poison period, then that's enough.
4900 if (isSCEVExprNeverPoison(I))
4901 return true;
4902
4903 // For an add recurrence specifically, we assume that infinite loops without
4904 // side effects are undefined behavior, and then reason as follows:
4905 //
4906 // If the add recurrence is poison in any iteration, it is poison on all
4907 // future iterations (since incrementing poison yields poison). If the result
4908 // of the add recurrence is fed into the loop latch condition and the loop
4909 // does not contain any throws or exiting blocks other than the latch, we now
4910 // have the ability to "choose" whether the backedge is taken or not (by
4911 // choosing a sufficiently evil value for the poison feeding into the branch)
4912 // for every iteration including and after the one in which \p I first became
4913 // poison. There are two possibilities (let's call the iteration in which \p
4914 // I first became poison as K):
4915 //
4916 // 1. In the set of iterations including and after K, the loop body executes
4917 // no side effects. In this case executing the backege an infinte number
4918 // of times will yield undefined behavior.
4919 //
4920 // 2. In the set of iterations including and after K, the loop body executes
4921 // at least one side effect. In this case, that specific instance of side
4922 // effect is control dependent on poison, which also yields undefined
4923 // behavior.
4924
4925 auto *ExitingBB = L->getExitingBlock();
4926 auto *LatchBB = L->getLoopLatch();
4927 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4928 return false;
4929
4930 SmallPtrSet<const Instruction *, 16> Pushed;
4931 SmallVector<const Instruction *, 8> Stack;
4932
4933 Pushed.insert(I);
4934 for (auto *U : I->users())
4935 if (Pushed.insert(cast<Instruction>(U)).second)
4936 Stack.push_back(cast<Instruction>(U));
4937
4938 bool LatchControlDependentOnPoison = false;
4939 while (!Stack.empty()) {
4940 const Instruction *I = Stack.pop_back_val();
4941
4942 for (auto *U : I->users()) {
4943 if (propagatesFullPoison(cast<Instruction>(U))) {
4944 if (Pushed.insert(cast<Instruction>(U)).second)
4945 Stack.push_back(cast<Instruction>(U));
4946 } else if (auto *BI = dyn_cast<BranchInst>(U)) {
4947 assert(BI->isConditional() && "Only possibility!");
4948 if (BI->getParent() == LatchBB) {
4949 LatchControlDependentOnPoison = true;
4950 break;
4951 }
4952 }
4953 }
4954 }
4955
4956 if (!LatchControlDependentOnPoison)
4957 return false;
4958
4959 // Now check if loop is no-throw, and cache the information. In the future,
4960 // we can consider commoning this logic with LICMSafetyInfo into a separate
4961 // analysis pass.
4962
4963 auto Itr = LoopMayThrow.find(L);
4964 if (Itr == LoopMayThrow.end()) {
4965 bool MayThrow = false;
4966 for (auto *BB : L->getBlocks()) {
4967 MayThrow = any_of(*BB, [](Instruction &I) { return I.mayThrow(); });
4968 if (MayThrow)
4969 break;
4970 }
4971 auto InsertPair = LoopMayThrow.insert({L, MayThrow});
4972 assert(InsertPair.second && "We just checked!");
4973 Itr = InsertPair.first;
4974 }
4975
4976 return !Itr->second;
4977}
4978
Jingyue Wu42f1d672015-07-28 18:22:40 +00004979/// createSCEV - We know that there is no SCEV for the specified value. Analyze
4980/// the expression.
Chris Lattnerd934c702004-04-02 20:23:17 +00004981///
Dan Gohmanaf752342009-07-07 17:06:11 +00004982const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004983 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004984 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004985
Dan Gohman69451a02010-03-09 23:46:50 +00004986 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00004987 // Don't attempt to analyze instructions in blocks that aren't
4988 // reachable. Such instructions don't matter, and they aren't required
4989 // to obey basic rules for definitions dominating uses which this
4990 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004991 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004992 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004993 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00004994 return getConstant(CI);
4995 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004996 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004997 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00004998 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004999 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005000 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005001
Dan Gohman80ca01c2009-07-17 20:47:02 +00005002 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005003 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005004 switch (BO->Opcode) {
5005 case Instruction::Add: {
5006 // The simple thing to do would be to just call getSCEV on both operands
5007 // and call getAddExpr with the result. However if we're looking at a
5008 // bunch of things all added together, this can be quite inefficient,
5009 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5010 // Instead, gather up all the operands and make a single getAddExpr call.
5011 // LLVM IR canonical form means we need only traverse the left operands.
5012 SmallVector<const SCEV *, 4> AddOps;
5013 do {
5014 if (BO->Op) {
5015 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5016 AddOps.push_back(OpSCEV);
5017 break;
5018 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005019
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005020 // If a NUW or NSW flag can be applied to the SCEV for this
5021 // addition, then compute the SCEV for this addition by itself
5022 // with a separate call to getAddExpr. We need to do that
5023 // instead of pushing the operands of the addition onto AddOps,
5024 // since the flags are only known to apply to this particular
5025 // addition - they may not apply to other additions that can be
5026 // formed with operands from AddOps.
5027 const SCEV *RHS = getSCEV(BO->RHS);
5028 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5029 if (Flags != SCEV::FlagAnyWrap) {
5030 const SCEV *LHS = getSCEV(BO->LHS);
5031 if (BO->Opcode == Instruction::Sub)
5032 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5033 else
5034 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5035 break;
5036 }
Dan Gohman36bad002009-09-17 18:05:20 +00005037 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005038
5039 if (BO->Opcode == Instruction::Sub)
5040 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5041 else
5042 AddOps.push_back(getSCEV(BO->RHS));
5043
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005044 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005045 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5046 NewBO->Opcode != Instruction::Sub)) {
5047 AddOps.push_back(getSCEV(BO->LHS));
5048 break;
5049 }
5050 BO = NewBO;
5051 } while (true);
5052
5053 return getAddExpr(AddOps);
5054 }
5055
5056 case Instruction::Mul: {
5057 SmallVector<const SCEV *, 4> MulOps;
5058 do {
5059 if (BO->Op) {
5060 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5061 MulOps.push_back(OpSCEV);
5062 break;
5063 }
5064
5065 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5066 if (Flags != SCEV::FlagAnyWrap) {
5067 MulOps.push_back(
5068 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5069 break;
5070 }
5071 }
5072
5073 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005074 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005075 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5076 MulOps.push_back(getSCEV(BO->LHS));
5077 break;
5078 }
5079 BO = NewBO;
5080 } while (true);
5081
5082 return getMulExpr(MulOps);
5083 }
5084 case Instruction::UDiv:
5085 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5086 case Instruction::Sub: {
5087 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5088 if (BO->Op)
5089 Flags = getNoWrapFlagsFromUB(BO->Op);
5090 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5091 }
5092 case Instruction::And:
5093 // For an expression like x&255 that merely masks off the high bits,
5094 // use zext(trunc(x)) as the SCEV expression.
5095 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5096 if (CI->isNullValue())
5097 return getSCEV(BO->RHS);
5098 if (CI->isAllOnesValue())
5099 return getSCEV(BO->LHS);
5100 const APInt &A = CI->getValue();
5101
5102 // Instcombine's ShrinkDemandedConstant may strip bits out of
5103 // constants, obscuring what would otherwise be a low-bits mask.
5104 // Use computeKnownBits to compute what ShrinkDemandedConstant
5105 // knew about to reconstruct a low-bits mask value.
5106 unsigned LZ = A.countLeadingZeros();
5107 unsigned TZ = A.countTrailingZeros();
5108 unsigned BitWidth = A.getBitWidth();
5109 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5110 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5111 0, &AC, nullptr, &DT);
5112
5113 APInt EffectiveMask =
5114 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5115 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5116 const SCEV *MulCount = getConstant(ConstantInt::get(
5117 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5118 return getMulExpr(
5119 getZeroExtendExpr(
5120 getTruncateExpr(
5121 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5122 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5123 BO->LHS->getType()),
5124 MulCount);
5125 }
Dan Gohman36bad002009-09-17 18:05:20 +00005126 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005127 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005128
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005129 case Instruction::Or:
5130 // If the RHS of the Or is a constant, we may have something like:
5131 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5132 // optimizations will transparently handle this case.
5133 //
5134 // In order for this transformation to be safe, the LHS must be of the
5135 // form X*(2^n) and the Or constant must be less than 2^n.
5136 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5137 const SCEV *LHS = getSCEV(BO->LHS);
5138 const APInt &CIVal = CI->getValue();
5139 if (GetMinTrailingZeros(LHS) >=
5140 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5141 // Build a plain add SCEV.
5142 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5143 // If the LHS of the add was an addrec and it has no-wrap flags,
5144 // transfer the no-wrap flags, since an or won't introduce a wrap.
5145 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5146 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5147 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5148 OldAR->getNoWrapFlags());
5149 }
5150 return S;
5151 }
5152 }
5153 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005154
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005155 case Instruction::Xor:
5156 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5157 // If the RHS of xor is -1, then this is a not operation.
5158 if (CI->isAllOnesValue())
5159 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005160
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005161 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5162 // This is a variant of the check for xor with -1, and it handles
5163 // the case where instcombine has trimmed non-demanded bits out
5164 // of an xor with -1.
5165 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5166 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5167 if (LBO->getOpcode() == Instruction::And &&
5168 LCI->getValue() == CI->getValue())
5169 if (const SCEVZeroExtendExpr *Z =
5170 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5171 Type *UTy = BO->LHS->getType();
5172 const SCEV *Z0 = Z->getOperand();
5173 Type *Z0Ty = Z0->getType();
5174 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005175
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005176 // If C is a low-bits mask, the zero extend is serving to
5177 // mask off the high bits. Complement the operand and
5178 // re-apply the zext.
5179 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5180 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5181
5182 // If C is a single bit, it may be in the sign-bit position
5183 // before the zero-extend. In this case, represent the xor
5184 // using an add, which is equivalent, and re-apply the zext.
5185 APInt Trunc = CI->getValue().trunc(Z0TySize);
5186 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5187 Trunc.isSignBit())
5188 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5189 UTy);
5190 }
5191 }
5192 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005193
5194 case Instruction::Shl:
5195 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005196 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5197 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005198
5199 // If the shift count is not less than the bitwidth, the result of
5200 // the shift is undefined. Don't try to analyze it, because the
5201 // resolution chosen here may differ from the resolution chosen in
5202 // other parts of the compiler.
5203 if (SA->getValue().uge(BitWidth))
5204 break;
5205
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005206 // It is currently not resolved how to interpret NSW for left
5207 // shift by BitWidth - 1, so we avoid applying flags in that
5208 // case. Remove this check (or this comment) once the situation
5209 // is resolved. See
5210 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5211 // and http://reviews.llvm.org/D8890 .
5212 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005213 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5214 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005215
Owen Andersonedb4a702009-07-24 23:12:02 +00005216 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005217 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005218 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005219 }
5220 break;
5221
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005222 case Instruction::AShr:
5223 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5224 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5225 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5226 if (L->getOpcode() == Instruction::Shl &&
5227 L->getOperand(1) == BO->RHS) {
5228 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005229
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005230 // If the shift count is not less than the bitwidth, the result of
5231 // the shift is undefined. Don't try to analyze it, because the
5232 // resolution chosen here may differ from the resolution chosen in
5233 // other parts of the compiler.
5234 if (CI->getValue().uge(BitWidth))
5235 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005236
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005237 uint64_t Amt = BitWidth - CI->getZExtValue();
5238 if (Amt == BitWidth)
5239 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5240 return getSignExtendExpr(
5241 getTruncateExpr(getSCEV(L->getOperand(0)),
5242 IntegerType::get(getContext(), Amt)),
5243 BO->LHS->getType());
5244 }
5245 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005246 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005247 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005248
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005249 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005250 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005251 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005252
5253 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005254 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005255
5256 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005257 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005258
5259 case Instruction::BitCast:
5260 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005261 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005262 return getSCEV(U->getOperand(0));
5263 break;
5264
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005265 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5266 // lead to pointer expressions which cannot safely be expanded to GEPs,
5267 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5268 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005269
Dan Gohmanee750d12009-05-08 20:26:55 +00005270 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005271 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005272
Dan Gohman05e89732008-06-22 19:56:46 +00005273 case Instruction::PHI:
5274 return createNodeForPHI(cast<PHINode>(U));
5275
5276 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005277 // U can also be a select constant expr, which let fall through. Since
5278 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5279 // constant expressions cannot have instructions as operands, we'd have
5280 // returned getUnknown for a select constant expressions anyway.
5281 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005282 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5283 U->getOperand(1), U->getOperand(2));
Chris Lattnerd934c702004-04-02 20:23:17 +00005284 }
5285
Dan Gohmanc8e23622009-04-21 23:15:49 +00005286 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005287}
5288
5289
5290
5291//===----------------------------------------------------------------------===//
5292// Iteration Count Computation Code
5293//
5294
Chandler Carruth6666c272014-10-11 00:12:11 +00005295unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5296 if (BasicBlock *ExitingBB = L->getExitingBlock())
5297 return getSmallConstantTripCount(L, ExitingBB);
5298
5299 // No trip count information for multiple exits.
5300 return 0;
5301}
5302
Andrew Trick2b6860f2011-08-11 23:36:16 +00005303/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00005304/// normal unsigned value. Returns 0 if the trip count is unknown or not
5305/// constant. Will also return 0 if the maximum trip count is very large (>=
5306/// 2^32).
5307///
5308/// This "trip count" assumes that control exits via ExitingBlock. More
5309/// precisely, it is the number of times that control may reach ExitingBlock
5310/// before taking the branch. For loops with multiple exits, it may not be the
5311/// number times that the loop header executes because the loop may exit
5312/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005313unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5314 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005315 assert(ExitingBlock && "Must pass a non-null exiting block!");
5316 assert(L->isLoopExiting(ExitingBlock) &&
5317 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005318 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005319 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005320 if (!ExitCount)
5321 return 0;
5322
5323 ConstantInt *ExitConst = ExitCount->getValue();
5324
5325 // Guard against huge trip counts.
5326 if (ExitConst->getValue().getActiveBits() > 32)
5327 return 0;
5328
5329 // In case of integer overflow, this returns 0, which is correct.
5330 return ((unsigned)ExitConst->getZExtValue()) + 1;
5331}
5332
Chandler Carruth6666c272014-10-11 00:12:11 +00005333unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5334 if (BasicBlock *ExitingBB = L->getExitingBlock())
5335 return getSmallConstantTripMultiple(L, ExitingBB);
5336
5337 // No trip multiple information for multiple exits.
5338 return 0;
5339}
5340
Andrew Trick2b6860f2011-08-11 23:36:16 +00005341/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
5342/// trip count of this loop as a normal unsigned value, if possible. This
5343/// means that the actual trip count is always a multiple of the returned
5344/// value (don't forget the trip count could very well be zero as well!).
5345///
5346/// Returns 1 if the trip count is unknown or not guaranteed to be the
5347/// multiple of a constant (which is also the case if the trip count is simply
5348/// constant, use getSmallConstantTripCount for that case), Will also return 1
5349/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005350///
5351/// As explained in the comments for getSmallConstantTripCount, this assumes
5352/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005353unsigned
5354ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5355 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005356 assert(ExitingBlock && "Must pass a non-null exiting block!");
5357 assert(L->isLoopExiting(ExitingBlock) &&
5358 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005359 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005360 if (ExitCount == getCouldNotCompute())
5361 return 1;
5362
5363 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005364 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005365 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5366 // to factor simple cases.
5367 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5368 TCMul = Mul->getOperand(0);
5369
5370 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5371 if (!MulC)
5372 return 1;
5373
5374 ConstantInt *Result = MulC->getValue();
5375
Hal Finkel30bd9342012-10-24 19:46:44 +00005376 // Guard against huge trip counts (this requires checking
5377 // for zero to handle the case where the trip count == -1 and the
5378 // addition wraps).
5379 if (!Result || Result->getValue().getActiveBits() > 32 ||
5380 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005381 return 1;
5382
5383 return (unsigned)Result->getZExtValue();
5384}
5385
Andrew Trick3ca3f982011-07-26 17:19:55 +00005386// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00005387// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00005388// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005389const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5390 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005391}
5392
Silviu Baranga6f444df2016-04-08 14:29:09 +00005393const SCEV *
5394ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5395 SCEVUnionPredicate &Preds) {
5396 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5397}
5398
Dan Gohman0bddac12009-02-24 18:55:53 +00005399/// getBackedgeTakenCount - If the specified loop has a predictable
5400/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
5401/// object. The backedge-taken count is the number of times the loop header
5402/// will be branched to from within the loop. This is one less than the
5403/// trip count of the loop, since it doesn't count the first iteration,
5404/// when the header is branched to from outside the loop.
5405///
5406/// Note that it is not valid to call this method on a loop without a
5407/// loop-invariant backedge-taken count (see
5408/// hasLoopInvariantBackedgeTakenCount).
5409///
Dan Gohmanaf752342009-07-07 17:06:11 +00005410const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005411 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005412}
5413
5414/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
5415/// return the least SCEV value that is known never to be less than the
5416/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005417const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005418 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005419}
5420
Dan Gohmandc191042009-07-08 19:23:34 +00005421/// PushLoopPHIs - Push PHI nodes in the header of the given loop
5422/// onto the given Worklist.
5423static void
5424PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5425 BasicBlock *Header = L->getHeader();
5426
5427 // Push all Loop-header PHIs onto the Worklist stack.
5428 for (BasicBlock::iterator I = Header->begin();
5429 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5430 Worklist.push_back(PN);
5431}
5432
Dan Gohman2b8da352009-04-30 20:47:05 +00005433const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005434ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5435 auto &BTI = getBackedgeTakenInfo(L);
5436 if (BTI.hasFullInfo())
5437 return BTI;
5438
5439 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5440
5441 if (!Pair.second)
5442 return Pair.first->second;
5443
5444 BackedgeTakenInfo Result =
5445 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5446
5447 return PredicatedBackedgeTakenCounts.find(L)->second = Result;
5448}
5449
5450const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005451ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005452 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005453 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005454 // update the value. The temporary CouldNotCompute value tells SCEV
5455 // code elsewhere that it shouldn't attempt to request a new
5456 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005457 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005458 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005459 if (!Pair.second)
5460 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005461
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005462 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005463 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5464 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005465 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005466
5467 if (Result.getExact(this) != getCouldNotCompute()) {
5468 assert(isLoopInvariant(Result.getExact(this), L) &&
5469 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005470 "Computed backedge-taken count isn't loop invariant for loop!");
5471 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005472 }
5473 else if (Result.getMax(this) == getCouldNotCompute() &&
5474 isa<PHINode>(L->getHeader()->begin())) {
5475 // Only count loops that have phi nodes as not being computable.
5476 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005477 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005478
Chris Lattnera337f5e2011-01-09 02:16:18 +00005479 // Now that we know more about the trip count for this loop, forget any
5480 // existing SCEV values for PHI nodes in this loop since they are only
5481 // conservative estimates made without the benefit of trip count
5482 // information. This is similar to the code in forgetLoop, except that
5483 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005484 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005485 SmallVector<Instruction *, 16> Worklist;
5486 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005487
Chris Lattnera337f5e2011-01-09 02:16:18 +00005488 SmallPtrSet<Instruction *, 8> Visited;
5489 while (!Worklist.empty()) {
5490 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005491 if (!Visited.insert(I).second)
5492 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005493
Chris Lattnera337f5e2011-01-09 02:16:18 +00005494 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005495 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005496 if (It != ValueExprMap.end()) {
5497 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005498
Chris Lattnera337f5e2011-01-09 02:16:18 +00005499 // SCEVUnknown for a PHI either means that it has an unrecognized
5500 // structure, or it's a PHI that's in the progress of being computed
5501 // by createNodeForPHI. In the former case, additional loop trip
5502 // count information isn't going to change anything. In the later
5503 // case, createNodeForPHI will perform the necessary updates on its
5504 // own when it gets to that point.
5505 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5506 forgetMemoizedResults(Old);
5507 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005508 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005509 if (PHINode *PN = dyn_cast<PHINode>(I))
5510 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005511 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005512
5513 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005514 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005515 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005516
5517 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005518 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005519 // recusive call to getBackedgeTakenInfo (on a different
5520 // loop), which would invalidate the iterator computed
5521 // earlier.
5522 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00005523}
5524
Dan Gohman880c92a2009-10-31 15:04:55 +00005525/// forgetLoop - This method should be called by the client when it has
5526/// changed a loop in a way that may effect ScalarEvolution's ability to
5527/// compute a trip count, or if the loop is deleted.
5528void ScalarEvolution::forgetLoop(const Loop *L) {
5529 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005530 auto RemoveLoopFromBackedgeMap =
5531 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5532 auto BTCPos = Map.find(L);
5533 if (BTCPos != Map.end()) {
5534 BTCPos->second.clear();
5535 Map.erase(BTCPos);
5536 }
5537 };
5538
5539 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5540 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005541
Dan Gohman880c92a2009-10-31 15:04:55 +00005542 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005543 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005544 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005545
Dan Gohmandc191042009-07-08 19:23:34 +00005546 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005547 while (!Worklist.empty()) {
5548 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005549 if (!Visited.insert(I).second)
5550 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005551
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005552 ValueExprMapType::iterator It =
5553 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005554 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005555 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005556 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005557 if (PHINode *PN = dyn_cast<PHINode>(I))
5558 ConstantEvolutionLoopExitValue.erase(PN);
5559 }
5560
5561 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005562 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005563
5564 // Forget all contained loops too, to avoid dangling entries in the
5565 // ValuesAtScopes map.
5566 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5567 forgetLoop(*I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005568
5569 LoopMayThrow.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005570}
5571
Eric Christopheref6d5932010-07-29 01:25:38 +00005572/// forgetValue - This method should be called by the client when it has
5573/// changed a value in a way that may effect its value, or which may
5574/// disconnect it from a def-use chain linking it to a loop.
5575void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005576 Instruction *I = dyn_cast<Instruction>(V);
5577 if (!I) return;
5578
5579 // Drop information about expressions based on loop-header PHIs.
5580 SmallVector<Instruction *, 16> Worklist;
5581 Worklist.push_back(I);
5582
5583 SmallPtrSet<Instruction *, 8> Visited;
5584 while (!Worklist.empty()) {
5585 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005586 if (!Visited.insert(I).second)
5587 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005588
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005589 ValueExprMapType::iterator It =
5590 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005591 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005592 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005593 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005594 if (PHINode *PN = dyn_cast<PHINode>(I))
5595 ConstantEvolutionLoopExitValue.erase(PN);
5596 }
5597
5598 PushDefUseChildren(I, Worklist);
5599 }
5600}
5601
Andrew Trick3ca3f982011-07-26 17:19:55 +00005602/// getExact - Get the exact loop backedge taken count considering all loop
Sanjoy Das135e5b92015-07-21 20:59:22 +00005603/// exits. A computable result can only be returned for loops with a single
5604/// exit. Returning the minimum taken count among all exits is incorrect
5605/// because one of the loop's exit limit's may have been skipped. HowFarToZero
5606/// assumes that the limit of each loop test is never skipped. This is a valid
5607/// assumption as long as the loop exits via that test. For precise results, it
5608/// is the caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005609/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005610const SCEV *
Silviu Baranga6f444df2016-04-08 14:29:09 +00005611ScalarEvolution::BackedgeTakenInfo::getExact(
5612 ScalarEvolution *SE, SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005613 // If any exits were not computable, the loop is not computable.
5614 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5615
Andrew Trick90c7a102011-11-16 00:52:40 +00005616 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005617 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005618 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5619
Craig Topper9f008862014-04-15 04:59:12 +00005620 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005621 for (auto &ENT : ExitNotTaken) {
5622 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005623
5624 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005625 BECount = ENT.ExactNotTaken;
5626 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005627 return SE->getCouldNotCompute();
Silviu Baranga6f444df2016-04-08 14:29:09 +00005628 if (Preds && ENT.getPred())
5629 Preds->add(ENT.getPred());
5630
5631 assert((Preds || ENT.hasAlwaysTruePred()) &&
5632 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005633 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005634
Andrew Trickbbb226a2011-09-02 21:20:46 +00005635 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005636 return BECount;
5637}
5638
5639/// getExact - Get the exact not taken count for this loop exit.
5640const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005641ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005642 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005643 for (auto &ENT : ExitNotTaken)
5644 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePred())
5645 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005646
Andrew Trick3ca3f982011-07-26 17:19:55 +00005647 return SE->getCouldNotCompute();
5648}
5649
5650/// getMax - Get the max backedge taken count for the loop.
5651const SCEV *
5652ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005653 for (auto &ENT : ExitNotTaken)
5654 if (!ENT.hasAlwaysTruePred())
5655 return SE->getCouldNotCompute();
5656
Andrew Trick3ca3f982011-07-26 17:19:55 +00005657 return Max ? Max : SE->getCouldNotCompute();
5658}
5659
Andrew Trick9093e152013-03-26 03:14:53 +00005660bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5661 ScalarEvolution *SE) const {
5662 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5663 return true;
5664
5665 if (!ExitNotTaken.ExitingBlock)
5666 return false;
5667
Silviu Baranga6f444df2016-04-08 14:29:09 +00005668 for (auto &ENT : ExitNotTaken)
5669 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5670 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005671 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005672
Andrew Trick9093e152013-03-26 03:14:53 +00005673 return false;
5674}
5675
Andrew Trick3ca3f982011-07-26 17:19:55 +00005676/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5677/// computable exit into a persistent ExitNotTakenInfo array.
5678ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Silviu Baranga6f444df2016-04-08 14:29:09 +00005679 SmallVectorImpl<EdgeInfo> &ExitCounts, bool Complete, const SCEV *MaxCount)
5680 : Max(MaxCount) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005681
5682 if (!Complete)
5683 ExitNotTaken.setIncomplete();
5684
5685 unsigned NumExits = ExitCounts.size();
5686 if (NumExits == 0) return;
5687
Silviu Baranga6f444df2016-04-08 14:29:09 +00005688 ExitNotTaken.ExitingBlock = ExitCounts[0].ExitBlock;
5689 ExitNotTaken.ExactNotTaken = ExitCounts[0].Taken;
5690
5691 // Determine the number of ExitNotTakenExtras structures that we need.
5692 unsigned ExtraInfoSize = 0;
5693 if (NumExits > 1)
5694 ExtraInfoSize = 1 + std::count_if(std::next(ExitCounts.begin()),
5695 ExitCounts.end(), [](EdgeInfo &Entry) {
5696 return !Entry.Pred.isAlwaysTrue();
5697 });
5698 else if (!ExitCounts[0].Pred.isAlwaysTrue())
5699 ExtraInfoSize = 1;
5700
5701 ExitNotTakenExtras *ENT = nullptr;
5702
5703 // Allocate the ExitNotTakenExtras structures and initialize the first
5704 // element (ExitNotTaken).
5705 if (ExtraInfoSize > 0) {
5706 ENT = new ExitNotTakenExtras[ExtraInfoSize];
5707 ExitNotTaken.ExtraInfo = &ENT[0];
5708 *ExitNotTaken.getPred() = std::move(ExitCounts[0].Pred);
5709 }
5710
5711 if (NumExits == 1)
5712 return;
5713
Silviu Baranga24dbd2e2016-05-13 14:54:50 +00005714 assert(ENT && "ExitNotTakenExtras is NULL while having more than one exit");
5715
Silviu Baranga6f444df2016-04-08 14:29:09 +00005716 auto &Exits = ExitNotTaken.ExtraInfo->Exits;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005717
5718 // Handle the rare case of multiple computable exits.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005719 for (unsigned i = 1, PredPos = 1; i < NumExits; ++i) {
5720 ExitNotTakenExtras *Ptr = nullptr;
5721 if (!ExitCounts[i].Pred.isAlwaysTrue()) {
5722 Ptr = &ENT[PredPos++];
5723 Ptr->Pred = std::move(ExitCounts[i].Pred);
5724 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005725
Silviu Baranga6f444df2016-04-08 14:29:09 +00005726 Exits.emplace_back(ExitCounts[i].ExitBlock, ExitCounts[i].Taken, Ptr);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005727 }
5728}
5729
5730/// clear - Invalidate this result and free the ExitNotTakenInfo array.
5731void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005732 ExitNotTaken.ExitingBlock = nullptr;
5733 ExitNotTaken.ExactNotTaken = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005734 delete[] ExitNotTaken.ExtraInfo;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005735}
5736
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005737/// computeBackedgeTakenCount - Compute the number of times the backedge
Dan Gohman0bddac12009-02-24 18:55:53 +00005738/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005739ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005740ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5741 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005742 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005743 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005744
Silviu Baranga6f444df2016-04-08 14:29:09 +00005745 SmallVector<EdgeInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005746 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005747 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005748 const SCEV *MustExitMaxBECount = nullptr;
5749 const SCEV *MayExitMaxBECount = nullptr;
5750
5751 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5752 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005753 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005754 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005755 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005756 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5757
5758 assert((AllowPredicates || EL.Pred.isAlwaysTrue()) &&
5759 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005760
5761 // 1. For each exit that can be computed, add an entry to ExitCounts.
5762 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005763 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005764 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005765 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005766 CouldComputeBECount = false;
5767 else
Silviu Baranga6f444df2016-04-08 14:29:09 +00005768 ExitCounts.emplace_back(EdgeInfo(ExitBB, EL.Exact, EL.Pred));
Andrew Trick3ca3f982011-07-26 17:19:55 +00005769
Andrew Trick839e30b2014-05-23 19:47:13 +00005770 // 2. Derive the loop's MaxBECount from each exit's max number of
5771 // non-exiting iterations. Partition the loop exits into two kinds:
5772 // LoopMustExits and LoopMayExits.
5773 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005774 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5775 // is a LoopMayExit. If any computable LoopMustExit is found, then
5776 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5777 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5778 // considered greater than any computable EL.Max.
5779 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005780 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005781 if (!MustExitMaxBECount)
5782 MustExitMaxBECount = EL.Max;
5783 else {
5784 MustExitMaxBECount =
5785 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005786 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005787 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5788 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5789 MayExitMaxBECount = EL.Max;
5790 else {
5791 MayExitMaxBECount =
5792 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5793 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005794 }
Dan Gohman96212b62009-06-22 00:31:57 +00005795 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005796 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5797 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005798 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005799}
5800
Andrew Trick3ca3f982011-07-26 17:19:55 +00005801ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005802ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5803 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005804
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005805 // Okay, we've chosen an exiting block. See what condition causes us to exit
5806 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005807 // lead to the loop header.
5808 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005809 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005810 for (auto *SBB : successors(ExitingBlock))
5811 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005812 if (Exit) // Multiple exit successors.
5813 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005814 Exit = SBB;
5815 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005816 MustExecuteLoopHeader = false;
5817 }
Dan Gohmance973df2009-06-24 04:48:43 +00005818
Chris Lattner18954852007-01-07 02:24:26 +00005819 // At this point, we know we have a conditional branch that determines whether
5820 // the loop is exited. However, we don't know if the branch is executed each
5821 // time through the loop. If not, then the execution count of the branch will
5822 // not be equal to the trip count of the loop.
5823 //
5824 // Currently we check for this by checking to see if the Exit branch goes to
5825 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005826 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005827 // loop header. This is common for un-rotated loops.
5828 //
5829 // If both of those tests fail, walk up the unique predecessor chain to the
5830 // header, stopping if there is an edge that doesn't exit the loop. If the
5831 // header is reached, the execution count of the branch will be equal to the
5832 // trip count of the loop.
5833 //
5834 // More extensive analysis could be done to handle more cases here.
5835 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005836 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005837 // The simple checks failed, try climbing the unique predecessor chain
5838 // up to the header.
5839 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005840 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005841 BasicBlock *Pred = BB->getUniquePredecessor();
5842 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005843 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005844 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005845 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005846 if (PredSucc == BB)
5847 continue;
5848 // If the predecessor has a successor that isn't BB and isn't
5849 // outside the loop, assume the worst.
5850 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005851 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005852 }
5853 if (Pred == L->getHeader()) {
5854 Ok = true;
5855 break;
5856 }
5857 BB = Pred;
5858 }
5859 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005860 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005861 }
5862
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005863 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005864 TerminatorInst *Term = ExitingBlock->getTerminator();
5865 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5866 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5867 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005868 return computeExitLimitFromCond(
5869 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5870 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005871 }
5872
5873 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005874 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005875 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005876
5877 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005878}
5879
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005880/// computeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005881/// backedge of the specified loop will execute if its exit condition
5882/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00005883///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005884/// @param ControlsExit is true if ExitCond directly controls the exit
5885/// branch. In this case, we can assume that the loop exits only if the
5886/// condition is true and can infer that failing to meet the condition prior to
5887/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005888ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005889ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005890 Value *ExitCond,
5891 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005892 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005893 bool ControlsExit,
5894 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005895 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005896 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5897 if (BO->getOpcode() == Instruction::And) {
5898 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005899 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005900 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005901 ControlsExit && !EitherMayExit,
5902 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005903 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005904 ControlsExit && !EitherMayExit,
5905 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005906 const SCEV *BECount = getCouldNotCompute();
5907 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005908 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005909 // Both conditions must be true for the loop to continue executing.
5910 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005911 if (EL0.Exact == getCouldNotCompute() ||
5912 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005913 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005914 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005915 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5916 if (EL0.Max == getCouldNotCompute())
5917 MaxBECount = EL1.Max;
5918 else if (EL1.Max == getCouldNotCompute())
5919 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005920 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005921 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005922 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005923 // Both conditions must be true at the same time for the loop to exit.
5924 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005925 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005926 if (EL0.Max == EL1.Max)
5927 MaxBECount = EL0.Max;
5928 if (EL0.Exact == EL1.Exact)
5929 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005930 }
5931
Silviu Baranga6f444df2016-04-08 14:29:09 +00005932 SCEVUnionPredicate NP;
5933 NP.add(&EL0.Pred);
5934 NP.add(&EL1.Pred);
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005935 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5936 // to be more aggressive when computing BECount than when computing
5937 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact
5938 // to match, but for EL0.Max and EL1.Max to not.
5939 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5940 !isa<SCEVCouldNotCompute>(BECount))
5941 MaxBECount = BECount;
5942
Silviu Baranga6f444df2016-04-08 14:29:09 +00005943 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005944 }
5945 if (BO->getOpcode() == Instruction::Or) {
5946 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005947 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005948 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005949 ControlsExit && !EitherMayExit,
5950 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005951 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005952 ControlsExit && !EitherMayExit,
5953 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005954 const SCEV *BECount = getCouldNotCompute();
5955 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005956 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005957 // Both conditions must be false for the loop to continue executing.
5958 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005959 if (EL0.Exact == getCouldNotCompute() ||
5960 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005961 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005962 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005963 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5964 if (EL0.Max == getCouldNotCompute())
5965 MaxBECount = EL1.Max;
5966 else if (EL1.Max == getCouldNotCompute())
5967 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005968 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005969 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005970 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005971 // Both conditions must be false at the same time for the loop to exit.
5972 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005973 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005974 if (EL0.Max == EL1.Max)
5975 MaxBECount = EL0.Max;
5976 if (EL0.Exact == EL1.Exact)
5977 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005978 }
5979
Silviu Baranga6f444df2016-04-08 14:29:09 +00005980 SCEVUnionPredicate NP;
5981 NP.add(&EL0.Pred);
5982 NP.add(&EL1.Pred);
5983 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005984 }
5985 }
5986
5987 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005988 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005989 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5990 ExitLimit EL =
5991 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5992 if (EL.hasFullInfo() || !AllowPredicates)
5993 return EL;
5994
5995 // Try again, but use SCEV predicates this time.
5996 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5997 /*AllowPredicates=*/true);
5998 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005999
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006000 // Check for a constant condition. These are normally stripped out by
6001 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6002 // preserve the CFG and is temporarily leaving constant conditions
6003 // in place.
6004 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6005 if (L->contains(FBB) == !CI->getZExtValue())
6006 // The backedge is always taken.
6007 return getCouldNotCompute();
6008 else
6009 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006010 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006011 }
6012
Eli Friedmanebf98b02009-05-09 12:32:42 +00006013 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006014 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006015}
6016
Andrew Trick3ca3f982011-07-26 17:19:55 +00006017ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006018ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006019 ICmpInst *ExitCond,
6020 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006021 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006022 bool ControlsExit,
6023 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006024
Reid Spencer266e42b2006-12-23 06:05:41 +00006025 // If the condition was exit on true, convert the condition to exit on false
6026 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006027 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006028 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006029 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006030 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006031
6032 // Handle common loops like: for (X = "string"; *X; ++X)
6033 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6034 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006035 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006036 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006037 if (ItCnt.hasAnyInfo())
6038 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006039 }
6040
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006041 ExitLimit ShiftEL = computeShiftCompareExitLimit(
6042 ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond);
6043 if (ShiftEL.hasAnyInfo())
6044 return ShiftEL;
6045
Dan Gohmanaf752342009-07-07 17:06:11 +00006046 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6047 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006048
6049 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006050 LHS = getSCEVAtScope(LHS, L);
6051 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006052
Dan Gohmance973df2009-06-24 04:48:43 +00006053 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006054 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006055 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006056 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006057 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006058 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006059 }
6060
Dan Gohman81585c12010-05-03 16:35:17 +00006061 // Simplify the operands before analyzing them.
6062 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6063
Chris Lattnerd934c702004-04-02 20:23:17 +00006064 // If we have a comparison of a chrec against a constant, try to use value
6065 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006066 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6067 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006068 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006069 // Form the constant range.
6070 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006071 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00006072
Dan Gohmanaf752342009-07-07 17:06:11 +00006073 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006074 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006075 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006076
Chris Lattnerd934c702004-04-02 20:23:17 +00006077 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006078 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006079 // Convert to: while (X-Y != 0)
Silviu Baranga6f444df2016-04-08 14:29:09 +00006080 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6081 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006082 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006083 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006084 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006085 case ICmpInst::ICMP_EQ: { // while (X == Y)
6086 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00006087 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
6088 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006089 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006090 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006091 case ICmpInst::ICMP_SLT:
6092 case ICmpInst::ICMP_ULT: { // while (X < Y)
6093 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006094 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6095 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006096 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006097 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006098 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006099 case ICmpInst::ICMP_SGT:
6100 case ICmpInst::ICMP_UGT: { // while (X > Y)
6101 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006102 ExitLimit EL =
6103 HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6104 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006105 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006106 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006107 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006108 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006109 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006110 }
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006111 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00006112}
6113
Benjamin Kramer5a188542014-02-11 15:44:32 +00006114ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006115ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006116 SwitchInst *Switch,
6117 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006118 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006119 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6120
6121 // Give up if the exit is the default dest of a switch.
6122 if (Switch->getDefaultDest() == ExitingBlock)
6123 return getCouldNotCompute();
6124
6125 assert(L->contains(Switch->getDefaultDest()) &&
6126 "Default case must not exit the loop!");
6127 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6128 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6129
6130 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006131 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006132 if (EL.hasAnyInfo())
6133 return EL;
6134
6135 return getCouldNotCompute();
6136}
6137
Chris Lattnerec901cc2004-10-12 01:49:27 +00006138static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006139EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6140 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006141 const SCEV *InVal = SE.getConstant(C);
6142 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006143 assert(isa<SCEVConstant>(Val) &&
6144 "Evaluation of SCEV at constant didn't fold correctly?");
6145 return cast<SCEVConstant>(Val)->getValue();
6146}
6147
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006148/// computeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00006149/// 'icmp op load X, cst', try to see if we can compute the backedge
6150/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006151ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006152ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006153 LoadInst *LI,
6154 Constant *RHS,
6155 const Loop *L,
6156 ICmpInst::Predicate predicate) {
6157
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006158 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006159
6160 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006161 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006162 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006163 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006164
6165 // Make sure that it is really a constant global we are gepping, with an
6166 // initializer, and make sure the first IDX is really 0.
6167 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006168 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006169 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6170 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006171 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006172
6173 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006174 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006175 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006176 unsigned VarIdxNum = 0;
6177 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6178 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6179 Indexes.push_back(CI);
6180 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006181 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006182 VarIdx = GEP->getOperand(i);
6183 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006184 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006185 }
6186
Andrew Trick7004e4b2012-03-26 22:33:59 +00006187 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6188 if (!VarIdx)
6189 return getCouldNotCompute();
6190
Chris Lattnerec901cc2004-10-12 01:49:27 +00006191 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6192 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006193 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006194 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006195
6196 // We can only recognize very limited forms of loop index expressions, in
6197 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006198 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006199 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006200 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6201 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006202 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006203
6204 unsigned MaxSteps = MaxBruteForceIterations;
6205 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006206 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006207 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006208 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006209
6210 // Form the GEP offset.
6211 Indexes[VarIdxNum] = Val;
6212
Chris Lattnere166a852012-01-24 05:49:24 +00006213 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6214 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006215 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006216
6217 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006218 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006219 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006220 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006221 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006222 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006223 }
6224 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006225 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006226}
6227
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006228ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6229 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6230 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6231 if (!RHS)
6232 return getCouldNotCompute();
6233
6234 const BasicBlock *Latch = L->getLoopLatch();
6235 if (!Latch)
6236 return getCouldNotCompute();
6237
6238 const BasicBlock *Predecessor = L->getLoopPredecessor();
6239 if (!Predecessor)
6240 return getCouldNotCompute();
6241
6242 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6243 // Return LHS in OutLHS and shift_opt in OutOpCode.
6244 auto MatchPositiveShift =
6245 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6246
6247 using namespace PatternMatch;
6248
6249 ConstantInt *ShiftAmt;
6250 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6251 OutOpCode = Instruction::LShr;
6252 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6253 OutOpCode = Instruction::AShr;
6254 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6255 OutOpCode = Instruction::Shl;
6256 else
6257 return false;
6258
6259 return ShiftAmt->getValue().isStrictlyPositive();
6260 };
6261
6262 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6263 //
6264 // loop:
6265 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6266 // %iv.shifted = lshr i32 %iv, <positive constant>
6267 //
6268 // Return true on a succesful match. Return the corresponding PHI node (%iv
6269 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6270 auto MatchShiftRecurrence =
6271 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6272 Optional<Instruction::BinaryOps> PostShiftOpCode;
6273
6274 {
6275 Instruction::BinaryOps OpC;
6276 Value *V;
6277
6278 // If we encounter a shift instruction, "peel off" the shift operation,
6279 // and remember that we did so. Later when we inspect %iv's backedge
6280 // value, we will make sure that the backedge value uses the same
6281 // operation.
6282 //
6283 // Note: the peeled shift operation does not have to be the same
6284 // instruction as the one feeding into the PHI's backedge value. We only
6285 // really care about it being the same *kind* of shift instruction --
6286 // that's all that is required for our later inferences to hold.
6287 if (MatchPositiveShift(LHS, V, OpC)) {
6288 PostShiftOpCode = OpC;
6289 LHS = V;
6290 }
6291 }
6292
6293 PNOut = dyn_cast<PHINode>(LHS);
6294 if (!PNOut || PNOut->getParent() != L->getHeader())
6295 return false;
6296
6297 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6298 Value *OpLHS;
6299
6300 return
6301 // The backedge value for the PHI node must be a shift by a positive
6302 // amount
6303 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6304
6305 // of the PHI node itself
6306 OpLHS == PNOut &&
6307
6308 // and the kind of shift should be match the kind of shift we peeled
6309 // off, if any.
6310 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6311 };
6312
6313 PHINode *PN;
6314 Instruction::BinaryOps OpCode;
6315 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6316 return getCouldNotCompute();
6317
6318 const DataLayout &DL = getDataLayout();
6319
6320 // The key rationale for this optimization is that for some kinds of shift
6321 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6322 // within a finite number of iterations. If the condition guarding the
6323 // backedge (in the sense that the backedge is taken if the condition is true)
6324 // is false for the value the shift recurrence stabilizes to, then we know
6325 // that the backedge is taken only a finite number of times.
6326
6327 ConstantInt *StableValue = nullptr;
6328 switch (OpCode) {
6329 default:
6330 llvm_unreachable("Impossible case!");
6331
6332 case Instruction::AShr: {
6333 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6334 // bitwidth(K) iterations.
6335 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6336 bool KnownZero, KnownOne;
6337 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6338 Predecessor->getTerminator(), &DT);
6339 auto *Ty = cast<IntegerType>(RHS->getType());
6340 if (KnownZero)
6341 StableValue = ConstantInt::get(Ty, 0);
6342 else if (KnownOne)
6343 StableValue = ConstantInt::get(Ty, -1, true);
6344 else
6345 return getCouldNotCompute();
6346
6347 break;
6348 }
6349 case Instruction::LShr:
6350 case Instruction::Shl:
6351 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6352 // stabilize to 0 in at most bitwidth(K) iterations.
6353 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6354 break;
6355 }
6356
6357 auto *Result =
6358 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6359 assert(Result->getType()->isIntegerTy(1) &&
6360 "Otherwise cannot be an operand to a branch instruction");
6361
6362 if (Result->isZeroValue()) {
6363 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6364 const SCEV *UpperBound =
6365 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
Silviu Baranga6f444df2016-04-08 14:29:09 +00006366 SCEVUnionPredicate P;
6367 return ExitLimit(getCouldNotCompute(), UpperBound, P);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006368 }
6369
6370 return getCouldNotCompute();
6371}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006372
Chris Lattnerdd730472004-04-17 22:58:41 +00006373/// CanConstantFold - Return true if we can constant fold an instruction of the
6374/// specified type, assuming that all operands were constants.
6375static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006376 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006377 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6378 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006379 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006380
Chris Lattnerdd730472004-04-17 22:58:41 +00006381 if (const CallInst *CI = dyn_cast<CallInst>(I))
6382 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006383 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006384 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006385}
6386
Andrew Trick3a86ba72011-10-05 03:25:31 +00006387/// Determine whether this instruction can constant evolve within this loop
6388/// assuming its operands can all constant evolve.
6389static bool canConstantEvolve(Instruction *I, const Loop *L) {
6390 // An instruction outside of the loop can't be derived from a loop PHI.
6391 if (!L->contains(I)) return false;
6392
6393 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006394 // We don't currently keep track of the control flow needed to evaluate
6395 // PHIs, so we cannot handle PHIs inside of loops.
6396 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006397 }
6398
6399 // If we won't be able to constant fold this expression even if the operands
6400 // are constants, bail early.
6401 return CanConstantFold(I);
6402}
6403
6404/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6405/// recursing through each instruction operand until reaching a loop header phi.
6406static PHINode *
6407getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006408 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006409
6410 // Otherwise, we can evaluate this instruction if all of its operands are
6411 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006412 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006413 for (Value *Op : UseInst->operands()) {
6414 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006415
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006416 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006417 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006418
6419 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006420 if (!P)
6421 // If this operand is already visited, reuse the prior result.
6422 // We may have P != PHI if this is the deepest point at which the
6423 // inconsistent paths meet.
6424 P = PHIMap.lookup(OpInst);
6425 if (!P) {
6426 // Recurse and memoize the results, whether a phi is found or not.
6427 // This recursive call invalidates pointers into PHIMap.
6428 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6429 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006430 }
Craig Topper9f008862014-04-15 04:59:12 +00006431 if (!P)
6432 return nullptr; // Not evolving from PHI
6433 if (PHI && PHI != P)
6434 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006435 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006436 }
6437 // This is a expression evolving from a constant PHI!
6438 return PHI;
6439}
6440
Chris Lattnerdd730472004-04-17 22:58:41 +00006441/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6442/// in the loop that V is derived from. We allow arbitrary operations along the
6443/// way, but the operands of an operation must either be constants or a value
6444/// derived from a constant PHI. If this expression does not fit with these
6445/// constraints, return null.
6446static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006447 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006448 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006449
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006450 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006451 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006452
Andrew Trick3a86ba72011-10-05 03:25:31 +00006453 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006454 DenseMap<Instruction *, PHINode *> PHIMap;
6455 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006456}
6457
6458/// EvaluateExpression - Given an expression that passes the
6459/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6460/// in the loop has the value PHIVal. If we can't fold this expression for some
6461/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006462static Constant *EvaluateExpression(Value *V, const Loop *L,
6463 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006464 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006465 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006466 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006467 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006468 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006469 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006470
Andrew Trick3a86ba72011-10-05 03:25:31 +00006471 if (Constant *C = Vals.lookup(I)) return C;
6472
Nick Lewyckya6674c72011-10-22 19:58:20 +00006473 // An instruction inside the loop depends on a value outside the loop that we
6474 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006475 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006476
6477 // An unmapped PHI can be due to a branch or another loop inside this loop,
6478 // or due to this not being the initial iteration through a loop where we
6479 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006480 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006481
Dan Gohmanf820bd32010-06-22 13:15:46 +00006482 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006483
6484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006485 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6486 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006487 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006488 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006489 continue;
6490 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006491 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006492 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006493 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006494 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006495 }
6496
Nick Lewyckya6674c72011-10-22 19:58:20 +00006497 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006498 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006499 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006500 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6501 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006502 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006503 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006504 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006505}
6506
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006507
6508// If every incoming value to PN except the one for BB is a specific Constant,
6509// return that, else return nullptr.
6510static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6511 Constant *IncomingVal = nullptr;
6512
6513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6514 if (PN->getIncomingBlock(i) == BB)
6515 continue;
6516
6517 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6518 if (!CurrentVal)
6519 return nullptr;
6520
6521 if (IncomingVal != CurrentVal) {
6522 if (IncomingVal)
6523 return nullptr;
6524 IncomingVal = CurrentVal;
6525 }
6526 }
6527
6528 return IncomingVal;
6529}
6530
Chris Lattnerdd730472004-04-17 22:58:41 +00006531/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6532/// in the header of its containing loop, we know the loop executes a
6533/// constant number of times, and the PHI node is just a recurrence
6534/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006535Constant *
6536ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006537 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006538 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006539 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006540 if (I != ConstantEvolutionLoopExitValue.end())
6541 return I->second;
6542
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006543 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006544 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006545
6546 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6547
Andrew Trick3a86ba72011-10-05 03:25:31 +00006548 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006549 BasicBlock *Header = L->getHeader();
6550 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006551
Sanjoy Dasdd709962015-10-08 18:28:36 +00006552 BasicBlock *Latch = L->getLoopLatch();
6553 if (!Latch)
6554 return nullptr;
6555
Sanjoy Das4493b402015-10-07 17:38:25 +00006556 for (auto &I : *Header) {
6557 PHINode *PHI = dyn_cast<PHINode>(&I);
6558 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006559 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006560 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006561 CurrentIterVals[PHI] = StartCST;
6562 }
6563 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006564 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006565
Sanjoy Dasdd709962015-10-08 18:28:36 +00006566 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006567
6568 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006569 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006570 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006571
Dan Gohman0bddac12009-02-24 18:55:53 +00006572 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006573 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006574 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006575 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006576 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006577 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006578
Nick Lewyckya6674c72011-10-22 19:58:20 +00006579 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006580 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006581 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006582 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006583 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006584 if (!NextPHI)
6585 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006586 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006587
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006588 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6589
Nick Lewyckya6674c72011-10-22 19:58:20 +00006590 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6591 // cease to be able to evaluate one of them or if they stop evolving,
6592 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006593 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006594 for (const auto &I : CurrentIterVals) {
6595 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006596 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006597 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006598 }
6599 // We use two distinct loops because EvaluateExpression may invalidate any
6600 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006601 for (const auto &I : PHIsToCompute) {
6602 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006603 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006604 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006605 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006606 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006607 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006608 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006609 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006610 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006611
6612 // If all entries in CurrentIterVals == NextIterVals then we can stop
6613 // iterating, the loop can't continue to change.
6614 if (StoppedEvolving)
6615 return RetVal = CurrentIterVals[PN];
6616
Andrew Trick3a86ba72011-10-05 03:25:31 +00006617 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006618 }
6619}
6620
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006621const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006622 Value *Cond,
6623 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006624 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006625 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006626
Dan Gohman866971e2010-06-19 14:17:24 +00006627 // If the loop is canonicalized, the PHI will have exactly two entries.
6628 // That's the only form we support here.
6629 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6630
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006631 DenseMap<Instruction *, Constant *> CurrentIterVals;
6632 BasicBlock *Header = L->getHeader();
6633 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6634
Sanjoy Dasdd709962015-10-08 18:28:36 +00006635 BasicBlock *Latch = L->getLoopLatch();
6636 assert(Latch && "Should follow from NumIncomingValues == 2!");
6637
Sanjoy Das4493b402015-10-07 17:38:25 +00006638 for (auto &I : *Header) {
6639 PHINode *PHI = dyn_cast<PHINode>(&I);
6640 if (!PHI)
6641 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006642 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006643 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006644 CurrentIterVals[PHI] = StartCST;
6645 }
6646 if (!CurrentIterVals.count(PN))
6647 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006648
6649 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6650 // the loop symbolically to determine when the condition gets a value of
6651 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006652 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006653 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006654 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006655 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006656 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006657
Zhou Sheng75b871f2007-01-11 12:24:14 +00006658 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006659 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006660
Reid Spencer983e3b32007-03-01 07:25:48 +00006661 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006662 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006663 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006664 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006665
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006666 // Update all the PHI nodes for the next iteration.
6667 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006668
6669 // Create a list of which PHIs we need to compute. We want to do this before
6670 // calling EvaluateExpression on them because that may invalidate iterators
6671 // into CurrentIterVals.
6672 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006673 for (const auto &I : CurrentIterVals) {
6674 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006675 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006676 PHIsToCompute.push_back(PHI);
6677 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006678 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006679 Constant *&NextPHI = NextIterVals[PHI];
6680 if (NextPHI) continue; // Already computed!
6681
Sanjoy Dasdd709962015-10-08 18:28:36 +00006682 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006683 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006684 }
6685 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006686 }
6687
6688 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006689 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006690}
6691
Dan Gohman237d9e52009-09-03 15:00:26 +00006692/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006693/// at the specified scope in the program. The L value specifies a loop
6694/// nest to evaluate the expression at, where null is the top-level or a
6695/// specified loop is immediately inside of the loop.
6696///
6697/// This method can be used to compute the exit value for a variable defined
6698/// in a loop by querying what the value will hold in the parent loop.
6699///
Dan Gohman8ca08852009-05-24 23:25:42 +00006700/// In the case that a relevant loop exit value cannot be computed, the
6701/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006702const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006703 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6704 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006705 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006706 for (auto &LS : Values)
6707 if (LS.first == L)
6708 return LS.second ? LS.second : V;
6709
6710 Values.emplace_back(L, nullptr);
6711
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006712 // Otherwise compute it.
6713 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006714 for (auto &LS : reverse(ValuesAtScopes[V]))
6715 if (LS.first == L) {
6716 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006717 break;
6718 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006719 return C;
6720}
6721
Nick Lewyckya6674c72011-10-22 19:58:20 +00006722/// This builds up a Constant using the ConstantExpr interface. That way, we
6723/// will return Constants for objects which aren't represented by a
6724/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6725/// Returns NULL if the SCEV isn't representable as a Constant.
6726static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006727 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006728 case scCouldNotCompute:
6729 case scAddRecExpr:
6730 break;
6731 case scConstant:
6732 return cast<SCEVConstant>(V)->getValue();
6733 case scUnknown:
6734 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6735 case scSignExtend: {
6736 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6737 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6738 return ConstantExpr::getSExt(CastOp, SS->getType());
6739 break;
6740 }
6741 case scZeroExtend: {
6742 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6743 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6744 return ConstantExpr::getZExt(CastOp, SZ->getType());
6745 break;
6746 }
6747 case scTruncate: {
6748 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6749 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6750 return ConstantExpr::getTrunc(CastOp, ST->getType());
6751 break;
6752 }
6753 case scAddExpr: {
6754 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6755 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006756 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6757 unsigned AS = PTy->getAddressSpace();
6758 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6759 C = ConstantExpr::getBitCast(C, DestPtrTy);
6760 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006761 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6762 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006763 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006764
6765 // First pointer!
6766 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006767 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006768 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006769 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006770 // The offsets have been converted to bytes. We can add bytes to an
6771 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006772 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006773 }
6774
6775 // Don't bother trying to sum two pointers. We probably can't
6776 // statically compute a load that results from it anyway.
6777 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006778 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006779
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006780 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6781 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006782 C2 = ConstantExpr::getIntegerCast(
6783 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006784 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006785 } else
6786 C = ConstantExpr::getAdd(C, C2);
6787 }
6788 return C;
6789 }
6790 break;
6791 }
6792 case scMulExpr: {
6793 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6794 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6795 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006796 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006797 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6798 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006799 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006800 C = ConstantExpr::getMul(C, C2);
6801 }
6802 return C;
6803 }
6804 break;
6805 }
6806 case scUDivExpr: {
6807 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6808 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6809 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6810 if (LHS->getType() == RHS->getType())
6811 return ConstantExpr::getUDiv(LHS, RHS);
6812 break;
6813 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006814 case scSMaxExpr:
6815 case scUMaxExpr:
6816 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006817 }
Craig Topper9f008862014-04-15 04:59:12 +00006818 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006819}
6820
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006821const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006822 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006823
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006824 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006825 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006826 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006827 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006828 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006829 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6830 if (PHINode *PN = dyn_cast<PHINode>(I))
6831 if (PN->getParent() == LI->getHeader()) {
6832 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006833 // to see if the loop that contains it has a known backedge-taken
6834 // count. If so, we may be able to force computation of the exit
6835 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006836 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006837 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006838 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006839 // Okay, we know how many times the containing loop executes. If
6840 // this is a constant evolving PHI node, get the final value at
6841 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006842 Constant *RV =
6843 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006844 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006845 }
6846 }
6847
Reid Spencere6328ca2006-12-04 21:33:23 +00006848 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006849 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006850 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006851 // result. This is particularly useful for computing loop exit values.
6852 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006853 SmallVector<Constant *, 4> Operands;
6854 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006855 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006856 if (Constant *C = dyn_cast<Constant>(Op)) {
6857 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006858 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006859 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006860
6861 // If any of the operands is non-constant and if they are
6862 // non-integer and non-pointer, don't even try to analyze them
6863 // with scev techniques.
6864 if (!isSCEVable(Op->getType()))
6865 return V;
6866
6867 const SCEV *OrigV = getSCEV(Op);
6868 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6869 MadeImprovement |= OrigV != OpV;
6870
Nick Lewyckya6674c72011-10-22 19:58:20 +00006871 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006872 if (!C) return V;
6873 if (C->getType() != Op->getType())
6874 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6875 Op->getType(),
6876 false),
6877 C, Op->getType());
6878 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006879 }
Dan Gohmance973df2009-06-24 04:48:43 +00006880
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006881 // Check to see if getSCEVAtScope actually made an improvement.
6882 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006883 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006884 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006885 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006886 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006887 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006888 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6889 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006890 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006891 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006892 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006893 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006894 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006895 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006896 }
6897 }
6898
6899 // This is some other type of SCEVUnknown, just return it.
6900 return V;
6901 }
6902
Dan Gohmana30370b2009-05-04 22:02:23 +00006903 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006904 // Avoid performing the look-up in the common case where the specified
6905 // expression has no loop-variant portions.
6906 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006907 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006908 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006909 // Okay, at least one of these operands is loop variant but might be
6910 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006911 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6912 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006913 NewOps.push_back(OpAtScope);
6914
6915 for (++i; i != e; ++i) {
6916 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006917 NewOps.push_back(OpAtScope);
6918 }
6919 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006920 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006921 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006922 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006923 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006924 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006925 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006926 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006927 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006928 }
6929 }
6930 // If we got here, all operands are loop invariant.
6931 return Comm;
6932 }
6933
Dan Gohmana30370b2009-05-04 22:02:23 +00006934 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006935 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6936 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006937 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6938 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006939 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006940 }
6941
6942 // If this is a loop recurrence for a loop that does not contain L, then we
6943 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006944 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006945 // First, attempt to evaluate each operand.
6946 // Avoid performing the look-up in the common case where the specified
6947 // expression has no loop-variant portions.
6948 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6949 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6950 if (OpAtScope == AddRec->getOperand(i))
6951 continue;
6952
6953 // Okay, at least one of these operands is loop variant but might be
6954 // foldable. Build a new instance of the folded commutative expression.
6955 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6956 AddRec->op_begin()+i);
6957 NewOps.push_back(OpAtScope);
6958 for (++i; i != e; ++i)
6959 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6960
Andrew Trick759ba082011-04-27 01:21:25 +00006961 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006962 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006963 AddRec->getNoWrapFlags(SCEV::FlagNW));
6964 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006965 // The addrec may be folded to a nonrecurrence, for example, if the
6966 // induction variable is multiplied by zero after constant folding. Go
6967 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006968 if (!AddRec)
6969 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006970 break;
6971 }
6972
6973 // If the scope is outside the addrec's loop, evaluate it by using the
6974 // loop exit value of the addrec.
6975 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006976 // To evaluate this recurrence, we need to know how many times the AddRec
6977 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006978 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006979 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006980
Eli Friedman61f67622008-08-04 23:49:06 +00006981 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006982 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006983 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006984
Dan Gohman8ca08852009-05-24 23:25:42 +00006985 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006986 }
6987
Dan Gohmana30370b2009-05-04 22:02:23 +00006988 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006989 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006990 if (Op == Cast->getOperand())
6991 return Cast; // must be loop invariant
6992 return getZeroExtendExpr(Op, Cast->getType());
6993 }
6994
Dan Gohmana30370b2009-05-04 22:02:23 +00006995 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006996 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006997 if (Op == Cast->getOperand())
6998 return Cast; // must be loop invariant
6999 return getSignExtendExpr(Op, Cast->getType());
7000 }
7001
Dan Gohmana30370b2009-05-04 22:02:23 +00007002 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007003 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00007004 if (Op == Cast->getOperand())
7005 return Cast; // must be loop invariant
7006 return getTruncateExpr(Op, Cast->getType());
7007 }
7008
Torok Edwinfbcc6632009-07-14 16:55:14 +00007009 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00007010}
7011
Dan Gohmanb81f47d2009-05-08 20:38:54 +00007012/// getSCEVAtScope - This is a convenience function which does
7013/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00007014const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007015 return getSCEVAtScope(getSCEV(V), L);
7016}
7017
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007018/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
7019/// following equation:
7020///
7021/// A * X = B (mod N)
7022///
7023/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7024/// A and B isn't important.
7025///
7026/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007027static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007028 ScalarEvolution &SE) {
7029 uint32_t BW = A.getBitWidth();
7030 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
7031 assert(A != 0 && "A must be non-zero.");
7032
7033 // 1. D = gcd(A, N)
7034 //
7035 // The gcd of A and N may have only one prime factor: 2. The number of
7036 // trailing zeros in A is its multiplicity
7037 uint32_t Mult2 = A.countTrailingZeros();
7038 // D = 2^Mult2
7039
7040 // 2. Check if B is divisible by D.
7041 //
7042 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7043 // is not less than multiplicity of this prime factor for D.
7044 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007045 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007046
7047 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7048 // modulo (N / D).
7049 //
7050 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
7051 // bit width during computations.
7052 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7053 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007054 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007055 APInt I = AD.multiplicativeInverse(Mod);
7056
7057 // 4. Compute the minimum unsigned root of the equation:
7058 // I * (B / D) mod (N / D)
7059 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7060
7061 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7062 // bits.
7063 return SE.getConstant(Result.trunc(BW));
7064}
Chris Lattnerd934c702004-04-02 20:23:17 +00007065
7066/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
7067/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
7068/// might be the same) or two SCEVCouldNotCompute objects.
7069///
Dan Gohmanaf752342009-07-07 17:06:11 +00007070static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007071SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007072 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007073 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7074 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7075 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007076
Chris Lattnerd934c702004-04-02 20:23:17 +00007077 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00007078 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00007079 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007080 return {CNC, CNC};
Chris Lattnerd934c702004-04-02 20:23:17 +00007081 }
7082
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007083 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7084 const APInt &L = LC->getAPInt();
7085 const APInt &M = MC->getAPInt();
7086 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007087 APInt Two(BitWidth, 2);
7088 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007089
Dan Gohmance973df2009-06-24 04:48:43 +00007090 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007091 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007092 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007093 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7094 // The B coefficient is M-N/2
7095 APInt B(M);
7096 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007097
Reid Spencer983e3b32007-03-01 07:25:48 +00007098 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007099 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007100
Reid Spencer983e3b32007-03-01 07:25:48 +00007101 // Compute the B^2-4ac term.
7102 APInt SqrtTerm(B);
7103 SqrtTerm *= B;
7104 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007105
Nick Lewyckyfb780832012-08-01 09:14:36 +00007106 if (SqrtTerm.isNegative()) {
7107 // The loop is provably infinite.
7108 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007109 return {CNC, CNC};
Nick Lewyckyfb780832012-08-01 09:14:36 +00007110 }
7111
Reid Spencer983e3b32007-03-01 07:25:48 +00007112 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7113 // integer value or else APInt::sqrt() will assert.
7114 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007115
Dan Gohmance973df2009-06-24 04:48:43 +00007116 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007117 // The divisions must be performed as signed divisions.
7118 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007119 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00007120 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00007121 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007122 return {CNC, CNC};
Nick Lewycky7b14e202008-11-03 02:43:49 +00007123 }
7124
Owen Anderson47db9412009-07-22 00:24:57 +00007125 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007126
7127 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007128 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007129 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007130 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007131
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007132 return {SE.getConstant(Solution1), SE.getConstant(Solution2)};
Nick Lewycky31555522011-10-03 07:10:45 +00007133 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007134}
7135
7136/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00007137/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00007138///
7139/// This is only used for loops with a "x != y" exit test. The exit condition is
7140/// now expressed as a single expression, V = x-y. So the exit test is
7141/// effectively V != 0. We know and take advantage of the fact that this
7142/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00007143ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00007144ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7145 bool AllowPredicates) {
7146 SCEVUnionPredicate P;
Chris Lattnerd934c702004-04-02 20:23:17 +00007147 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007148 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007149 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007150 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007151 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007152 }
7153
Dan Gohman48f82222009-05-04 22:30:44 +00007154 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007155 if (!AddRec && AllowPredicates)
7156 // Try to make this an AddRec using runtime tests, in the first X
7157 // iterations of this loop, where X is the SCEV expression found by the
7158 // algorithm below.
7159 AddRec = convertSCEVToAddRecWithPredicates(V, L, P);
7160
Chris Lattnerd934c702004-04-02 20:23:17 +00007161 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007162 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007163
Chris Lattnerdff679f2011-01-09 22:39:48 +00007164 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7165 // the quadratic equation to solve it.
7166 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7167 std::pair<const SCEV *,const SCEV *> Roots =
7168 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00007169 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7170 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00007171 if (R1 && R2) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007172 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007173 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00007174 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
7175 R1->getValue(),
7176 R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007177 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00007178 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007179
Chris Lattnerd934c702004-04-02 20:23:17 +00007180 // We can only use this value if the chrec ends up with an exact zero
7181 // value at this index. When solving for "X*X != 5", for example, we
7182 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007183 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007184 if (Val->isZero())
Silviu Baranga6f444df2016-04-08 14:29:09 +00007185 return ExitLimit(R1, R1, P); // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00007186 }
7187 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007188 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007189 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007190
Chris Lattnerdff679f2011-01-09 22:39:48 +00007191 // Otherwise we can only handle this if it is affine.
7192 if (!AddRec->isAffine())
7193 return getCouldNotCompute();
7194
7195 // If this is an affine expression, the execution count of this branch is
7196 // the minimum unsigned root of the following equation:
7197 //
7198 // Start + Step*N = 0 (mod 2^BW)
7199 //
7200 // equivalent to:
7201 //
7202 // Step*N = -Start (mod 2^BW)
7203 //
7204 // where BW is the common bit width of Start and Step.
7205
7206 // Get the initial value for the loop.
7207 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7208 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7209
7210 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007211 //
7212 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7213 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7214 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7215 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007216 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007217 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007218 return getCouldNotCompute();
7219
Andrew Trick8b55b732011-03-14 16:50:06 +00007220 // For positive steps (counting up until unsigned overflow):
7221 // N = -Start/Step (as unsigned)
7222 // For negative steps (counting down to zero):
7223 // N = Start/-Step
7224 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007225 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007226 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007227
7228 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007229 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7230 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007231 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7232 ConstantRange CR = getUnsignedRange(Start);
7233 const SCEV *MaxBECount;
7234 if (!CountDown && CR.getUnsignedMin().isMinValue())
7235 // When counting up, the worst starting value is 1, not 0.
7236 MaxBECount = CR.getUnsignedMax().isMinValue()
7237 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7238 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7239 else
7240 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7241 : -CR.getUnsignedMin());
Silviu Baranga6f444df2016-04-08 14:29:09 +00007242 return ExitLimit(Distance, MaxBECount, P);
Nick Lewycky31555522011-10-03 07:10:45 +00007243 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007244
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007245 // As a special case, handle the instance where Step is a positive power of
7246 // two. In this case, determining whether Step divides Distance evenly can be
7247 // done by counting and comparing the number of trailing zeros of Step and
7248 // Distance.
7249 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007250 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007251 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7252 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7253 // case is not handled as this code is guarded by !CountDown.
7254 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007255 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7256 // Here we've constrained the equation to be of the form
7257 //
7258 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7259 //
7260 // where we're operating on a W bit wide integer domain and k is
7261 // non-negative. The smallest unsigned solution for X is the trip count.
7262 //
7263 // (0) is equivalent to:
7264 //
7265 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7266 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7267 // <=> 2^k * Distance' - X = L * 2^(W - N)
7268 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7269 //
7270 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7271 // by 2^(W - N).
7272 //
7273 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7274 //
7275 // E.g. say we're solving
7276 //
7277 // 2 * Val = 2 * X (in i8) ... (3)
7278 //
7279 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7280 //
7281 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7282 // necessarily the smallest unsigned value of X that satisfies (3).
7283 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7284 // is i8 1, not i8 -127
7285
7286 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7287
7288 // Since SCEV does not have a URem node, we construct one using a truncate
7289 // and a zero extend.
7290
7291 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7292 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7293 auto *WideTy = Distance->getType();
7294
Silviu Baranga6f444df2016-04-08 14:29:09 +00007295 const SCEV *Limit =
7296 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7297 return ExitLimit(Limit, Limit, P);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007298 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007299 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007300
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007301 // If the condition controls loop exit (the loop exits only if the expression
7302 // is true) and the addition is no-wrap we can use unsigned divide to
7303 // compute the backedge count. In this case, the step may not divide the
7304 // distance, but we don't care because if the condition is "missed" the loop
7305 // will have undefined behavior due to wrapping.
Sanjoy Das76c48e02016-02-04 18:21:54 +00007306 if (ControlsExit && AddRec->hasNoSelfWrap()) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007307 const SCEV *Exact =
7308 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007309 return ExitLimit(Exact, Exact, P);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007310 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007311
Chris Lattnerdff679f2011-01-09 22:39:48 +00007312 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007313 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7314 const SCEV *E = SolveLinEquationWithOverflow(
7315 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7316 return ExitLimit(E, E, P);
7317 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007318 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007319}
7320
7321/// HowFarToNonZero - Return the number of times a backedge checking the
7322/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00007323/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00007324ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00007325ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007326 // Loops that look like: while (X == 0) are very strange indeed. We don't
7327 // handle them yet except for the trivial case. This could be expanded in the
7328 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007329
Chris Lattnerd934c702004-04-02 20:23:17 +00007330 // If the value is a constant, check to see if it is known to be non-zero
7331 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007332 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007333 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007334 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007335 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007336 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007337
Chris Lattnerd934c702004-04-02 20:23:17 +00007338 // We could implement others, but I really doubt anyone writes loops like
7339 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007340 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007341}
7342
Dan Gohmanf9081a22008-09-15 22:18:04 +00007343/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
7344/// (which may not be an immediate predecessor) which has exactly one
7345/// successor from which BB is reachable, or null if no such block is
7346/// found.
7347///
Dan Gohman4e3c1132010-04-15 16:19:08 +00007348std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007349ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007350 // If the block has a unique predecessor, then there is no path from the
7351 // predecessor to the block that does not go through the direct edge
7352 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007353 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007354 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007355
7356 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007357 // If the header has a unique predecessor outside the loop, it must be
7358 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007359 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007360 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007361
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007362 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007363}
7364
Dan Gohman450f4e02009-06-20 00:35:32 +00007365/// HasSameValue - SCEV structural equivalence is usually sufficient for
7366/// testing whether two expressions are equal, however for the purposes of
7367/// looking for a condition guarding a loop, it can be useful to be a little
7368/// more general, since a front-end may have replicated the controlling
7369/// expression.
7370///
Dan Gohmanaf752342009-07-07 17:06:11 +00007371static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007372 // Quick check to see if they are the same SCEV.
7373 if (A == B) return true;
7374
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007375 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7376 // Not all instructions that are "identical" compute the same value. For
7377 // instance, two distinct alloca instructions allocating the same type are
7378 // identical and do not read memory; but compute distinct values.
7379 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7380 };
7381
Dan Gohman450f4e02009-06-20 00:35:32 +00007382 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7383 // two different instructions with the same value. Check for this case.
7384 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7385 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7386 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7387 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007388 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007389 return true;
7390
7391 // Otherwise assume they may have a different value.
7392 return false;
7393}
7394
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007395/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007396/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007397///
7398bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007399 const SCEV *&LHS, const SCEV *&RHS,
7400 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007401 bool Changed = false;
7402
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007403 // If we hit the max recursion limit bail out.
7404 if (Depth >= 3)
7405 return false;
7406
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007407 // Canonicalize a constant to the right side.
7408 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7409 // Check for both operands constant.
7410 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7411 if (ConstantExpr::getICmp(Pred,
7412 LHSC->getValue(),
7413 RHSC->getValue())->isNullValue())
7414 goto trivially_false;
7415 else
7416 goto trivially_true;
7417 }
7418 // Otherwise swap the operands to put the constant on the right.
7419 std::swap(LHS, RHS);
7420 Pred = ICmpInst::getSwappedPredicate(Pred);
7421 Changed = true;
7422 }
7423
7424 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007425 // addrec's loop, put the addrec on the left. Also make a dominance check,
7426 // as both operands could be addrecs loop-invariant in each other's loop.
7427 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7428 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007429 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007430 std::swap(LHS, RHS);
7431 Pred = ICmpInst::getSwappedPredicate(Pred);
7432 Changed = true;
7433 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007434 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007435
7436 // If there's a constant operand, canonicalize comparisons with boundary
7437 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7438 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007439 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007440 switch (Pred) {
7441 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7442 case ICmpInst::ICMP_EQ:
7443 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007444 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7445 if (!RA)
7446 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7447 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00007448 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7449 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007450 RHS = AE->getOperand(1);
7451 LHS = ME->getOperand(1);
7452 Changed = true;
7453 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007454 break;
7455 case ICmpInst::ICMP_UGE:
7456 if ((RA - 1).isMinValue()) {
7457 Pred = ICmpInst::ICMP_NE;
7458 RHS = getConstant(RA - 1);
7459 Changed = true;
7460 break;
7461 }
7462 if (RA.isMaxValue()) {
7463 Pred = ICmpInst::ICMP_EQ;
7464 Changed = true;
7465 break;
7466 }
7467 if (RA.isMinValue()) goto trivially_true;
7468
7469 Pred = ICmpInst::ICMP_UGT;
7470 RHS = getConstant(RA - 1);
7471 Changed = true;
7472 break;
7473 case ICmpInst::ICMP_ULE:
7474 if ((RA + 1).isMaxValue()) {
7475 Pred = ICmpInst::ICMP_NE;
7476 RHS = getConstant(RA + 1);
7477 Changed = true;
7478 break;
7479 }
7480 if (RA.isMinValue()) {
7481 Pred = ICmpInst::ICMP_EQ;
7482 Changed = true;
7483 break;
7484 }
7485 if (RA.isMaxValue()) goto trivially_true;
7486
7487 Pred = ICmpInst::ICMP_ULT;
7488 RHS = getConstant(RA + 1);
7489 Changed = true;
7490 break;
7491 case ICmpInst::ICMP_SGE:
7492 if ((RA - 1).isMinSignedValue()) {
7493 Pred = ICmpInst::ICMP_NE;
7494 RHS = getConstant(RA - 1);
7495 Changed = true;
7496 break;
7497 }
7498 if (RA.isMaxSignedValue()) {
7499 Pred = ICmpInst::ICMP_EQ;
7500 Changed = true;
7501 break;
7502 }
7503 if (RA.isMinSignedValue()) goto trivially_true;
7504
7505 Pred = ICmpInst::ICMP_SGT;
7506 RHS = getConstant(RA - 1);
7507 Changed = true;
7508 break;
7509 case ICmpInst::ICMP_SLE:
7510 if ((RA + 1).isMaxSignedValue()) {
7511 Pred = ICmpInst::ICMP_NE;
7512 RHS = getConstant(RA + 1);
7513 Changed = true;
7514 break;
7515 }
7516 if (RA.isMinSignedValue()) {
7517 Pred = ICmpInst::ICMP_EQ;
7518 Changed = true;
7519 break;
7520 }
7521 if (RA.isMaxSignedValue()) goto trivially_true;
7522
7523 Pred = ICmpInst::ICMP_SLT;
7524 RHS = getConstant(RA + 1);
7525 Changed = true;
7526 break;
7527 case ICmpInst::ICMP_UGT:
7528 if (RA.isMinValue()) {
7529 Pred = ICmpInst::ICMP_NE;
7530 Changed = true;
7531 break;
7532 }
7533 if ((RA + 1).isMaxValue()) {
7534 Pred = ICmpInst::ICMP_EQ;
7535 RHS = getConstant(RA + 1);
7536 Changed = true;
7537 break;
7538 }
7539 if (RA.isMaxValue()) goto trivially_false;
7540 break;
7541 case ICmpInst::ICMP_ULT:
7542 if (RA.isMaxValue()) {
7543 Pred = ICmpInst::ICMP_NE;
7544 Changed = true;
7545 break;
7546 }
7547 if ((RA - 1).isMinValue()) {
7548 Pred = ICmpInst::ICMP_EQ;
7549 RHS = getConstant(RA - 1);
7550 Changed = true;
7551 break;
7552 }
7553 if (RA.isMinValue()) goto trivially_false;
7554 break;
7555 case ICmpInst::ICMP_SGT:
7556 if (RA.isMinSignedValue()) {
7557 Pred = ICmpInst::ICMP_NE;
7558 Changed = true;
7559 break;
7560 }
7561 if ((RA + 1).isMaxSignedValue()) {
7562 Pred = ICmpInst::ICMP_EQ;
7563 RHS = getConstant(RA + 1);
7564 Changed = true;
7565 break;
7566 }
7567 if (RA.isMaxSignedValue()) goto trivially_false;
7568 break;
7569 case ICmpInst::ICMP_SLT:
7570 if (RA.isMaxSignedValue()) {
7571 Pred = ICmpInst::ICMP_NE;
7572 Changed = true;
7573 break;
7574 }
7575 if ((RA - 1).isMinSignedValue()) {
7576 Pred = ICmpInst::ICMP_EQ;
7577 RHS = getConstant(RA - 1);
7578 Changed = true;
7579 break;
7580 }
7581 if (RA.isMinSignedValue()) goto trivially_false;
7582 break;
7583 }
7584 }
7585
7586 // Check for obvious equality.
7587 if (HasSameValue(LHS, RHS)) {
7588 if (ICmpInst::isTrueWhenEqual(Pred))
7589 goto trivially_true;
7590 if (ICmpInst::isFalseWhenEqual(Pred))
7591 goto trivially_false;
7592 }
7593
Dan Gohman81585c12010-05-03 16:35:17 +00007594 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7595 // adding or subtracting 1 from one of the operands.
7596 switch (Pred) {
7597 case ICmpInst::ICMP_SLE:
7598 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7599 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007600 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007601 Pred = ICmpInst::ICMP_SLT;
7602 Changed = true;
7603 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007604 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007605 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007606 Pred = ICmpInst::ICMP_SLT;
7607 Changed = true;
7608 }
7609 break;
7610 case ICmpInst::ICMP_SGE:
7611 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007612 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007613 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007614 Pred = ICmpInst::ICMP_SGT;
7615 Changed = true;
7616 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7617 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007618 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007619 Pred = ICmpInst::ICMP_SGT;
7620 Changed = true;
7621 }
7622 break;
7623 case ICmpInst::ICMP_ULE:
7624 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007625 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007626 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007627 Pred = ICmpInst::ICMP_ULT;
7628 Changed = true;
7629 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007630 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007631 Pred = ICmpInst::ICMP_ULT;
7632 Changed = true;
7633 }
7634 break;
7635 case ICmpInst::ICMP_UGE:
7636 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007637 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007638 Pred = ICmpInst::ICMP_UGT;
7639 Changed = true;
7640 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007641 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007642 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007643 Pred = ICmpInst::ICMP_UGT;
7644 Changed = true;
7645 }
7646 break;
7647 default:
7648 break;
7649 }
7650
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007651 // TODO: More simplifications are possible here.
7652
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007653 // Recursively simplify until we either hit a recursion limit or nothing
7654 // changes.
7655 if (Changed)
7656 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7657
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007658 return Changed;
7659
7660trivially_true:
7661 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007662 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007663 Pred = ICmpInst::ICMP_EQ;
7664 return true;
7665
7666trivially_false:
7667 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007668 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007669 Pred = ICmpInst::ICMP_NE;
7670 return true;
7671}
7672
Dan Gohmane65c9172009-07-13 21:35:55 +00007673bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7674 return getSignedRange(S).getSignedMax().isNegative();
7675}
7676
7677bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7678 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7679}
7680
7681bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7682 return !getSignedRange(S).getSignedMin().isNegative();
7683}
7684
7685bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7686 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7687}
7688
7689bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7690 return isKnownNegative(S) || isKnownPositive(S);
7691}
7692
7693bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7694 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007695 // Canonicalize the inputs first.
7696 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7697
Dan Gohman07591692010-04-11 22:16:48 +00007698 // If LHS or RHS is an addrec, check to see if the condition is true in
7699 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007700 // If LHS and RHS are both addrec, both conditions must be true in
7701 // every iteration of the loop.
7702 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7703 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7704 bool LeftGuarded = false;
7705 bool RightGuarded = false;
7706 if (LAR) {
7707 const Loop *L = LAR->getLoop();
7708 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7709 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7710 if (!RAR) return true;
7711 LeftGuarded = true;
7712 }
7713 }
7714 if (RAR) {
7715 const Loop *L = RAR->getLoop();
7716 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7717 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7718 if (!LAR) return true;
7719 RightGuarded = true;
7720 }
7721 }
7722 if (LeftGuarded && RightGuarded)
7723 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007724
Sanjoy Das7d910f22015-10-02 18:50:30 +00007725 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7726 return true;
7727
Dan Gohman07591692010-04-11 22:16:48 +00007728 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007729 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007730}
7731
Sanjoy Das5dab2052015-07-27 21:42:49 +00007732bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7733 ICmpInst::Predicate Pred,
7734 bool &Increasing) {
7735 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7736
7737#ifndef NDEBUG
7738 // Verify an invariant: inverting the predicate should turn a monotonically
7739 // increasing change to a monotonically decreasing one, and vice versa.
7740 bool IncreasingSwapped;
7741 bool ResultSwapped = isMonotonicPredicateImpl(
7742 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7743
7744 assert(Result == ResultSwapped && "should be able to analyze both!");
7745 if (ResultSwapped)
7746 assert(Increasing == !IncreasingSwapped &&
7747 "monotonicity should flip as we flip the predicate");
7748#endif
7749
7750 return Result;
7751}
7752
7753bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7754 ICmpInst::Predicate Pred,
7755 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007756
7757 // A zero step value for LHS means the induction variable is essentially a
7758 // loop invariant value. We don't really depend on the predicate actually
7759 // flipping from false to true (for increasing predicates, and the other way
7760 // around for decreasing predicates), all we care about is that *if* the
7761 // predicate changes then it only changes from false to true.
7762 //
7763 // A zero step value in itself is not very useful, but there may be places
7764 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7765 // as general as possible.
7766
Sanjoy Das366acc12015-08-06 20:43:41 +00007767 switch (Pred) {
7768 default:
7769 return false; // Conservative answer
7770
7771 case ICmpInst::ICMP_UGT:
7772 case ICmpInst::ICMP_UGE:
7773 case ICmpInst::ICMP_ULT:
7774 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007775 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007776 return false;
7777
7778 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007779 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007780
7781 case ICmpInst::ICMP_SGT:
7782 case ICmpInst::ICMP_SGE:
7783 case ICmpInst::ICMP_SLT:
7784 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007785 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007786 return false;
7787
7788 const SCEV *Step = LHS->getStepRecurrence(*this);
7789
7790 if (isKnownNonNegative(Step)) {
7791 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7792 return true;
7793 }
7794
7795 if (isKnownNonPositive(Step)) {
7796 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7797 return true;
7798 }
7799
7800 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007801 }
7802
Sanjoy Das5dab2052015-07-27 21:42:49 +00007803 }
7804
Sanjoy Das366acc12015-08-06 20:43:41 +00007805 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007806}
7807
7808bool ScalarEvolution::isLoopInvariantPredicate(
7809 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7810 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7811 const SCEV *&InvariantRHS) {
7812
7813 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7814 if (!isLoopInvariant(RHS, L)) {
7815 if (!isLoopInvariant(LHS, L))
7816 return false;
7817
7818 std::swap(LHS, RHS);
7819 Pred = ICmpInst::getSwappedPredicate(Pred);
7820 }
7821
7822 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7823 if (!ArLHS || ArLHS->getLoop() != L)
7824 return false;
7825
7826 bool Increasing;
7827 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7828 return false;
7829
7830 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7831 // true as the loop iterates, and the backedge is control dependent on
7832 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7833 //
7834 // * if the predicate was false in the first iteration then the predicate
7835 // is never evaluated again, since the loop exits without taking the
7836 // backedge.
7837 // * if the predicate was true in the first iteration then it will
7838 // continue to be true for all future iterations since it is
7839 // monotonically increasing.
7840 //
7841 // For both the above possibilities, we can replace the loop varying
7842 // predicate with its value on the first iteration of the loop (which is
7843 // loop invariant).
7844 //
7845 // A similar reasoning applies for a monotonically decreasing predicate, by
7846 // replacing true with false and false with true in the above two bullets.
7847
7848 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7849
7850 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7851 return false;
7852
7853 InvariantPred = Pred;
7854 InvariantLHS = ArLHS->getStart();
7855 InvariantRHS = RHS;
7856 return true;
7857}
7858
Sanjoy Das401e6312016-02-01 20:48:10 +00007859bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7860 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007861 if (HasSameValue(LHS, RHS))
7862 return ICmpInst::isTrueWhenEqual(Pred);
7863
Dan Gohman07591692010-04-11 22:16:48 +00007864 // This code is split out from isKnownPredicate because it is called from
7865 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007866
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007867 auto CheckRanges =
7868 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7869 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7870 .contains(RangeLHS);
7871 };
7872
7873 // The check at the top of the function catches the case where the values are
7874 // known to be equal.
7875 if (Pred == CmpInst::ICMP_EQ)
7876 return false;
7877
7878 if (Pred == CmpInst::ICMP_NE)
7879 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7880 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7881 isKnownNonZero(getMinusSCEV(LHS, RHS));
7882
7883 if (CmpInst::isSigned(Pred))
7884 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7885
7886 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007887}
7888
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007889bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7890 const SCEV *LHS,
7891 const SCEV *RHS) {
7892
7893 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7894 // Return Y via OutY.
7895 auto MatchBinaryAddToConst =
7896 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7897 SCEV::NoWrapFlags ExpectedFlags) {
7898 const SCEV *NonConstOp, *ConstOp;
7899 SCEV::NoWrapFlags FlagsPresent;
7900
7901 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7902 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7903 return false;
7904
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007905 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007906 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7907 };
7908
7909 APInt C;
7910
7911 switch (Pred) {
7912 default:
7913 break;
7914
7915 case ICmpInst::ICMP_SGE:
7916 std::swap(LHS, RHS);
7917 case ICmpInst::ICMP_SLE:
7918 // X s<= (X + C)<nsw> if C >= 0
7919 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7920 return true;
7921
7922 // (X + C)<nsw> s<= X if C <= 0
7923 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7924 !C.isStrictlyPositive())
7925 return true;
7926 break;
7927
7928 case ICmpInst::ICMP_SGT:
7929 std::swap(LHS, RHS);
7930 case ICmpInst::ICMP_SLT:
7931 // X s< (X + C)<nsw> if C > 0
7932 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7933 C.isStrictlyPositive())
7934 return true;
7935
7936 // (X + C)<nsw> s< X if C < 0
7937 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7938 return true;
7939 break;
7940 }
7941
7942 return false;
7943}
7944
Sanjoy Das7d910f22015-10-02 18:50:30 +00007945bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7946 const SCEV *LHS,
7947 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007948 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007949 return false;
7950
7951 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7952 // the stack can result in exponential time complexity.
7953 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7954
7955 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7956 //
7957 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7958 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7959 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7960 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7961 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007962 return isKnownNonNegative(RHS) &&
7963 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7964 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007965}
7966
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007967bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7968 ICmpInst::Predicate Pred,
7969 const SCEV *LHS, const SCEV *RHS) {
7970 // No need to even try if we know the module has no guards.
7971 if (!HasGuards)
7972 return false;
7973
7974 return any_of(*BB, [&](Instruction &I) {
7975 using namespace llvm::PatternMatch;
7976
7977 Value *Condition;
7978 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7979 m_Value(Condition))) &&
7980 isImpliedCond(Pred, LHS, RHS, Condition, false);
7981 });
7982}
7983
Dan Gohmane65c9172009-07-13 21:35:55 +00007984/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7985/// protected by a conditional between LHS and RHS. This is used to
7986/// to eliminate casts.
7987bool
7988ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7989 ICmpInst::Predicate Pred,
7990 const SCEV *LHS, const SCEV *RHS) {
7991 // Interpret a null as meaning no loop, where there is obviously no guard
7992 // (interprocedural conditions notwithstanding).
7993 if (!L) return true;
7994
Sanjoy Das401e6312016-02-01 20:48:10 +00007995 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7996 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007997
Dan Gohmane65c9172009-07-13 21:35:55 +00007998 BasicBlock *Latch = L->getLoopLatch();
7999 if (!Latch)
8000 return false;
8001
8002 BranchInst *LoopContinuePredicate =
8003 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008004 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8005 isImpliedCond(Pred, LHS, RHS,
8006 LoopContinuePredicate->getCondition(),
8007 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8008 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00008009
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008010 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008011 // -- that can lead to O(n!) time complexity.
8012 if (WalkingBEDominatingConds)
8013 return false;
8014
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00008015 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008016
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00008017 // See if we can exploit a trip count to prove the predicate.
8018 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8019 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8020 if (LatchBECount != getCouldNotCompute()) {
8021 // We know that Latch branches back to the loop header exactly
8022 // LatchBECount times. This means the backdege condition at Latch is
8023 // equivalent to "{0,+,1} u< LatchBECount".
8024 Type *Ty = LatchBECount->getType();
8025 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8026 const SCEV *LoopCounter =
8027 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8028 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8029 LatchBECount))
8030 return true;
8031 }
8032
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00008033 // Check conditions due to any @llvm.assume intrinsics.
8034 for (auto &AssumeVH : AC.assumptions()) {
8035 if (!AssumeVH)
8036 continue;
8037 auto *CI = cast<CallInst>(AssumeVH);
8038 if (!DT.dominates(CI, Latch->getTerminator()))
8039 continue;
8040
8041 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8042 return true;
8043 }
8044
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008045 // If the loop is not reachable from the entry block, we risk running into an
8046 // infinite loop as we walk up into the dom tree. These loops do not matter
8047 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008048 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008049 return false;
8050
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008051 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8052 return true;
8053
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008054 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8055 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008056
8057 assert(DTN && "should reach the loop header before reaching the root!");
8058
8059 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008060 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8061 return true;
8062
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008063 BasicBlock *PBB = BB->getSinglePredecessor();
8064 if (!PBB)
8065 continue;
8066
8067 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8068 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8069 continue;
8070
8071 Value *Condition = ContinuePredicate->getCondition();
8072
8073 // If we have an edge `E` within the loop body that dominates the only
8074 // latch, the condition guarding `E` also guards the backedge. This
8075 // reasoning works only for loops with a single latch.
8076
8077 BasicBlockEdge DominatingEdge(PBB, BB);
8078 if (DominatingEdge.isSingleEdge()) {
8079 // We're constructively (and conservatively) enumerating edges within the
8080 // loop body that dominate the latch. The dominator tree better agree
8081 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008082 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008083
8084 if (isImpliedCond(Pred, LHS, RHS, Condition,
8085 BB != ContinuePredicate->getSuccessor(0)))
8086 return true;
8087 }
8088 }
8089
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008090 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008091}
8092
Dan Gohmanb50349a2010-04-11 19:27:13 +00008093/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00008094/// by a conditional between LHS and RHS. This is used to help avoid max
8095/// expressions in loop trip counts, and to eliminate casts.
8096bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008097ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8098 ICmpInst::Predicate Pred,
8099 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008100 // Interpret a null as meaning no loop, where there is obviously no guard
8101 // (interprocedural conditions notwithstanding).
8102 if (!L) return false;
8103
Sanjoy Das401e6312016-02-01 20:48:10 +00008104 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8105 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008106
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008107 // Starting at the loop predecessor, climb up the predecessor chain, as long
8108 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008109 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008110 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008111 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008112 Pair.first;
8113 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008114
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008115 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8116 return true;
8117
Dan Gohman2a62fd92008-08-12 20:17:31 +00008118 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008119 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008120 if (!LoopEntryPredicate ||
8121 LoopEntryPredicate->isUnconditional())
8122 continue;
8123
Dan Gohmane18c2d62010-08-10 23:46:30 +00008124 if (isImpliedCond(Pred, LHS, RHS,
8125 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008126 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008127 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008128 }
8129
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008130 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008131 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00008132 if (!AssumeVH)
8133 continue;
8134 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008135 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008136 continue;
8137
8138 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8139 return true;
8140 }
8141
Dan Gohman2a62fd92008-08-12 20:17:31 +00008142 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008143}
8144
Benjamin Kramer039b1042015-10-28 13:54:36 +00008145namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008146/// RAII wrapper to prevent recursive application of isImpliedCond.
8147/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
8148/// currently evaluating isImpliedCond.
8149struct MarkPendingLoopPredicate {
8150 Value *Cond;
8151 DenseSet<Value*> &LoopPreds;
8152 bool Pending;
8153
8154 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
8155 : Cond(C), LoopPreds(LP) {
8156 Pending = !LoopPreds.insert(Cond).second;
8157 }
8158 ~MarkPendingLoopPredicate() {
8159 if (!Pending)
8160 LoopPreds.erase(Cond);
8161 }
8162};
Benjamin Kramer039b1042015-10-28 13:54:36 +00008163} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008164
Dan Gohman430f0cc2009-07-21 23:03:19 +00008165/// isImpliedCond - Test whether the condition described by Pred, LHS,
8166/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008167bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008168 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008169 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008170 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008171 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
8172 if (Mark.Pending)
8173 return false;
8174
Dan Gohman8b0a4192010-03-01 17:49:51 +00008175 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008177 if (BO->getOpcode() == Instruction::And) {
8178 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008179 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8180 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008181 } else if (BO->getOpcode() == Instruction::Or) {
8182 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008183 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8184 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008185 }
8186 }
8187
Dan Gohmane18c2d62010-08-10 23:46:30 +00008188 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008189 if (!ICI) return false;
8190
Andrew Trickfa594032012-11-29 18:35:13 +00008191 // Now that we found a conditional branch that dominates the loop or controls
8192 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008193 ICmpInst::Predicate FoundPred;
8194 if (Inverse)
8195 FoundPred = ICI->getInversePredicate();
8196 else
8197 FoundPred = ICI->getPredicate();
8198
8199 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8200 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008201
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008202 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8203}
8204
8205bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8206 const SCEV *RHS,
8207 ICmpInst::Predicate FoundPred,
8208 const SCEV *FoundLHS,
8209 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008210 // Balance the types.
8211 if (getTypeSizeInBits(LHS->getType()) <
8212 getTypeSizeInBits(FoundLHS->getType())) {
8213 if (CmpInst::isSigned(Pred)) {
8214 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8215 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8216 } else {
8217 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8218 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8219 }
8220 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008221 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008222 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008223 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8224 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8225 } else {
8226 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8227 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8228 }
8229 }
8230
Dan Gohman430f0cc2009-07-21 23:03:19 +00008231 // Canonicalize the query to match the way instcombine will have
8232 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008233 if (SimplifyICmpOperands(Pred, LHS, RHS))
8234 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008235 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008236 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8237 if (FoundLHS == FoundRHS)
8238 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008239
8240 // Check to see if we can make the LHS or RHS match.
8241 if (LHS == FoundRHS || RHS == FoundLHS) {
8242 if (isa<SCEVConstant>(RHS)) {
8243 std::swap(FoundLHS, FoundRHS);
8244 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8245 } else {
8246 std::swap(LHS, RHS);
8247 Pred = ICmpInst::getSwappedPredicate(Pred);
8248 }
8249 }
8250
8251 // Check whether the found predicate is the same as the desired predicate.
8252 if (FoundPred == Pred)
8253 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8254
8255 // Check whether swapping the found predicate makes it the same as the
8256 // desired predicate.
8257 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8258 if (isa<SCEVConstant>(RHS))
8259 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8260 else
8261 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8262 RHS, LHS, FoundLHS, FoundRHS);
8263 }
8264
Sanjoy Das6e78b172015-10-22 19:57:34 +00008265 // Unsigned comparison is the same as signed comparison when both the operands
8266 // are non-negative.
8267 if (CmpInst::isUnsigned(FoundPred) &&
8268 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8269 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8270 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8271
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008272 // Check if we can make progress by sharpening ranges.
8273 if (FoundPred == ICmpInst::ICMP_NE &&
8274 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8275
8276 const SCEVConstant *C = nullptr;
8277 const SCEV *V = nullptr;
8278
8279 if (isa<SCEVConstant>(FoundLHS)) {
8280 C = cast<SCEVConstant>(FoundLHS);
8281 V = FoundRHS;
8282 } else {
8283 C = cast<SCEVConstant>(FoundRHS);
8284 V = FoundLHS;
8285 }
8286
8287 // The guarding predicate tells us that C != V. If the known range
8288 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8289 // range we consider has to correspond to same signedness as the
8290 // predicate we're interested in folding.
8291
8292 APInt Min = ICmpInst::isSigned(Pred) ?
8293 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8294
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008295 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008296 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8297 // This is true even if (Min + 1) wraps around -- in case of
8298 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8299
8300 APInt SharperMin = Min + 1;
8301
8302 switch (Pred) {
8303 case ICmpInst::ICMP_SGE:
8304 case ICmpInst::ICMP_UGE:
8305 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8306 // RHS, we're done.
8307 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8308 getConstant(SharperMin)))
8309 return true;
8310
8311 case ICmpInst::ICMP_SGT:
8312 case ICmpInst::ICMP_UGT:
8313 // We know from the range information that (V `Pred` Min ||
8314 // V == Min). We know from the guarding condition that !(V
8315 // == Min). This gives us
8316 //
8317 // V `Pred` Min || V == Min && !(V == Min)
8318 // => V `Pred` Min
8319 //
8320 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8321
8322 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8323 return true;
8324
8325 default:
8326 // No change
8327 break;
8328 }
8329 }
8330 }
8331
Dan Gohman430f0cc2009-07-21 23:03:19 +00008332 // Check whether the actual condition is beyond sufficient.
8333 if (FoundPred == ICmpInst::ICMP_EQ)
8334 if (ICmpInst::isTrueWhenEqual(Pred))
8335 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8336 return true;
8337 if (Pred == ICmpInst::ICMP_NE)
8338 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8339 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8340 return true;
8341
8342 // Otherwise assume the worst.
8343 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008344}
8345
Sanjoy Das1ed69102015-10-13 02:53:27 +00008346bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8347 const SCEV *&L, const SCEV *&R,
8348 SCEV::NoWrapFlags &Flags) {
8349 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8350 if (!AE || AE->getNumOperands() != 2)
8351 return false;
8352
8353 L = AE->getOperand(0);
8354 R = AE->getOperand(1);
8355 Flags = AE->getNoWrapFlags();
8356 return true;
8357}
8358
8359bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
8360 const SCEV *More,
8361 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008362 // We avoid subtracting expressions here because this function is usually
8363 // fairly deep in the call stack (i.e. is called many times).
8364
Sanjoy Das96709c42015-09-25 23:53:45 +00008365 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8366 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8367 const auto *MAR = cast<SCEVAddRecExpr>(More);
8368
8369 if (LAR->getLoop() != MAR->getLoop())
8370 return false;
8371
8372 // We look at affine expressions only; not for correctness but to keep
8373 // getStepRecurrence cheap.
8374 if (!LAR->isAffine() || !MAR->isAffine())
8375 return false;
8376
Sanjoy Das1ed69102015-10-13 02:53:27 +00008377 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00008378 return false;
8379
8380 Less = LAR->getStart();
8381 More = MAR->getStart();
8382
8383 // fall through
8384 }
8385
8386 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008387 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8388 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008389 C = M - L;
8390 return true;
8391 }
8392
8393 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008394 SCEV::NoWrapFlags Flags;
8395 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008396 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8397 if (R == More) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008398 C = -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008399 return true;
8400 }
8401
Sanjoy Das1ed69102015-10-13 02:53:27 +00008402 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008403 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8404 if (R == Less) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008405 C = LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008406 return true;
8407 }
8408
8409 return false;
8410}
8411
8412bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8413 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8414 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8415 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8416 return false;
8417
8418 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8419 if (!AddRecLHS)
8420 return false;
8421
8422 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8423 if (!AddRecFoundLHS)
8424 return false;
8425
8426 // We'd like to let SCEV reason about control dependencies, so we constrain
8427 // both the inequalities to be about add recurrences on the same loop. This
8428 // way we can use isLoopEntryGuardedByCond later.
8429
8430 const Loop *L = AddRecFoundLHS->getLoop();
8431 if (L != AddRecLHS->getLoop())
8432 return false;
8433
8434 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8435 //
8436 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8437 // ... (2)
8438 //
8439 // Informal proof for (2), assuming (1) [*]:
8440 //
8441 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8442 //
8443 // Then
8444 //
8445 // FoundLHS s< FoundRHS s< INT_MIN - C
8446 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8447 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8448 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8449 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8450 // <=> FoundLHS + C s< FoundRHS + C
8451 //
8452 // [*]: (1) can be proved by ruling out overflow.
8453 //
8454 // [**]: This can be proved by analyzing all the four possibilities:
8455 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8456 // (A s>= 0, B s>= 0).
8457 //
8458 // Note:
8459 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8460 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8461 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8462 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8463 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8464 // C)".
8465
8466 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008467 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
8468 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00008469 LDiff != RDiff)
8470 return false;
8471
8472 if (LDiff == 0)
8473 return true;
8474
Sanjoy Das96709c42015-09-25 23:53:45 +00008475 APInt FoundRHSLimit;
8476
8477 if (Pred == CmpInst::ICMP_ULT) {
8478 FoundRHSLimit = -RDiff;
8479 } else {
8480 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00008481 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008482 }
8483
8484 // Try to prove (1) or (2), as needed.
8485 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8486 getConstant(FoundRHSLimit));
8487}
8488
Dan Gohman430f0cc2009-07-21 23:03:19 +00008489/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00008490/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008491/// and FoundRHS is true.
8492bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8493 const SCEV *LHS, const SCEV *RHS,
8494 const SCEV *FoundLHS,
8495 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008496 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8497 return true;
8498
Sanjoy Das96709c42015-09-25 23:53:45 +00008499 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8500 return true;
8501
Dan Gohman430f0cc2009-07-21 23:03:19 +00008502 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8503 FoundLHS, FoundRHS) ||
8504 // ~x < ~y --> x > y
8505 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8506 getNotSCEV(FoundRHS),
8507 getNotSCEV(FoundLHS));
8508}
8509
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008510
8511/// If Expr computes ~A, return A else return nullptr
8512static const SCEV *MatchNotExpr(const SCEV *Expr) {
8513 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008514 if (!Add || Add->getNumOperands() != 2 ||
8515 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008516 return nullptr;
8517
8518 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008519 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8520 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008521 return nullptr;
8522
8523 return AddRHS->getOperand(1);
8524}
8525
8526
8527/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8528template<typename MaxExprType>
8529static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8530 const SCEV *Candidate) {
8531 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8532 if (!MaxExpr) return false;
8533
Sanjoy Das347d2722015-12-01 07:49:27 +00008534 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008535}
8536
8537
8538/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8539template<typename MaxExprType>
8540static bool IsMinConsistingOf(ScalarEvolution &SE,
8541 const SCEV *MaybeMinExpr,
8542 const SCEV *Candidate) {
8543 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8544 if (!MaybeMaxExpr)
8545 return false;
8546
8547 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8548}
8549
Hal Finkela8d205f2015-08-19 01:51:51 +00008550static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8551 ICmpInst::Predicate Pred,
8552 const SCEV *LHS, const SCEV *RHS) {
8553
8554 // If both sides are affine addrecs for the same loop, with equal
8555 // steps, and we know the recurrences don't wrap, then we only
8556 // need to check the predicate on the starting values.
8557
8558 if (!ICmpInst::isRelational(Pred))
8559 return false;
8560
8561 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8562 if (!LAR)
8563 return false;
8564 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8565 if (!RAR)
8566 return false;
8567 if (LAR->getLoop() != RAR->getLoop())
8568 return false;
8569 if (!LAR->isAffine() || !RAR->isAffine())
8570 return false;
8571
8572 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8573 return false;
8574
Hal Finkelff08a2e2015-08-19 17:26:07 +00008575 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8576 SCEV::FlagNSW : SCEV::FlagNUW;
8577 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008578 return false;
8579
8580 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8581}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008582
8583/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8584/// expression?
8585static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8586 ICmpInst::Predicate Pred,
8587 const SCEV *LHS, const SCEV *RHS) {
8588 switch (Pred) {
8589 default:
8590 return false;
8591
8592 case ICmpInst::ICMP_SGE:
8593 std::swap(LHS, RHS);
8594 // fall through
8595 case ICmpInst::ICMP_SLE:
8596 return
8597 // min(A, ...) <= A
8598 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8599 // A <= max(A, ...)
8600 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8601
8602 case ICmpInst::ICMP_UGE:
8603 std::swap(LHS, RHS);
8604 // fall through
8605 case ICmpInst::ICMP_ULE:
8606 return
8607 // min(A, ...) <= A
8608 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8609 // A <= max(A, ...)
8610 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8611 }
8612
8613 llvm_unreachable("covered switch fell through?!");
8614}
8615
Dan Gohman430f0cc2009-07-21 23:03:19 +00008616/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00008617/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008618/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00008619bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008620ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8621 const SCEV *LHS, const SCEV *RHS,
8622 const SCEV *FoundLHS,
8623 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008624 auto IsKnownPredicateFull =
8625 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008626 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008627 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008628 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8629 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008630 };
8631
Dan Gohmane65c9172009-07-13 21:35:55 +00008632 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008633 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8634 case ICmpInst::ICMP_EQ:
8635 case ICmpInst::ICMP_NE:
8636 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8637 return true;
8638 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008639 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008640 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008641 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8642 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008643 return true;
8644 break;
8645 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008646 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008647 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8648 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008649 return true;
8650 break;
8651 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008652 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008653 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8654 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008655 return true;
8656 break;
8657 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008658 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008659 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8660 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008661 return true;
8662 break;
8663 }
8664
8665 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008666}
8667
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008668/// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
8669/// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
8670bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8671 const SCEV *LHS,
8672 const SCEV *RHS,
8673 const SCEV *FoundLHS,
8674 const SCEV *FoundRHS) {
8675 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8676 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8677 // reduce the compile time impact of this optimization.
8678 return false;
8679
8680 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8681 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8682 !isa<SCEVConstant>(AddLHS->getOperand(0)))
8683 return false;
8684
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008685 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008686
8687 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8688 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8689 ConstantRange FoundLHSRange =
8690 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8691
8692 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8693 // for `LHS`:
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008694 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008695 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8696
8697 // We can also compute the range of values for `LHS` that satisfy the
8698 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008699 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008700 ConstantRange SatisfyingLHSRange =
8701 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8702
8703 // The antecedent implies the consequent if every value of `LHS` that
8704 // satisfies the antecedent also satisfies the consequent.
8705 return SatisfyingLHSRange.contains(LHSRange);
8706}
8707
Johannes Doerfert2683e562015-02-09 12:34:23 +00008708// Verify if an linear IV with positive stride can overflow when in a
8709// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008710// stride and the knowledge of NSW/NUW flags on the recurrence.
8711bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8712 bool IsSigned, bool NoWrap) {
8713 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008714
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008715 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008716 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008717
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008718 if (IsSigned) {
8719 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8720 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8721 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8722 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008723
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008724 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8725 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008726 }
Dan Gohman01048422009-06-21 23:46:38 +00008727
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008728 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8729 APInt MaxValue = APInt::getMaxValue(BitWidth);
8730 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8731 .getUnsignedMax();
8732
8733 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8734 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8735}
8736
Johannes Doerfert2683e562015-02-09 12:34:23 +00008737// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008738// greater-than comparison, knowing the invariant term of the comparison,
8739// the stride and the knowledge of NSW/NUW flags on the recurrence.
8740bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8741 bool IsSigned, bool NoWrap) {
8742 if (NoWrap) return false;
8743
8744 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008745 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008746
8747 if (IsSigned) {
8748 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8749 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8750 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8751 .getSignedMax();
8752
8753 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8754 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8755 }
8756
8757 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8758 APInt MinValue = APInt::getMinValue(BitWidth);
8759 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8760 .getUnsignedMax();
8761
8762 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8763 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8764}
8765
8766// Compute the backedge taken count knowing the interval difference, the
8767// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00008768const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008769 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008770 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008771 Delta = Equality ? getAddExpr(Delta, Step)
8772 : getAddExpr(Delta, getMinusSCEV(Step, One));
8773 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008774}
8775
Chris Lattner587a75b2005-08-15 23:33:51 +00008776/// HowManyLessThans - Return the number of times a backedge containing the
8777/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00008778/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00008779///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008780/// @param ControlsExit is true when the LHS < RHS condition directly controls
8781/// the branch (loops exits only if condition is true). In this case, we can use
8782/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00008783ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00008784ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008785 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008786 bool ControlsExit, bool AllowPredicates) {
8787 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008788 // We handle only IV < Invariant
8789 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008790 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008791
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008792 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008793 if (!IV && AllowPredicates)
8794 // Try to make this an AddRec using runtime tests, in the first X
8795 // iterations of this loop, where X is the SCEV expression found by the
8796 // algorithm below.
8797 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Dan Gohman2b8da352009-04-30 20:47:05 +00008798
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008799 // Avoid weird loops
8800 if (!IV || IV->getLoop() != L || !IV->isAffine())
8801 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008802
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008803 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008804 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008805
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008806 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008807
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008808 // Avoid negative or zero stride values
8809 if (!isKnownPositive(Stride))
8810 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008811
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008812 // Avoid proven overflow cases: this will ensure that the backedge taken count
8813 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008814 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008815 // behaviors like the case of C language.
8816 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8817 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008818
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008819 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8820 : ICmpInst::ICMP_ULT;
8821 const SCEV *Start = IV->getStart();
8822 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008823 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8824 const SCEV *Diff = getMinusSCEV(RHS, Start);
8825 // If we have NoWrap set, then we can assume that the increment won't
8826 // overflow, in which case if RHS - Start is a constant, we don't need to
8827 // do a max operation since we can just figure it out statically
8828 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008829 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008830 if (D.isNegative())
8831 End = Start;
8832 } else
8833 End = IsSigned ? getSMaxExpr(RHS, Start)
8834 : getUMaxExpr(RHS, Start);
8835 }
Dan Gohman51aaf022010-01-26 04:40:18 +00008836
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008837 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008838
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008839 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8840 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008841
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008842 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8843 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008844
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008845 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8846 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8847 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008848
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008849 // Although End can be a MAX expression we estimate MaxEnd considering only
8850 // the case End = RHS. This is safe because in the other case (End - Start)
8851 // is zero, leading to a zero maximum backedge taken count.
8852 APInt MaxEnd =
8853 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8854 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8855
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008856 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008857 if (isa<SCEVConstant>(BECount))
8858 MaxBECount = BECount;
8859 else
8860 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8861 getConstant(MinStride), false);
8862
8863 if (isa<SCEVCouldNotCompute>(MaxBECount))
8864 MaxBECount = BECount;
8865
Silviu Baranga6f444df2016-04-08 14:29:09 +00008866 return ExitLimit(BECount, MaxBECount, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008867}
8868
8869ScalarEvolution::ExitLimit
8870ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8871 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008872 bool ControlsExit, bool AllowPredicates) {
8873 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008874 // We handle only IV > Invariant
8875 if (!isLoopInvariant(RHS, L))
8876 return getCouldNotCompute();
8877
8878 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008879 if (!IV && AllowPredicates)
8880 // Try to make this an AddRec using runtime tests, in the first X
8881 // iterations of this loop, where X is the SCEV expression found by the
8882 // algorithm below.
8883 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008884
8885 // Avoid weird loops
8886 if (!IV || IV->getLoop() != L || !IV->isAffine())
8887 return getCouldNotCompute();
8888
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008889 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008890 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8891
8892 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8893
8894 // Avoid negative or zero stride values
8895 if (!isKnownPositive(Stride))
8896 return getCouldNotCompute();
8897
8898 // Avoid proven overflow cases: this will ensure that the backedge taken count
8899 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008900 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008901 // behaviors like the case of C language.
8902 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8903 return getCouldNotCompute();
8904
8905 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8906 : ICmpInst::ICMP_UGT;
8907
8908 const SCEV *Start = IV->getStart();
8909 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008910 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8911 const SCEV *Diff = getMinusSCEV(RHS, Start);
8912 // If we have NoWrap set, then we can assume that the increment won't
8913 // overflow, in which case if RHS - Start is a constant, we don't need to
8914 // do a max operation since we can just figure it out statically
8915 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008916 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008917 if (!D.isNegative())
8918 End = Start;
8919 } else
8920 End = IsSigned ? getSMinExpr(RHS, Start)
8921 : getUMinExpr(RHS, Start);
8922 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008923
8924 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8925
8926 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8927 : getUnsignedRange(Start).getUnsignedMax();
8928
8929 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8930 : getUnsignedRange(Stride).getUnsignedMin();
8931
8932 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8933 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8934 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8935
8936 // Although End can be a MIN expression we estimate MinEnd considering only
8937 // the case End = RHS. This is safe because in the other case (Start - End)
8938 // is zero, leading to a zero maximum backedge taken count.
8939 APInt MinEnd =
8940 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8941 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8942
8943
8944 const SCEV *MaxBECount = getCouldNotCompute();
8945 if (isa<SCEVConstant>(BECount))
8946 MaxBECount = BECount;
8947 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008948 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008949 getConstant(MinStride), false);
8950
8951 if (isa<SCEVCouldNotCompute>(MaxBECount))
8952 MaxBECount = BECount;
8953
Silviu Baranga6f444df2016-04-08 14:29:09 +00008954 return ExitLimit(BECount, MaxBECount, P);
Chris Lattner587a75b2005-08-15 23:33:51 +00008955}
8956
Chris Lattnerd934c702004-04-02 20:23:17 +00008957/// getNumIterationsInRange - Return the number of iterations of this loop that
8958/// produce values in the specified constant range. Another way of looking at
8959/// this is that it returns the first iteration number where the value is not in
8960/// the condition, thus computing the exit count. If the iteration count can't
8961/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00008962const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008963 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008964 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008965 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008966
8967 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008968 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008969 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008970 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008971 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008972 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008973 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008974 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008975 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008976 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008977 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008978 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008979 }
8980
8981 // The only time we can solve this is when we have all constant indices.
8982 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008983 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008984 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008985
8986 // Okay at this point we know that all elements of the chrec are constants and
8987 // that the start element is zero.
8988
8989 // First check to see if the range contains zero. If not, the first
8990 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008991 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008992 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008993 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008994
Chris Lattnerd934c702004-04-02 20:23:17 +00008995 if (isAffine()) {
8996 // If this is an affine expression then we have this situation:
8997 // Solve {0,+,A} in Range === Ax in Range
8998
Nick Lewycky52460262007-07-16 02:08:00 +00008999 // We know that zero is in the range. If A is positive then we know that
9000 // the upper value of the range must be the first possible exit value.
9001 // If A is negative then the lower of the range is the last possible loop
9002 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00009003 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009004 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00009005 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00009006
Nick Lewycky52460262007-07-16 02:08:00 +00009007 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00009008 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00009009 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00009010
9011 // Evaluate at the exit value. If we really did fall out of the valid
9012 // range, then we computed our trip count, otherwise wrap around or other
9013 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00009014 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009015 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00009016 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009017
9018 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00009019 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00009020 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00009021 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00009022 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00009023 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00009024 } else if (isQuadratic()) {
9025 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9026 // quadratic equation to solve it. To do this, we must frame our problem in
9027 // terms of figuring out when zero is crossed, instead of when
9028 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00009029 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00009030 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00009031 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
9032 // getNoWrapFlags(FlagNW)
9033 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00009034
9035 // Next, solve the constructed addrec
Sanjoy Das01947432015-11-22 21:20:13 +00009036 auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00009037 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
9038 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00009039 if (R1) {
9040 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00009041 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9042 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00009043 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00009044 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00009045
Chris Lattnerd934c702004-04-02 20:23:17 +00009046 // Make sure the root is not off by one. The returned iteration should
9047 // not be in the range, but the previous one should be. When solving
9048 // for "X*X < 5", for example, we should not return a root of 2.
9049 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00009050 R1->getValue(),
9051 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009052 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009053 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00009054 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009055 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00009056
Dan Gohmana37eaf22007-10-22 18:31:58 +00009057 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009058 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00009059 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00009060 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009061 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009062
Chris Lattnerd934c702004-04-02 20:23:17 +00009063 // If R1 was not in the range, then it is a good return value. Make
9064 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00009065 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00009066 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00009067 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00009068 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00009069 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00009070 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00009071 }
9072 }
9073 }
9074
Dan Gohman31efa302009-04-18 17:58:19 +00009075 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00009076}
9077
Sebastian Pop448712b2014-05-07 18:01:20 +00009078namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009079struct FindUndefs {
9080 bool Found;
9081 FindUndefs() : Found(false) {}
9082
9083 bool follow(const SCEV *S) {
9084 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
9085 if (isa<UndefValue>(C->getValue()))
9086 Found = true;
9087 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
9088 if (isa<UndefValue>(C->getValue()))
9089 Found = true;
9090 }
9091
9092 // Keep looking if we haven't found it yet.
9093 return !Found;
9094 }
9095 bool isDone() const {
9096 // Stop recursion if we have found an undef.
9097 return Found;
9098 }
9099};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009100}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009101
9102// Return true when S contains at least an undef value.
9103static inline bool
9104containsUndefs(const SCEV *S) {
9105 FindUndefs F;
9106 SCEVTraversal<FindUndefs> ST(F);
9107 ST.visitAll(S);
9108
9109 return F.Found;
9110}
9111
9112namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009113// Collect all steps of SCEV expressions.
9114struct SCEVCollectStrides {
9115 ScalarEvolution &SE;
9116 SmallVectorImpl<const SCEV *> &Strides;
9117
9118 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9119 : SE(SE), Strides(S) {}
9120
9121 bool follow(const SCEV *S) {
9122 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9123 Strides.push_back(AR->getStepRecurrence(SE));
9124 return true;
9125 }
9126 bool isDone() const { return false; }
9127};
9128
9129// Collect all SCEVUnknown and SCEVMulExpr expressions.
9130struct SCEVCollectTerms {
9131 SmallVectorImpl<const SCEV *> &Terms;
9132
9133 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9134 : Terms(T) {}
9135
9136 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009137 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009138 if (!containsUndefs(S))
9139 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009140
9141 // Stop recursion: once we collected a term, do not walk its operands.
9142 return false;
9143 }
9144
9145 // Keep looking.
9146 return true;
9147 }
9148 bool isDone() const { return false; }
9149};
Tobias Grosser374bce02015-10-12 08:02:00 +00009150
9151// Check if a SCEV contains an AddRecExpr.
9152struct SCEVHasAddRec {
9153 bool &ContainsAddRec;
9154
9155 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9156 ContainsAddRec = false;
9157 }
9158
9159 bool follow(const SCEV *S) {
9160 if (isa<SCEVAddRecExpr>(S)) {
9161 ContainsAddRec = true;
9162
9163 // Stop recursion: once we collected a term, do not walk its operands.
9164 return false;
9165 }
9166
9167 // Keep looking.
9168 return true;
9169 }
9170 bool isDone() const { return false; }
9171};
9172
9173// Find factors that are multiplied with an expression that (possibly as a
9174// subexpression) contains an AddRecExpr. In the expression:
9175//
9176// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9177//
9178// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9179// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9180// parameters as they form a product with an induction variable.
9181//
9182// This collector expects all array size parameters to be in the same MulExpr.
9183// It might be necessary to later add support for collecting parameters that are
9184// spread over different nested MulExpr.
9185struct SCEVCollectAddRecMultiplies {
9186 SmallVectorImpl<const SCEV *> &Terms;
9187 ScalarEvolution &SE;
9188
9189 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9190 : Terms(T), SE(SE) {}
9191
9192 bool follow(const SCEV *S) {
9193 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9194 bool HasAddRec = false;
9195 SmallVector<const SCEV *, 0> Operands;
9196 for (auto Op : Mul->operands()) {
9197 if (isa<SCEVUnknown>(Op)) {
9198 Operands.push_back(Op);
9199 } else {
9200 bool ContainsAddRec;
9201 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9202 visitAll(Op, ContiansAddRec);
9203 HasAddRec |= ContainsAddRec;
9204 }
9205 }
9206 if (Operands.size() == 0)
9207 return true;
9208
9209 if (!HasAddRec)
9210 return false;
9211
9212 Terms.push_back(SE.getMulExpr(Operands));
9213 // Stop recursion: once we collected a term, do not walk its operands.
9214 return false;
9215 }
9216
9217 // Keep looking.
9218 return true;
9219 }
9220 bool isDone() const { return false; }
9221};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009222}
Sebastian Pop448712b2014-05-07 18:01:20 +00009223
Tobias Grosser374bce02015-10-12 08:02:00 +00009224/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9225/// two places:
9226/// 1) The strides of AddRec expressions.
9227/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009228void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9229 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009230 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009231 SCEVCollectStrides StrideCollector(*this, Strides);
9232 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009233
9234 DEBUG({
9235 dbgs() << "Strides:\n";
9236 for (const SCEV *S : Strides)
9237 dbgs() << *S << "\n";
9238 });
9239
9240 for (const SCEV *S : Strides) {
9241 SCEVCollectTerms TermCollector(Terms);
9242 visitAll(S, TermCollector);
9243 }
9244
9245 DEBUG({
9246 dbgs() << "Terms:\n";
9247 for (const SCEV *T : Terms)
9248 dbgs() << *T << "\n";
9249 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009250
9251 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9252 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009253}
9254
Sebastian Popb1a548f2014-05-12 19:01:53 +00009255static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009256 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009257 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009258 int Last = Terms.size() - 1;
9259 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009260
Sebastian Pop448712b2014-05-07 18:01:20 +00009261 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009262 if (Last == 0) {
9263 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009264 SmallVector<const SCEV *, 2> Qs;
9265 for (const SCEV *Op : M->operands())
9266 if (!isa<SCEVConstant>(Op))
9267 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009268
Sebastian Pope30bd352014-05-27 22:41:56 +00009269 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009270 }
9271
Sebastian Pope30bd352014-05-27 22:41:56 +00009272 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009273 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009274 }
9275
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009276 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009277 // Normalize the terms before the next call to findArrayDimensionsRec.
9278 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009279 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009280
9281 // Bail out when GCD does not evenly divide one of the terms.
9282 if (!R->isZero())
9283 return false;
9284
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009285 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009286 }
9287
Tobias Grosser3080cf12014-05-08 07:55:34 +00009288 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00009289 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
9290 return isa<SCEVConstant>(E);
9291 }),
9292 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009293
Sebastian Pop448712b2014-05-07 18:01:20 +00009294 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009295 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9296 return false;
9297
Sebastian Pope30bd352014-05-27 22:41:56 +00009298 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009299 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009300}
Sebastian Popc62c6792013-11-12 22:47:20 +00009301
Sebastian Pop448712b2014-05-07 18:01:20 +00009302// Returns true when S contains at least a SCEVUnknown parameter.
9303static inline bool
9304containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00009305 struct FindParameter {
9306 bool FoundParameter;
9307 FindParameter() : FoundParameter(false) {}
9308
9309 bool follow(const SCEV *S) {
9310 if (isa<SCEVUnknown>(S)) {
9311 FoundParameter = true;
9312 // Stop recursion: we found a parameter.
9313 return false;
9314 }
9315 // Keep looking.
9316 return true;
9317 }
9318 bool isDone() const {
9319 // Stop recursion if we have found a parameter.
9320 return FoundParameter;
9321 }
9322 };
9323
Sebastian Pop448712b2014-05-07 18:01:20 +00009324 FindParameter F;
9325 SCEVTraversal<FindParameter> ST(F);
9326 ST.visitAll(S);
9327
9328 return F.FoundParameter;
9329}
9330
9331// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9332static inline bool
9333containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9334 for (const SCEV *T : Terms)
9335 if (containsParameters(T))
9336 return true;
9337 return false;
9338}
9339
9340// Return the number of product terms in S.
9341static inline int numberOfTerms(const SCEV *S) {
9342 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9343 return Expr->getNumOperands();
9344 return 1;
9345}
9346
Sebastian Popa6e58602014-05-27 22:41:45 +00009347static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9348 if (isa<SCEVConstant>(T))
9349 return nullptr;
9350
9351 if (isa<SCEVUnknown>(T))
9352 return T;
9353
9354 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9355 SmallVector<const SCEV *, 2> Factors;
9356 for (const SCEV *Op : M->operands())
9357 if (!isa<SCEVConstant>(Op))
9358 Factors.push_back(Op);
9359
9360 return SE.getMulExpr(Factors);
9361 }
9362
9363 return T;
9364}
9365
9366/// Return the size of an element read or written by Inst.
9367const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9368 Type *Ty;
9369 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9370 Ty = Store->getValueOperand()->getType();
9371 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009372 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009373 else
9374 return nullptr;
9375
9376 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9377 return getSizeOfExpr(ETy, Ty);
9378}
9379
Sebastian Pop448712b2014-05-07 18:01:20 +00009380/// Second step of delinearization: compute the array dimensions Sizes from the
9381/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00009382void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9383 SmallVectorImpl<const SCEV *> &Sizes,
9384 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00009385
Sebastian Pop53524082014-05-29 19:44:05 +00009386 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009387 return;
9388
9389 // Early return when Terms do not contain parameters: we do not delinearize
9390 // non parametric SCEVs.
9391 if (!containsParameters(Terms))
9392 return;
9393
9394 DEBUG({
9395 dbgs() << "Terms:\n";
9396 for (const SCEV *T : Terms)
9397 dbgs() << *T << "\n";
9398 });
9399
9400 // Remove duplicates.
9401 std::sort(Terms.begin(), Terms.end());
9402 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9403
9404 // Put larger terms first.
9405 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9406 return numberOfTerms(LHS) > numberOfTerms(RHS);
9407 });
9408
Sebastian Popa6e58602014-05-27 22:41:45 +00009409 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9410
Tobias Grosser374bce02015-10-12 08:02:00 +00009411 // Try to divide all terms by the element size. If term is not divisible by
9412 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009413 for (const SCEV *&Term : Terms) {
9414 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009415 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009416 if (!Q->isZero())
9417 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009418 }
9419
9420 SmallVector<const SCEV *, 4> NewTerms;
9421
9422 // Remove constant factors.
9423 for (const SCEV *T : Terms)
9424 if (const SCEV *NewT = removeConstantFactors(SE, T))
9425 NewTerms.push_back(NewT);
9426
Sebastian Pop448712b2014-05-07 18:01:20 +00009427 DEBUG({
9428 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009429 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009430 dbgs() << *T << "\n";
9431 });
9432
Sebastian Popa6e58602014-05-27 22:41:45 +00009433 if (NewTerms.empty() ||
9434 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009435 Sizes.clear();
9436 return;
9437 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009438
Sebastian Popa6e58602014-05-27 22:41:45 +00009439 // The last element to be pushed into Sizes is the size of an element.
9440 Sizes.push_back(ElementSize);
9441
Sebastian Pop448712b2014-05-07 18:01:20 +00009442 DEBUG({
9443 dbgs() << "Sizes:\n";
9444 for (const SCEV *S : Sizes)
9445 dbgs() << *S << "\n";
9446 });
9447}
9448
9449/// Third step of delinearization: compute the access functions for the
9450/// Subscripts based on the dimensions in Sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009451void ScalarEvolution::computeAccessFunctions(
9452 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9453 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009454
Sebastian Popb1a548f2014-05-12 19:01:53 +00009455 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009456 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009457 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009458
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009459 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009460 if (!AR->isAffine())
9461 return;
9462
9463 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009464 int Last = Sizes.size() - 1;
9465 for (int i = Last; i >= 0; i--) {
9466 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009467 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009468
9469 DEBUG({
9470 dbgs() << "Res: " << *Res << "\n";
9471 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9472 dbgs() << "Res divided by Sizes[i]:\n";
9473 dbgs() << "Quotient: " << *Q << "\n";
9474 dbgs() << "Remainder: " << *R << "\n";
9475 });
9476
9477 Res = Q;
9478
Sebastian Popa6e58602014-05-27 22:41:45 +00009479 // Do not record the last subscript corresponding to the size of elements in
9480 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009481 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009482
9483 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009484 if (isa<SCEVAddRecExpr>(R)) {
9485 Subscripts.clear();
9486 Sizes.clear();
9487 return;
9488 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009489
Sebastian Pop448712b2014-05-07 18:01:20 +00009490 continue;
9491 }
9492
9493 // Record the access function for the current subscript.
9494 Subscripts.push_back(R);
9495 }
9496
9497 // Also push in last position the remainder of the last division: it will be
9498 // the access function of the innermost dimension.
9499 Subscripts.push_back(Res);
9500
9501 std::reverse(Subscripts.begin(), Subscripts.end());
9502
9503 DEBUG({
9504 dbgs() << "Subscripts:\n";
9505 for (const SCEV *S : Subscripts)
9506 dbgs() << *S << "\n";
9507 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009508}
9509
Sebastian Popc62c6792013-11-12 22:47:20 +00009510/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9511/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009512/// is the offset start of the array. The SCEV->delinearize algorithm computes
9513/// the multiples of SCEV coefficients: that is a pattern matching of sub
9514/// expressions in the stride and base of a SCEV corresponding to the
9515/// computation of a GCD (greatest common divisor) of base and stride. When
9516/// SCEV->delinearize fails, it returns the SCEV unchanged.
9517///
9518/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9519///
9520/// void foo(long n, long m, long o, double A[n][m][o]) {
9521///
9522/// for (long i = 0; i < n; i++)
9523/// for (long j = 0; j < m; j++)
9524/// for (long k = 0; k < o; k++)
9525/// A[i][j][k] = 1.0;
9526/// }
9527///
9528/// the delinearization input is the following AddRec SCEV:
9529///
9530/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9531///
9532/// From this SCEV, we are able to say that the base offset of the access is %A
9533/// because it appears as an offset that does not divide any of the strides in
9534/// the loops:
9535///
9536/// CHECK: Base offset: %A
9537///
9538/// and then SCEV->delinearize determines the size of some of the dimensions of
9539/// the array as these are the multiples by which the strides are happening:
9540///
9541/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9542///
9543/// Note that the outermost dimension remains of UnknownSize because there are
9544/// no strides that would help identifying the size of the last dimension: when
9545/// the array has been statically allocated, one could compute the size of that
9546/// dimension by dividing the overall size of the array by the size of the known
9547/// dimensions: %m * %o * 8.
9548///
9549/// Finally delinearize provides the access functions for the array reference
9550/// that does correspond to A[i][j][k] of the above C testcase:
9551///
9552/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9553///
9554/// The testcases are checking the output of a function pass:
9555/// DelinearizationPass that walks through all loads and stores of a function
9556/// asking for the SCEV of the memory access with respect to all enclosing
9557/// loops, calling SCEV->delinearize on that and printing the results.
9558
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009559void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009560 SmallVectorImpl<const SCEV *> &Subscripts,
9561 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009562 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009563 // First step: collect parametric terms.
9564 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009565 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009566
Sebastian Popb1a548f2014-05-12 19:01:53 +00009567 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009568 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009569
Sebastian Pop448712b2014-05-07 18:01:20 +00009570 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009571 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009572
Sebastian Popb1a548f2014-05-12 19:01:53 +00009573 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009574 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009575
Sebastian Pop448712b2014-05-07 18:01:20 +00009576 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009577 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009578
Sebastian Pop28e6b972014-05-27 22:41:51 +00009579 if (Subscripts.empty())
9580 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009581
Sebastian Pop448712b2014-05-07 18:01:20 +00009582 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009583 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009584 dbgs() << "ArrayDecl[UnknownSize]";
9585 for (const SCEV *S : Sizes)
9586 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009587
Sebastian Pop444621a2014-05-09 22:45:02 +00009588 dbgs() << "\nArrayRef";
9589 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009590 dbgs() << "[" << *S << "]";
9591 dbgs() << "\n";
9592 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009593}
Chris Lattnerd934c702004-04-02 20:23:17 +00009594
9595//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009596// SCEVCallbackVH Class Implementation
9597//===----------------------------------------------------------------------===//
9598
Dan Gohmand33a0902009-05-19 19:22:47 +00009599void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009600 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009601 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9602 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009603 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009604 // this now dangles!
9605}
9606
Dan Gohman7a066722010-07-28 01:09:07 +00009607void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009608 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009609
Dan Gohman48f82222009-05-04 22:30:44 +00009610 // Forget all the expressions associated with users of the old value,
9611 // so that future queries will recompute the expressions using the new
9612 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009613 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009614 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009615 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009616 while (!Worklist.empty()) {
9617 User *U = Worklist.pop_back_val();
9618 // Deleting the Old value will cause this to dangle. Postpone
9619 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009620 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009621 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009622 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009623 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009624 if (PHINode *PN = dyn_cast<PHINode>(U))
9625 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009626 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009627 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009628 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009629 // Delete the Old value.
9630 if (PHINode *PN = dyn_cast<PHINode>(Old))
9631 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009632 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009633 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009634}
9635
Dan Gohmand33a0902009-05-19 19:22:47 +00009636ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009637 : CallbackVH(V), SE(se) {}
9638
9639//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009640// ScalarEvolution Class Implementation
9641//===----------------------------------------------------------------------===//
9642
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009643ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9644 AssumptionCache &AC, DominatorTree &DT,
9645 LoopInfo &LI)
9646 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9647 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009648 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9649 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009650 FirstUnknown(nullptr) {
9651
9652 // To use guards for proving predicates, we need to scan every instruction in
9653 // relevant basic blocks, and not just terminators. Doing this is a waste of
9654 // time if the IR does not actually contain any calls to
9655 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9656 //
9657 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9658 // to _add_ guards to the module when there weren't any before, and wants
9659 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9660 // efficient in lieu of being smart in that rather obscure case.
9661
9662 auto *GuardDecl = F.getParent()->getFunction(
9663 Intrinsic::getName(Intrinsic::experimental_guard));
9664 HasGuards = GuardDecl && !GuardDecl->use_empty();
9665}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009666
9667ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009668 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9669 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009670 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009671 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009672 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009673 PredicatedBackedgeTakenCounts(
9674 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009675 ConstantEvolutionLoopExitValue(
9676 std::move(Arg.ConstantEvolutionLoopExitValue)),
9677 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9678 LoopDispositions(std::move(Arg.LoopDispositions)),
9679 BlockDispositions(std::move(Arg.BlockDispositions)),
9680 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9681 SignedRanges(std::move(Arg.SignedRanges)),
9682 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009683 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009684 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9685 FirstUnknown(Arg.FirstUnknown) {
9686 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009687}
9688
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009689ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009690 // Iterate through all the SCEVUnknown instances and call their
9691 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009692 for (SCEVUnknown *U = FirstUnknown; U;) {
9693 SCEVUnknown *Tmp = U;
9694 U = U->Next;
9695 Tmp->~SCEVUnknown();
9696 }
Craig Topper9f008862014-04-15 04:59:12 +00009697 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009698
Wei Mia49559b2016-02-04 01:27:38 +00009699 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009700 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009701 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009702
9703 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9704 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009705 for (auto &BTCI : BackedgeTakenCounts)
9706 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009707 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9708 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009709
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009710 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009711 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009712 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009713}
9714
Dan Gohmanc8e23622009-04-21 23:15:49 +00009715bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009716 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009717}
9718
Dan Gohmanc8e23622009-04-21 23:15:49 +00009719static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009720 const Loop *L) {
9721 // Print all inner loops first
9722 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
9723 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009724
Dan Gohmanbc694912010-01-09 18:17:45 +00009725 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009726 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009727 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009728
Dan Gohmancb0efec2009-12-18 01:14:11 +00009729 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009730 L->getExitBlocks(ExitBlocks);
9731 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009732 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009733
Dan Gohman0bddac12009-02-24 18:55:53 +00009734 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9735 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009736 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009737 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009738 }
9739
Dan Gohmanbc694912010-01-09 18:17:45 +00009740 OS << "\n"
9741 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009742 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009743 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009744
9745 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9746 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9747 } else {
9748 OS << "Unpredictable max backedge-taken count. ";
9749 }
9750
Silviu Baranga6f444df2016-04-08 14:29:09 +00009751 OS << "\n"
9752 "Loop ";
9753 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9754 OS << ": ";
9755
9756 SCEVUnionPredicate Pred;
9757 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9758 if (!isa<SCEVCouldNotCompute>(PBT)) {
9759 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9760 OS << " Predicates:\n";
9761 Pred.print(OS, 4);
9762 } else {
9763 OS << "Unpredictable predicated backedge-taken count. ";
9764 }
Dan Gohman69942932009-06-24 00:33:16 +00009765 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009766}
9767
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009768static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9769 switch (LD) {
9770 case ScalarEvolution::LoopVariant:
9771 return "Variant";
9772 case ScalarEvolution::LoopInvariant:
9773 return "Invariant";
9774 case ScalarEvolution::LoopComputable:
9775 return "Computable";
9776 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009777 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009778}
9779
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009780void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009781 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009782 // out SCEV values of all instructions that are interesting. Doing
9783 // this potentially causes it to create new SCEV objects though,
9784 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009785 // observable from outside the class though, so casting away the
9786 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009787 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009788
Dan Gohmanbc694912010-01-09 18:17:45 +00009789 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009790 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009791 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009792 for (Instruction &I : instructions(F))
9793 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9794 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009795 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009796 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009797 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009798 if (!isa<SCEVCouldNotCompute>(SV)) {
9799 OS << " U: ";
9800 SE.getUnsignedRange(SV).print(OS);
9801 OS << " S: ";
9802 SE.getSignedRange(SV).print(OS);
9803 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009804
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009805 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009806
Dan Gohmanaf752342009-07-07 17:06:11 +00009807 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009808 if (AtUse != SV) {
9809 OS << " --> ";
9810 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009811 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9812 OS << " U: ";
9813 SE.getUnsignedRange(AtUse).print(OS);
9814 OS << " S: ";
9815 SE.getSignedRange(AtUse).print(OS);
9816 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009817 }
9818
9819 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009820 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009821 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009822 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009823 OS << "<<Unknown>>";
9824 } else {
9825 OS << *ExitValue;
9826 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009827
9828 bool First = true;
9829 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9830 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009831 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009832 First = false;
9833 } else {
9834 OS << ", ";
9835 }
9836
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009837 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9838 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009839 }
9840
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009841 for (auto *InnerL : depth_first(L)) {
9842 if (InnerL == L)
9843 continue;
9844 if (First) {
9845 OS << "\t\t" "LoopDispositions: { ";
9846 First = false;
9847 } else {
9848 OS << ", ";
9849 }
9850
9851 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9852 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9853 }
9854
9855 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009856 }
9857
Chris Lattnerd934c702004-04-02 20:23:17 +00009858 OS << "\n";
9859 }
9860
Dan Gohmanbc694912010-01-09 18:17:45 +00009861 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009862 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009863 OS << "\n";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009864 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
Dan Gohmanc8e23622009-04-21 23:15:49 +00009865 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009866}
Dan Gohmane20f8242009-04-21 00:47:46 +00009867
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009868ScalarEvolution::LoopDisposition
9869ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009870 auto &Values = LoopDispositions[S];
9871 for (auto &V : Values) {
9872 if (V.getPointer() == L)
9873 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009874 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009875 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009876 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009877 auto &Values2 = LoopDispositions[S];
9878 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9879 if (V.getPointer() == L) {
9880 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009881 break;
9882 }
9883 }
9884 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009885}
9886
9887ScalarEvolution::LoopDisposition
9888ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009889 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009890 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009891 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009892 case scTruncate:
9893 case scZeroExtend:
9894 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009895 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009896 case scAddRecExpr: {
9897 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9898
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009899 // If L is the addrec's loop, it's computable.
9900 if (AR->getLoop() == L)
9901 return LoopComputable;
9902
Dan Gohmanafd6db92010-11-17 21:23:15 +00009903 // Add recurrences are never invariant in the function-body (null loop).
9904 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009905 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009906
9907 // This recurrence is variant w.r.t. L if L contains AR's loop.
9908 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009909 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009910
9911 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9912 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009913 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009914
9915 // This recurrence is variant w.r.t. L if any of its operands
9916 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009917 for (auto *Op : AR->operands())
9918 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009919 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009920
9921 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009922 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009923 }
9924 case scAddExpr:
9925 case scMulExpr:
9926 case scUMaxExpr:
9927 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009928 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009929 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9930 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009931 if (D == LoopVariant)
9932 return LoopVariant;
9933 if (D == LoopComputable)
9934 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009935 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009936 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009937 }
9938 case scUDivExpr: {
9939 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009940 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9941 if (LD == LoopVariant)
9942 return LoopVariant;
9943 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9944 if (RD == LoopVariant)
9945 return LoopVariant;
9946 return (LD == LoopInvariant && RD == LoopInvariant) ?
9947 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009948 }
9949 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009950 // All non-instruction values are loop invariant. All instructions are loop
9951 // invariant if they are not contained in the specified loop.
9952 // Instructions are never considered invariant in the function body
9953 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009954 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009955 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9956 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009957 case scCouldNotCompute:
9958 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009959 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009960 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009961}
9962
9963bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9964 return getLoopDisposition(S, L) == LoopInvariant;
9965}
9966
9967bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9968 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009969}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009970
Dan Gohman8ea83d82010-11-18 00:34:22 +00009971ScalarEvolution::BlockDisposition
9972ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009973 auto &Values = BlockDispositions[S];
9974 for (auto &V : Values) {
9975 if (V.getPointer() == BB)
9976 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009977 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009978 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009979 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009980 auto &Values2 = BlockDispositions[S];
9981 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9982 if (V.getPointer() == BB) {
9983 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009984 break;
9985 }
9986 }
9987 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009988}
9989
Dan Gohman8ea83d82010-11-18 00:34:22 +00009990ScalarEvolution::BlockDisposition
9991ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009992 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009993 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009994 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009995 case scTruncate:
9996 case scZeroExtend:
9997 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009998 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009999 case scAddRecExpr: {
10000 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +000010001 // to test for proper dominance too, because the instruction which
10002 // produces the addrec's value is a PHI, and a PHI effectively properly
10003 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +000010004 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010005 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010006 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010007 }
10008 // FALL THROUGH into SCEVNAryExpr handling.
10009 case scAddExpr:
10010 case scMulExpr:
10011 case scUMaxExpr:
10012 case scSMaxExpr: {
10013 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010014 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +000010015 for (const SCEV *NAryOp : NAry->operands()) {
10016 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010017 if (D == DoesNotDominateBlock)
10018 return DoesNotDominateBlock;
10019 if (D == DominatesBlock)
10020 Proper = false;
10021 }
10022 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010023 }
10024 case scUDivExpr: {
10025 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010026 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10027 BlockDisposition LD = getBlockDisposition(LHS, BB);
10028 if (LD == DoesNotDominateBlock)
10029 return DoesNotDominateBlock;
10030 BlockDisposition RD = getBlockDisposition(RHS, BB);
10031 if (RD == DoesNotDominateBlock)
10032 return DoesNotDominateBlock;
10033 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10034 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010035 }
10036 case scUnknown:
10037 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +000010038 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10039 if (I->getParent() == BB)
10040 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010041 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +000010042 return ProperlyDominatesBlock;
10043 return DoesNotDominateBlock;
10044 }
10045 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010046 case scCouldNotCompute:
10047 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +000010048 }
Benjamin Kramer987b8502014-02-11 19:02:55 +000010049 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +000010050}
10051
10052bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10053 return getBlockDisposition(S, BB) >= DominatesBlock;
10054}
10055
10056bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10057 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +000010058}
Dan Gohman534749b2010-11-17 22:27:42 +000010059
10060bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +000010061 // Search for a SCEV expression node within an expression tree.
10062 // Implements SCEVTraversal::Visitor.
10063 struct SCEVSearch {
10064 const SCEV *Node;
10065 bool IsFound;
10066
10067 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
10068
10069 bool follow(const SCEV *S) {
10070 IsFound |= (S == Node);
10071 return !IsFound;
10072 }
10073 bool isDone() const { return IsFound; }
10074 };
10075
Andrew Trick365e31c2012-07-13 23:33:03 +000010076 SCEVSearch Search(Op);
10077 visitAll(S, Search);
10078 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +000010079}
Dan Gohman7e6b3932010-11-17 23:28:48 +000010080
10081void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10082 ValuesAtScopes.erase(S);
10083 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +000010084 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010085 UnsignedRanges.erase(S);
10086 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +000010087 ExprValueMap.erase(S);
10088 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +000010089
Silviu Baranga6f444df2016-04-08 14:29:09 +000010090 auto RemoveSCEVFromBackedgeMap =
10091 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10092 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10093 BackedgeTakenInfo &BEInfo = I->second;
10094 if (BEInfo.hasOperand(S, this)) {
10095 BEInfo.clear();
10096 Map.erase(I++);
10097 } else
10098 ++I;
10099 }
10100 };
10101
10102 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10103 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010104}
Benjamin Kramer214935e2012-10-26 17:31:32 +000010105
10106typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010107
Alp Tokercb402912014-01-24 17:20:08 +000010108/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010109static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10110 size_t Pos = 0;
10111 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10112 Str.replace(Pos, From.size(), To.data(), To.size());
10113 Pos += To.size();
10114 }
10115}
10116
Benjamin Kramer214935e2012-10-26 17:31:32 +000010117/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10118static void
10119getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010120 std::string &S = Map[L];
10121 if (S.empty()) {
10122 raw_string_ostream OS(S);
10123 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010124
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010125 // false and 0 are semantically equivalent. This can happen in dead loops.
10126 replaceSubString(OS.str(), "false", "0");
10127 // Remove wrap flags, their use in SCEV is highly fragile.
10128 // FIXME: Remove this when SCEV gets smarter about them.
10129 replaceSubString(OS.str(), "<nw>", "");
10130 replaceSubString(OS.str(), "<nsw>", "");
10131 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010132 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010133
JF Bastien61ad8b32015-12-23 18:18:53 +000010134 for (auto *R : reverse(*L))
10135 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010136}
10137
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010138void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010139 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10140
10141 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10142 // FIXME: It would be much better to store actual values instead of strings,
10143 // but SCEV pointers will change if we drop the caches.
10144 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010145 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010146 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10147
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010148 // Gather stringified backedge taken counts for all loops using a fresh
10149 // ScalarEvolution object.
10150 ScalarEvolution SE2(F, TLI, AC, DT, LI);
10151 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10152 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010153
10154 // Now compare whether they're the same with and without caches. This allows
10155 // verifying that no pass changed the cache.
10156 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10157 "New loops suddenly appeared!");
10158
10159 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10160 OldE = BackedgeDumpsOld.end(),
10161 NewI = BackedgeDumpsNew.begin();
10162 OldI != OldE; ++OldI, ++NewI) {
10163 assert(OldI->first == NewI->first && "Loop order changed!");
10164
10165 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10166 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010167 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010168 // means that a pass is buggy or SCEV has to learn a new pattern but is
10169 // usually not harmful.
10170 if (OldI->second != NewI->second &&
10171 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010172 NewI->second.find("undef") == std::string::npos &&
10173 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010174 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010175 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010176 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010177 << "' changed from '" << OldI->second
10178 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010179 std::abort();
10180 }
10181 }
10182
10183 // TODO: Verify more things.
10184}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010185
Chandler Carruthb4faf132016-03-11 10:22:49 +000010186char ScalarEvolutionAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010187
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010188ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +000010189 AnalysisManager<Function> &AM) {
10190 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10191 AM.getResult<AssumptionAnalysis>(F),
10192 AM.getResult<DominatorTreeAnalysis>(F),
10193 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010194}
10195
10196PreservedAnalyses
Chandler Carruthb47f8012016-03-11 11:05:24 +000010197ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> &AM) {
10198 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010199 return PreservedAnalyses::all();
10200}
10201
10202INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10203 "Scalar Evolution Analysis", false, true)
10204INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10205INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10206INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10207INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10208INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10209 "Scalar Evolution Analysis", false, true)
10210char ScalarEvolutionWrapperPass::ID = 0;
10211
10212ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10213 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10214}
10215
10216bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10217 SE.reset(new ScalarEvolution(
10218 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10219 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10220 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10221 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10222 return false;
10223}
10224
10225void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10226
10227void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10228 SE->print(OS);
10229}
10230
10231void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10232 if (!VerifySCEV)
10233 return;
10234
10235 SE->verify();
10236}
10237
10238void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10239 AU.setPreservesAll();
10240 AU.addRequiredTransitive<AssumptionCacheTracker>();
10241 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10242 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10243 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10244}
Silviu Barangae3c05342015-11-02 14:41:02 +000010245
10246const SCEVPredicate *
10247ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10248 const SCEVConstant *RHS) {
10249 FoldingSetNodeID ID;
10250 // Unique this node based on the arguments
10251 ID.AddInteger(SCEVPredicate::P_Equal);
10252 ID.AddPointer(LHS);
10253 ID.AddPointer(RHS);
10254 void *IP = nullptr;
10255 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10256 return S;
10257 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10258 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10259 UniquePreds.InsertNode(Eq, IP);
10260 return Eq;
10261}
10262
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010263const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10264 const SCEVAddRecExpr *AR,
10265 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10266 FoldingSetNodeID ID;
10267 // Unique this node based on the arguments
10268 ID.AddInteger(SCEVPredicate::P_Wrap);
10269 ID.AddPointer(AR);
10270 ID.AddInteger(AddedFlags);
10271 void *IP = nullptr;
10272 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10273 return S;
10274 auto *OF = new (SCEVAllocator)
10275 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10276 UniquePreds.InsertNode(OF, IP);
10277 return OF;
10278}
10279
Benjamin Kramer83709b12015-11-16 09:01:28 +000010280namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010281
Silviu Barangae3c05342015-11-02 14:41:02 +000010282class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10283public:
Sanjoy Das807d33d2016-02-20 01:44:10 +000010284 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010285 // If Assume is true, rewrite is free to add further predicates to A
10286 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010287 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10288 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010289 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010290 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010291 }
10292
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010293 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10294 SCEVUnionPredicate &P, bool Assume)
10295 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010296
10297 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10298 auto ExprPreds = P.getPredicatesForExpr(Expr);
10299 for (auto *Pred : ExprPreds)
10300 if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred))
10301 if (IPred->getLHS() == Expr)
10302 return IPred->getRHS();
10303
10304 return Expr;
10305 }
10306
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010307 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10308 const SCEV *Operand = visit(Expr->getOperand());
10309 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
10310 if (AR && AR->getLoop() == L && AR->isAffine()) {
10311 // This couldn't be folded because the operand didn't have the nuw
10312 // flag. Add the nusw flag as an assumption that we could make.
10313 const SCEV *Step = AR->getStepRecurrence(SE);
10314 Type *Ty = Expr->getType();
10315 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10316 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10317 SE.getSignExtendExpr(Step, Ty), L,
10318 AR->getNoWrapFlags());
10319 }
10320 return SE.getZeroExtendExpr(Operand, Expr->getType());
10321 }
10322
10323 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10324 const SCEV *Operand = visit(Expr->getOperand());
10325 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
10326 if (AR && AR->getLoop() == L && AR->isAffine()) {
10327 // This couldn't be folded because the operand didn't have the nsw
10328 // flag. Add the nssw flag as an assumption that we could make.
10329 const SCEV *Step = AR->getStepRecurrence(SE);
10330 Type *Ty = Expr->getType();
10331 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10332 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10333 SE.getSignExtendExpr(Step, Ty), L,
10334 AR->getNoWrapFlags());
10335 }
10336 return SE.getSignExtendExpr(Operand, Expr->getType());
10337 }
10338
Silviu Barangae3c05342015-11-02 14:41:02 +000010339private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010340 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10341 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10342 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10343 if (!Assume) {
10344 // Check if we've already made this assumption.
10345 if (P.implies(A))
10346 return true;
10347 return false;
10348 }
10349 P.add(A);
10350 return true;
10351 }
10352
Silviu Barangae3c05342015-11-02 14:41:02 +000010353 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010354 const Loop *L;
10355 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +000010356};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010357} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010358
Sanjoy Das807d33d2016-02-20 01:44:10 +000010359const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010360 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +000010361 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010362}
10363
Silviu Barangad68ed852016-03-23 15:29:30 +000010364const SCEVAddRecExpr *
Sanjoy Das807d33d2016-02-20 01:44:10 +000010365ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
10366 SCEVUnionPredicate &Preds) {
Silviu Barangad68ed852016-03-23 15:29:30 +000010367 SCEVUnionPredicate TransformPreds;
10368 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true);
10369 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10370
10371 if (!AddRec)
10372 return nullptr;
10373
10374 // Since the transformation was successful, we can now transfer the SCEV
10375 // predicates.
10376 Preds.add(&TransformPreds);
10377 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010378}
10379
10380/// SCEV predicates
10381SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10382 SCEVPredicateKind Kind)
10383 : FastID(ID), Kind(Kind) {}
10384
10385SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10386 const SCEVUnknown *LHS,
10387 const SCEVConstant *RHS)
10388 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10389
10390bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10391 const auto *Op = dyn_cast<const SCEVEqualPredicate>(N);
10392
10393 if (!Op)
10394 return false;
10395
10396 return Op->LHS == LHS && Op->RHS == RHS;
10397}
10398
10399bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10400
10401const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10402
10403void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10404 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10405}
10406
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010407SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10408 const SCEVAddRecExpr *AR,
10409 IncrementWrapFlags Flags)
10410 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10411
10412const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10413
10414bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10415 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10416
10417 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10418}
10419
10420bool SCEVWrapPredicate::isAlwaysTrue() const {
10421 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10422 IncrementWrapFlags IFlags = Flags;
10423
10424 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10425 IFlags = clearFlags(IFlags, IncrementNSSW);
10426
10427 return IFlags == IncrementAnyWrap;
10428}
10429
10430void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10431 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10432 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10433 OS << "<nusw>";
10434 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10435 OS << "<nssw>";
10436 OS << "\n";
10437}
10438
10439SCEVWrapPredicate::IncrementWrapFlags
10440SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10441 ScalarEvolution &SE) {
10442 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10443 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10444
10445 // We can safely transfer the NSW flag as NSSW.
10446 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10447 ImpliedFlags = IncrementNSSW;
10448
10449 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10450 // If the increment is positive, the SCEV NUW flag will also imply the
10451 // WrapPredicate NUSW flag.
10452 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10453 if (Step->getValue()->getValue().isNonNegative())
10454 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10455 }
10456
10457 return ImpliedFlags;
10458}
10459
Silviu Barangae3c05342015-11-02 14:41:02 +000010460/// Union predicates don't get cached so create a dummy set ID for it.
10461SCEVUnionPredicate::SCEVUnionPredicate()
10462 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10463
10464bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010465 return all_of(Preds,
10466 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010467}
10468
10469ArrayRef<const SCEVPredicate *>
10470SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10471 auto I = SCEVToPreds.find(Expr);
10472 if (I == SCEVToPreds.end())
10473 return ArrayRef<const SCEVPredicate *>();
10474 return I->second;
10475}
10476
10477bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10478 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010479 return all_of(Set->Preds,
10480 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010481
10482 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10483 if (ScevPredsIt == SCEVToPreds.end())
10484 return false;
10485 auto &SCEVPreds = ScevPredsIt->second;
10486
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010487 return any_of(SCEVPreds,
10488 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010489}
10490
10491const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10492
10493void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10494 for (auto Pred : Preds)
10495 Pred->print(OS, Depth);
10496}
10497
10498void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10499 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) {
10500 for (auto Pred : Set->Preds)
10501 add(Pred);
10502 return;
10503 }
10504
10505 if (implies(N))
10506 return;
10507
10508 const SCEV *Key = N->getExpr();
10509 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10510 " associated expression!");
10511
10512 SCEVToPreds[Key].push_back(N);
10513 Preds.push_back(N);
10514}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010515
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010516PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10517 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010518 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010519
10520const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10521 const SCEV *Expr = SE.getSCEV(V);
10522 RewriteEntry &Entry = RewriteMap[Expr];
10523
10524 // If we already have an entry and the version matches, return it.
10525 if (Entry.second && Generation == Entry.first)
10526 return Entry.second;
10527
10528 // We found an entry but it's stale. Rewrite the stale entry
10529 // acording to the current predicate.
10530 if (Entry.second)
10531 Expr = Entry.second;
10532
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010533 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010534 Entry = {Generation, NewSCEV};
10535
10536 return NewSCEV;
10537}
10538
Silviu Baranga6f444df2016-04-08 14:29:09 +000010539const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10540 if (!BackedgeCount) {
10541 SCEVUnionPredicate BackedgePred;
10542 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10543 addPredicate(BackedgePred);
10544 }
10545 return BackedgeCount;
10546}
10547
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010548void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10549 if (Preds.implies(&Pred))
10550 return;
10551 Preds.add(&Pred);
10552 updateGeneration();
10553}
10554
10555const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10556 return Preds;
10557}
10558
10559void PredicatedScalarEvolution::updateGeneration() {
10560 // If the generation number wrapped recompute everything.
10561 if (++Generation == 0) {
10562 for (auto &II : RewriteMap) {
10563 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010564 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010565 }
10566 }
10567}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010568
10569void PredicatedScalarEvolution::setNoOverflow(
10570 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10571 const SCEV *Expr = getSCEV(V);
10572 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10573
10574 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10575
10576 // Clear the statically implied flags.
10577 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10578 addPredicate(*SE.getWrapPredicate(AR, Flags));
10579
10580 auto II = FlagsMap.insert({V, Flags});
10581 if (!II.second)
10582 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10583}
10584
10585bool PredicatedScalarEvolution::hasNoOverflow(
10586 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10587 const SCEV *Expr = getSCEV(V);
10588 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10589
10590 Flags = SCEVWrapPredicate::clearFlags(
10591 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10592
10593 auto II = FlagsMap.find(V);
10594
10595 if (II != FlagsMap.end())
10596 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10597
10598 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10599}
10600
Silviu Barangad68ed852016-03-23 15:29:30 +000010601const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010602 const SCEV *Expr = this->getSCEV(V);
Silviu Barangad68ed852016-03-23 15:29:30 +000010603 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10604
10605 if (!New)
10606 return nullptr;
10607
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010608 updateGeneration();
10609 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10610 return New;
10611}
10612
Silviu Baranga6f444df2016-04-08 14:29:09 +000010613PredicatedScalarEvolution::PredicatedScalarEvolution(
10614 const PredicatedScalarEvolution &Init)
10615 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10616 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010617 for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I)
10618 FlagsMap.insert(*I);
10619}
Silviu Barangab77365b2016-04-14 16:08:45 +000010620
10621void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10622 // For each block.
10623 for (auto *BB : L.getBlocks())
10624 for (auto &I : *BB) {
10625 if (!SE.isSCEVable(I.getType()))
10626 continue;
10627
10628 auto *Expr = SE.getSCEV(&I);
10629 auto II = RewriteMap.find(Expr);
10630
10631 if (II == RewriteMap.end())
10632 continue;
10633
10634 // Don't print things that are not interesting.
10635 if (II->second.second == Expr)
10636 continue;
10637
10638 OS.indent(Depth) << "[PSE]" << I << ":\n";
10639 OS.indent(Depth + 2) << *Expr << "\n";
10640 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10641 }
10642}