blob: 746487dcde1b67c562ab2fada449475b287e8024 [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 +0000290bool SCEV::isNonConstantNegative() const {
291 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
292 if (!Mul) return false;
293
294 // If there is a constant factor, it will be first.
295 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
296 if (!SC) return false;
297
298 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000299 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000300}
301
Owen Anderson04052ec2009-06-22 21:57:23 +0000302SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000303 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000304
Chris Lattnerd934c702004-04-02 20:23:17 +0000305bool SCEVCouldNotCompute::classof(const SCEV *S) {
306 return S->getSCEVType() == scCouldNotCompute;
307}
308
Dan Gohmanaf752342009-07-07 17:06:11 +0000309const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000310 FoldingSetNodeID ID;
311 ID.AddInteger(scConstant);
312 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000313 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000314 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000315 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316 UniqueSCEVs.InsertNode(S, IP);
317 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000318}
Chris Lattnerd934c702004-04-02 20:23:17 +0000319
Nick Lewycky31eaca52014-01-27 10:04:03 +0000320const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000321 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000322}
323
Dan Gohmanaf752342009-07-07 17:06:11 +0000324const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000325ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
326 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000327 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000328}
329
Dan Gohman24ceda82010-06-18 19:54:20 +0000330SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000331 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000332 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000333
Dan Gohman24ceda82010-06-18 19:54:20 +0000334SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000335 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000336 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000337 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
338 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000339 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000340}
Chris Lattnerd934c702004-04-02 20:23:17 +0000341
Dan Gohman24ceda82010-06-18 19:54:20 +0000342SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000343 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000344 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000345 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
346 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000347 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000348}
349
Dan Gohman24ceda82010-06-18 19:54:20 +0000350SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000351 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000352 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000353 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
354 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000355 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000356}
357
Dan Gohman7cac9572010-08-02 23:49:30 +0000358void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000359 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000360 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000361
362 // Remove this SCEVUnknown from the uniquing map.
363 SE->UniqueSCEVs.RemoveNode(this);
364
365 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000366 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000367}
368
369void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000370 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000371 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000372
373 // Remove this SCEVUnknown from the uniquing map.
374 SE->UniqueSCEVs.RemoveNode(this);
375
376 // Update this SCEVUnknown to point to the new value. This is needed
377 // because there may still be outstanding SCEVs which still point to
378 // this SCEVUnknown.
379 setValPtr(New);
380}
381
Chris Lattner229907c2011-07-18 04:54:35 +0000382bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue() &&
388 CE->getNumOperands() == 2)
389 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
390 if (CI->isOne()) {
391 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
392 ->getElementType();
393 return true;
394 }
Dan Gohmancf913832010-01-28 02:15:55 +0000395
396 return false;
397}
398
Chris Lattner229907c2011-07-18 04:54:35 +0000399bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000400 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000401 if (VCE->getOpcode() == Instruction::PtrToInt)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000403 if (CE->getOpcode() == Instruction::GetElementPtr &&
404 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000405 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000406 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000407 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 if (!STy->isPacked() &&
409 CE->getNumOperands() == 3 &&
410 CE->getOperand(1)->isNullValue()) {
411 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
412 if (CI->isOne() &&
413 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000414 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 AllocTy = STy->getElementType(1);
416 return true;
417 }
418 }
419 }
Dan Gohmancf913832010-01-28 02:15:55 +0000420
421 return false;
422}
423
Chris Lattner229907c2011-07-18 04:54:35 +0000424bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000425 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000426 if (VCE->getOpcode() == Instruction::PtrToInt)
427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
428 if (CE->getOpcode() == Instruction::GetElementPtr &&
429 CE->getNumOperands() == 3 &&
430 CE->getOperand(0)->isNullValue() &&
431 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000432 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000433 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
434 // Ignore vector types here so that ScalarEvolutionExpander doesn't
435 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000436 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000437 CTy = Ty;
438 FieldNo = CE->getOperand(2);
439 return true;
440 }
441 }
442
443 return false;
444}
445
Chris Lattnereb3e8402004-06-20 06:23:15 +0000446//===----------------------------------------------------------------------===//
447// SCEV Utilities
448//===----------------------------------------------------------------------===//
449
450namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000451/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
452/// than the complexity of the RHS. This comparator is used to canonicalize
453/// expressions.
454class SCEVComplexityCompare {
455 const LoopInfo *const LI;
456public:
457 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000458
Sanjoy Das7881abd2015-12-08 04:32:51 +0000459 // Return true or false if LHS is less than, or at least RHS, respectively.
460 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
461 return compare(LHS, RHS) < 0;
462 }
Dan Gohman27065672010-08-27 15:26:01 +0000463
Sanjoy Das7881abd2015-12-08 04:32:51 +0000464 // Return negative, zero, or positive, if LHS is less than, equal to, or
465 // greater than RHS, respectively. A three-way result allows recursive
466 // comparisons to be more efficient.
467 int compare(const SCEV *LHS, const SCEV *RHS) const {
468 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
469 if (LHS == RHS)
470 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000471
Sanjoy Das7881abd2015-12-08 04:32:51 +0000472 // Primarily, sort the SCEVs by their getSCEVType().
473 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
474 if (LType != RType)
475 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000476
Sanjoy Das7881abd2015-12-08 04:32:51 +0000477 // Aside from the getSCEVType() ordering, the particular ordering
478 // isn't very important except that it's beneficial to be consistent,
479 // so that (a + b) and (b + a) don't end up as different expressions.
480 switch (static_cast<SCEVTypes>(LType)) {
481 case scUnknown: {
482 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
483 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000484
Sanjoy Das7881abd2015-12-08 04:32:51 +0000485 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
486 // not as complete as it could be.
487 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000488
Sanjoy Das7881abd2015-12-08 04:32:51 +0000489 // Order pointer values after integer values. This helps SCEVExpander
490 // form GEPs.
491 bool LIsPointer = LV->getType()->isPointerTy(),
492 RIsPointer = RV->getType()->isPointerTy();
493 if (LIsPointer != RIsPointer)
494 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000495
Sanjoy Das7881abd2015-12-08 04:32:51 +0000496 // Compare getValueID values.
497 unsigned LID = LV->getValueID(),
498 RID = RV->getValueID();
499 if (LID != RID)
500 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000501
Sanjoy Das7881abd2015-12-08 04:32:51 +0000502 // Sort arguments by their position.
503 if (const Argument *LA = dyn_cast<Argument>(LV)) {
504 const Argument *RA = cast<Argument>(RV);
505 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
506 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000507 }
508
Sanjoy Das7881abd2015-12-08 04:32:51 +0000509 // For instructions, compare their loop depth, and their operand
510 // count. This is pretty loose.
511 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
512 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000513
Sanjoy Das7881abd2015-12-08 04:32:51 +0000514 // Compare loop depths.
515 const BasicBlock *LParent = LInst->getParent(),
516 *RParent = RInst->getParent();
517 if (LParent != RParent) {
518 unsigned LDepth = LI->getLoopDepth(LParent),
519 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000520 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000521 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 }
Dan Gohman27065672010-08-27 15:26:01 +0000523
Sanjoy Das7881abd2015-12-08 04:32:51 +0000524 // Compare the number of operands.
525 unsigned LNumOps = LInst->getNumOperands(),
526 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000527 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000528 }
529
Sanjoy Das7881abd2015-12-08 04:32:51 +0000530 return 0;
531 }
Dan Gohman27065672010-08-27 15:26:01 +0000532
Sanjoy Das7881abd2015-12-08 04:32:51 +0000533 case scConstant: {
534 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
535 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
536
537 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000538 const APInt &LA = LC->getAPInt();
539 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000540 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
541 if (LBitWidth != RBitWidth)
542 return (int)LBitWidth - (int)RBitWidth;
543 return LA.ult(RA) ? -1 : 1;
544 }
545
546 case scAddRecExpr: {
547 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
548 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
549
550 // Compare addrec loop depths.
551 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
552 if (LLoop != RLoop) {
553 unsigned LDepth = LLoop->getLoopDepth(),
554 RDepth = RLoop->getLoopDepth();
555 if (LDepth != RDepth)
556 return (int)LDepth - (int)RDepth;
557 }
558
559 // Addrec complexity grows with operand count.
560 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
561 if (LNumOps != RNumOps)
562 return (int)LNumOps - (int)RNumOps;
563
564 // Lexicographically compare.
565 for (unsigned i = 0; i != LNumOps; ++i) {
566 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000567 if (X != 0)
568 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000569 }
570
Sanjoy Das7881abd2015-12-08 04:32:51 +0000571 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000572 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000573
574 case scAddExpr:
575 case scMulExpr:
576 case scSMaxExpr:
577 case scUMaxExpr: {
578 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
579 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
580
581 // Lexicographically compare n-ary expressions.
582 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
583 if (LNumOps != RNumOps)
584 return (int)LNumOps - (int)RNumOps;
585
586 for (unsigned i = 0; i != LNumOps; ++i) {
587 if (i >= RNumOps)
588 return 1;
589 long X = compare(LC->getOperand(i), RC->getOperand(i));
590 if (X != 0)
591 return X;
592 }
593 return (int)LNumOps - (int)RNumOps;
594 }
595
596 case scUDivExpr: {
597 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
598 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
599
600 // Lexicographically compare udiv expressions.
601 long X = compare(LC->getLHS(), RC->getLHS());
602 if (X != 0)
603 return X;
604 return compare(LC->getRHS(), RC->getRHS());
605 }
606
607 case scTruncate:
608 case scZeroExtend:
609 case scSignExtend: {
610 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
611 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
612
613 // Compare cast expressions by operand.
614 return compare(LC->getOperand(), RC->getOperand());
615 }
616
617 case scCouldNotCompute:
618 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
619 }
620 llvm_unreachable("Unknown SCEV kind!");
621 }
622};
623} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000624
Sanjoy Dasf8570812016-05-29 00:38:22 +0000625/// Given a list of SCEV objects, order them by their complexity, and group
626/// objects of the same complexity together by value. When this routine is
627/// finished, we know that any duplicates in the vector are consecutive and that
628/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000629///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000630/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000631/// results from this routine. In other words, we don't want the results of
632/// this to depend on where the addresses of various SCEV objects happened to
633/// land in memory.
634///
Dan Gohmanaf752342009-07-07 17:06:11 +0000635static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000636 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000637 if (Ops.size() < 2) return; // Noop
638 if (Ops.size() == 2) {
639 // This is the common case, which also happens to be trivially simple.
640 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000641 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
642 if (SCEVComplexityCompare(LI)(RHS, LHS))
643 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000644 return;
645 }
646
Dan Gohman24ceda82010-06-18 19:54:20 +0000647 // Do the rough sort by complexity.
648 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
649
650 // Now that we are sorted by complexity, group elements of the same
651 // complexity. Note that this is, at worst, N^2, but the vector is likely to
652 // be extremely short in practice. Note that we take this approach because we
653 // do not want to depend on the addresses of the objects we are grouping.
654 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
655 const SCEV *S = Ops[i];
656 unsigned Complexity = S->getSCEVType();
657
658 // If there are any objects of the same complexity and same value as this
659 // one, group them.
660 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
661 if (Ops[j] == S) { // Found a duplicate.
662 // Move it to immediately after i'th element.
663 std::swap(Ops[i+1], Ops[j]);
664 ++i; // no need to rescan it.
665 if (i == e-2) return; // Done!
666 }
667 }
668 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000669}
670
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000671// Returns the size of the SCEV S.
672static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000673 struct FindSCEVSize {
674 int Size;
675 FindSCEVSize() : Size(0) {}
676
677 bool follow(const SCEV *S) {
678 ++Size;
679 // Keep looking at all operands of S.
680 return true;
681 }
682 bool isDone() const {
683 return false;
684 }
685 };
686
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000687 FindSCEVSize F;
688 SCEVTraversal<FindSCEVSize> ST(F);
689 ST.visitAll(S);
690 return F.Size;
691}
692
693namespace {
694
David Majnemer4e879362014-12-14 09:12:33 +0000695struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000696public:
697 // Computes the Quotient and Remainder of the division of Numerator by
698 // Denominator.
699 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
700 const SCEV *Denominator, const SCEV **Quotient,
701 const SCEV **Remainder) {
702 assert(Numerator && Denominator && "Uninitialized SCEV");
703
David Majnemer4e879362014-12-14 09:12:33 +0000704 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000705
706 // Check for the trivial case here to avoid having to check for it in the
707 // rest of the code.
708 if (Numerator == Denominator) {
709 *Quotient = D.One;
710 *Remainder = D.Zero;
711 return;
712 }
713
714 if (Numerator->isZero()) {
715 *Quotient = D.Zero;
716 *Remainder = D.Zero;
717 return;
718 }
719
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000720 // A simple case when N/1. The quotient is N.
721 if (Denominator->isOne()) {
722 *Quotient = Numerator;
723 *Remainder = D.Zero;
724 return;
725 }
726
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000727 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000728 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000729 const SCEV *Q, *R;
730 *Quotient = Numerator;
731 for (const SCEV *Op : T->operands()) {
732 divide(SE, *Quotient, Op, &Q, &R);
733 *Quotient = Q;
734
735 // Bail out when the Numerator is not divisible by one of the terms of
736 // the Denominator.
737 if (!R->isZero()) {
738 *Quotient = D.Zero;
739 *Remainder = Numerator;
740 return;
741 }
742 }
743 *Remainder = D.Zero;
744 return;
745 }
746
747 D.visit(Numerator);
748 *Quotient = D.Quotient;
749 *Remainder = D.Remainder;
750 }
751
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000752 // Except in the trivial case described above, we do not know how to divide
753 // Expr by Denominator for the following functions with empty implementation.
754 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
755 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
756 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
757 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
758 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
759 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
760 void visitUnknown(const SCEVUnknown *Numerator) {}
761 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
762
David Majnemer4e879362014-12-14 09:12:33 +0000763 void visitConstant(const SCEVConstant *Numerator) {
764 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000765 APInt NumeratorVal = Numerator->getAPInt();
766 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000767 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
768 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
769
770 if (NumeratorBW > DenominatorBW)
771 DenominatorVal = DenominatorVal.sext(NumeratorBW);
772 else if (NumeratorBW < DenominatorBW)
773 NumeratorVal = NumeratorVal.sext(DenominatorBW);
774
775 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
776 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
777 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
778 Quotient = SE.getConstant(QuotientVal);
779 Remainder = SE.getConstant(RemainderVal);
780 return;
781 }
782 }
783
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000784 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
785 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000786 if (!Numerator->isAffine())
787 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000788 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
789 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000790 // Bail out if the types do not match.
791 Type *Ty = Denominator->getType();
792 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000793 Ty != StepQ->getType() || Ty != StepR->getType())
794 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000795 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
796 Numerator->getNoWrapFlags());
797 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 }
800
801 void visitAddExpr(const SCEVAddExpr *Numerator) {
802 SmallVector<const SCEV *, 2> Qs, Rs;
803 Type *Ty = Denominator->getType();
804
805 for (const SCEV *Op : Numerator->operands()) {
806 const SCEV *Q, *R;
807 divide(SE, Op, Denominator, &Q, &R);
808
809 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000810 if (Ty != Q->getType() || Ty != R->getType())
811 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000812
813 Qs.push_back(Q);
814 Rs.push_back(R);
815 }
816
817 if (Qs.size() == 1) {
818 Quotient = Qs[0];
819 Remainder = Rs[0];
820 return;
821 }
822
823 Quotient = SE.getAddExpr(Qs);
824 Remainder = SE.getAddExpr(Rs);
825 }
826
827 void visitMulExpr(const SCEVMulExpr *Numerator) {
828 SmallVector<const SCEV *, 2> Qs;
829 Type *Ty = Denominator->getType();
830
831 bool FoundDenominatorTerm = false;
832 for (const SCEV *Op : Numerator->operands()) {
833 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000834 if (Ty != Op->getType())
835 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000836
837 if (FoundDenominatorTerm) {
838 Qs.push_back(Op);
839 continue;
840 }
841
842 // Check whether Denominator divides one of the product operands.
843 const SCEV *Q, *R;
844 divide(SE, Op, Denominator, &Q, &R);
845 if (!R->isZero()) {
846 Qs.push_back(Op);
847 continue;
848 }
849
850 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000851 if (Ty != Q->getType())
852 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000853
854 FoundDenominatorTerm = true;
855 Qs.push_back(Q);
856 }
857
858 if (FoundDenominatorTerm) {
859 Remainder = Zero;
860 if (Qs.size() == 1)
861 Quotient = Qs[0];
862 else
863 Quotient = SE.getMulExpr(Qs);
864 return;
865 }
866
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000867 if (!isa<SCEVUnknown>(Denominator))
868 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000869
870 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
871 ValueToValueMap RewriteMap;
872 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
873 cast<SCEVConstant>(Zero)->getValue();
874 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
875
876 if (Remainder->isZero()) {
877 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
878 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
879 cast<SCEVConstant>(One)->getValue();
880 Quotient =
881 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
882 return;
883 }
884
885 // Quotient is (Numerator - Remainder) divided by Denominator.
886 const SCEV *Q, *R;
887 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000888 // This SCEV does not seem to simplify: fail the division here.
889 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
890 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000891 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000892 if (R != Zero)
893 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000894 Quotient = Q;
895 }
896
897private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000898 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
899 const SCEV *Denominator)
900 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000901 Zero = SE.getZero(Denominator->getType());
902 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000903
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000904 // We generally do not know how to divide Expr by Denominator. We
905 // initialize the division to a "cannot divide" state to simplify the rest
906 // of the code.
907 cannotDivide(Numerator);
908 }
909
910 // Convenience function for giving up on the division. We set the quotient to
911 // be equal to zero and the remainder to be equal to the numerator.
912 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000913 Quotient = Zero;
914 Remainder = Numerator;
915 }
916
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000917 ScalarEvolution &SE;
918 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000919};
920
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000921}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000922
Chris Lattnerd934c702004-04-02 20:23:17 +0000923//===----------------------------------------------------------------------===//
924// Simple SCEV method implementations
925//===----------------------------------------------------------------------===//
926
Sanjoy Dasf8570812016-05-29 00:38:22 +0000927/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000928static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000929 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000930 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000931 // Handle the simplest case efficiently.
932 if (K == 1)
933 return SE.getTruncateOrZeroExtend(It, ResultTy);
934
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000935 // We are using the following formula for BC(It, K):
936 //
937 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
938 //
Eli Friedman61f67622008-08-04 23:49:06 +0000939 // Suppose, W is the bitwidth of the return value. We must be prepared for
940 // overflow. Hence, we must assure that the result of our computation is
941 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
942 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000943 //
Eli Friedman61f67622008-08-04 23:49:06 +0000944 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000945 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000946 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
947 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000948 //
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000950 //
Eli Friedman61f67622008-08-04 23:49:06 +0000951 // This formula is trivially equivalent to the previous formula. However,
952 // this formula can be implemented much more efficiently. The trick is that
953 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
954 // arithmetic. To do exact division in modular arithmetic, all we have
955 // to do is multiply by the inverse. Therefore, this step can be done at
956 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000957 //
Eli Friedman61f67622008-08-04 23:49:06 +0000958 // The next issue is how to safely do the division by 2^T. The way this
959 // is done is by doing the multiplication step at a width of at least W + T
960 // bits. This way, the bottom W+T bits of the product are accurate. Then,
961 // when we perform the division by 2^T (which is equivalent to a right shift
962 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
963 // truncated out after the division by 2^T.
964 //
965 // In comparison to just directly using the first formula, this technique
966 // is much more efficient; using the first formula requires W * K bits,
967 // but this formula less than W + K bits. Also, the first formula requires
968 // a division step, whereas this formula only requires multiplies and shifts.
969 //
970 // It doesn't matter whether the subtraction step is done in the calculation
971 // width or the input iteration count's width; if the subtraction overflows,
972 // the result must be zero anyway. We prefer here to do it in the width of
973 // the induction variable because it helps a lot for certain cases; CodeGen
974 // isn't smart enough to ignore the overflow, which leads to much less
975 // efficient code if the width of the subtraction is wider than the native
976 // register width.
977 //
978 // (It's possible to not widen at all by pulling out factors of 2 before
979 // the multiplication; for example, K=2 can be calculated as
980 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
981 // extra arithmetic, so it's not an obvious win, and it gets
982 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000983
Eli Friedman61f67622008-08-04 23:49:06 +0000984 // Protection from insane SCEVs; this bound is conservative,
985 // but it probably doesn't matter.
986 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000987 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000988
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000989 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000990
Eli Friedman61f67622008-08-04 23:49:06 +0000991 // Calculate K! / 2^T and T; we divide out the factors of two before
992 // multiplying for calculating K! / 2^T to avoid overflow.
993 // Other overflow doesn't matter because we only care about the bottom
994 // W bits of the result.
995 APInt OddFactorial(W, 1);
996 unsigned T = 1;
997 for (unsigned i = 3; i <= K; ++i) {
998 APInt Mult(W, i);
999 unsigned TwoFactors = Mult.countTrailingZeros();
1000 T += TwoFactors;
1001 Mult = Mult.lshr(TwoFactors);
1002 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001003 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001004
Eli Friedman61f67622008-08-04 23:49:06 +00001005 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001006 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001007
Dan Gohman8b0a4192010-03-01 17:49:51 +00001008 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001009 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001010
1011 // Calculate the multiplicative inverse of K! / 2^T;
1012 // this multiplication factor will perform the exact division by
1013 // K! / 2^T.
1014 APInt Mod = APInt::getSignedMinValue(W+1);
1015 APInt MultiplyFactor = OddFactorial.zext(W+1);
1016 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1017 MultiplyFactor = MultiplyFactor.trunc(W);
1018
1019 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001020 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001021 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001022 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001023 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001024 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001025 Dividend = SE.getMulExpr(Dividend,
1026 SE.getTruncateOrZeroExtend(S, CalculationTy));
1027 }
1028
1029 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001030 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001031
1032 // Truncate the result, and divide by K! / 2^T.
1033
1034 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1035 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001036}
1037
Sanjoy Dasf8570812016-05-29 00:38:22 +00001038/// Return the value of this chain of recurrences at the specified iteration
1039/// number. We can evaluate this recurrence by multiplying each element in the
1040/// chain by the binomial coefficient corresponding to it. In other words, we
1041/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001042///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001043/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001044///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001045/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001046///
Dan Gohmanaf752342009-07-07 17:06:11 +00001047const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001048 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001049 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001050 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001051 // The computation is correct in the face of overflow provided that the
1052 // multiplication is performed _after_ the evaluation of the binomial
1053 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001054 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001055 if (isa<SCEVCouldNotCompute>(Coeff))
1056 return Coeff;
1057
1058 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001059 }
1060 return Result;
1061}
1062
Chris Lattnerd934c702004-04-02 20:23:17 +00001063//===----------------------------------------------------------------------===//
1064// SCEV Expression folder implementations
1065//===----------------------------------------------------------------------===//
1066
Dan Gohmanaf752342009-07-07 17:06:11 +00001067const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001068 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001069 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001070 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001071 assert(isSCEVable(Ty) &&
1072 "This is not a conversion to a SCEVable type!");
1073 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001074
Dan Gohman3a302cb2009-07-13 20:50:19 +00001075 FoldingSetNodeID ID;
1076 ID.AddInteger(scTruncate);
1077 ID.AddPointer(Op);
1078 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001079 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001080 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1081
Dan Gohman3423e722009-06-30 20:13:32 +00001082 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001083 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001084 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001085 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001086
Dan Gohman79af8542009-04-22 16:20:48 +00001087 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001088 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001089 return getTruncateExpr(ST->getOperand(), Ty);
1090
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001091 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001092 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001093 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1094
1095 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001096 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001097 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1098
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001099 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001100 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001101 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1102 SmallVector<const SCEV *, 4> Operands;
1103 bool hasTrunc = false;
1104 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1105 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001106 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1107 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001108 Operands.push_back(S);
1109 }
1110 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001111 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001112 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001113 }
1114
Nick Lewycky5c901f32011-01-19 18:56:00 +00001115 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001116 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001117 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1118 SmallVector<const SCEV *, 4> Operands;
1119 bool hasTrunc = false;
1120 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1121 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001122 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1123 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001124 Operands.push_back(S);
1125 }
1126 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001127 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001128 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001129 }
1130
Dan Gohman5a728c92009-06-18 16:24:47 +00001131 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001132 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001133 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001134 for (const SCEV *Op : AddRec->operands())
1135 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001136 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001137 }
1138
Dan Gohman89dd42a2010-06-25 18:47:08 +00001139 // The cast wasn't folded; create an explicit cast node. We can reuse
1140 // the existing insert position since if we get here, we won't have
1141 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001142 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1143 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001144 UniqueSCEVs.InsertNode(S, IP);
1145 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001146}
1147
Sanjoy Das4153f472015-02-18 01:47:07 +00001148// Get the limit of a recurrence such that incrementing by Step cannot cause
1149// signed overflow as long as the value of the recurrence within the
1150// loop does not exceed this limit before incrementing.
1151static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1152 ICmpInst::Predicate *Pred,
1153 ScalarEvolution *SE) {
1154 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1155 if (SE->isKnownPositive(Step)) {
1156 *Pred = ICmpInst::ICMP_SLT;
1157 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1158 SE->getSignedRange(Step).getSignedMax());
1159 }
1160 if (SE->isKnownNegative(Step)) {
1161 *Pred = ICmpInst::ICMP_SGT;
1162 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1163 SE->getSignedRange(Step).getSignedMin());
1164 }
1165 return nullptr;
1166}
1167
1168// Get the limit of a recurrence such that incrementing by Step cannot cause
1169// unsigned overflow as long as the value of the recurrence within the loop does
1170// not exceed this limit before incrementing.
1171static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1172 ICmpInst::Predicate *Pred,
1173 ScalarEvolution *SE) {
1174 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1175 *Pred = ICmpInst::ICMP_ULT;
1176
1177 return SE->getConstant(APInt::getMinValue(BitWidth) -
1178 SE->getUnsignedRange(Step).getUnsignedMax());
1179}
1180
1181namespace {
1182
1183struct ExtendOpTraitsBase {
1184 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1185};
1186
1187// Used to make code generic over signed and unsigned overflow.
1188template <typename ExtendOp> struct ExtendOpTraits {
1189 // Members present:
1190 //
1191 // static const SCEV::NoWrapFlags WrapType;
1192 //
1193 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1194 //
1195 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1196 // ICmpInst::Predicate *Pred,
1197 // ScalarEvolution *SE);
1198};
1199
1200template <>
1201struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1202 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1203
1204 static const GetExtendExprTy GetExtendExpr;
1205
1206 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1207 ICmpInst::Predicate *Pred,
1208 ScalarEvolution *SE) {
1209 return getSignedOverflowLimitForStep(Step, Pred, SE);
1210 }
1211};
1212
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001213const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001214 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1215
1216template <>
1217struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1218 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1219
1220 static const GetExtendExprTy GetExtendExpr;
1221
1222 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1223 ICmpInst::Predicate *Pred,
1224 ScalarEvolution *SE) {
1225 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1226 }
1227};
1228
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001229const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001230 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001231}
Sanjoy Das4153f472015-02-18 01:47:07 +00001232
1233// The recurrence AR has been shown to have no signed/unsigned wrap or something
1234// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1235// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1236// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1237// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1238// expression "Step + sext/zext(PreIncAR)" is congruent with
1239// "sext/zext(PostIncAR)"
1240template <typename ExtendOpTy>
1241static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1242 ScalarEvolution *SE) {
1243 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1244 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1245
1246 const Loop *L = AR->getLoop();
1247 const SCEV *Start = AR->getStart();
1248 const SCEV *Step = AR->getStepRecurrence(*SE);
1249
1250 // Check for a simple looking step prior to loop entry.
1251 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1252 if (!SA)
1253 return nullptr;
1254
1255 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1256 // subtraction is expensive. For this purpose, perform a quick and dirty
1257 // difference, by checking for Step in the operand list.
1258 SmallVector<const SCEV *, 4> DiffOps;
1259 for (const SCEV *Op : SA->operands())
1260 if (Op != Step)
1261 DiffOps.push_back(Op);
1262
1263 if (DiffOps.size() == SA->getNumOperands())
1264 return nullptr;
1265
1266 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1267 // `Step`:
1268
1269 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001270 auto PreStartFlags =
1271 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1272 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001273 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1274 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1275
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001276 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1277 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001278 //
1279
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001280 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1281 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1282 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001283 return PreStart;
1284
1285 // 2. Direct overflow check on the step operation's expression.
1286 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1287 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1288 const SCEV *OperandExtendedStart =
1289 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1290 (SE->*GetExtendExpr)(Step, WideTy));
1291 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1292 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1293 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1294 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1295 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1296 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1297 }
1298 return PreStart;
1299 }
1300
1301 // 3. Loop precondition.
1302 ICmpInst::Predicate Pred;
1303 const SCEV *OverflowLimit =
1304 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1305
1306 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001307 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001308 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001309
Sanjoy Das4153f472015-02-18 01:47:07 +00001310 return nullptr;
1311}
1312
1313// Get the normalized zero or sign extended expression for this AddRec's Start.
1314template <typename ExtendOpTy>
1315static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1316 ScalarEvolution *SE) {
1317 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1318
1319 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1320 if (!PreStart)
1321 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1322
1323 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1324 (SE->*GetExtendExpr)(PreStart, Ty));
1325}
1326
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001327// Try to prove away overflow by looking at "nearby" add recurrences. A
1328// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1329// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1330//
1331// Formally:
1332//
1333// {S,+,X} == {S-T,+,X} + T
1334// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1335//
1336// If ({S-T,+,X} + T) does not overflow ... (1)
1337//
1338// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1339//
1340// If {S-T,+,X} does not overflow ... (2)
1341//
1342// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1343// == {Ext(S-T)+Ext(T),+,Ext(X)}
1344//
1345// If (S-T)+T does not overflow ... (3)
1346//
1347// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1348// == {Ext(S),+,Ext(X)} == LHS
1349//
1350// Thus, if (1), (2) and (3) are true for some T, then
1351// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1352//
1353// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1354// does not overflow" restricted to the 0th iteration. Therefore we only need
1355// to check for (1) and (2).
1356//
1357// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1358// is `Delta` (defined below).
1359//
1360template <typename ExtendOpTy>
1361bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1362 const SCEV *Step,
1363 const Loop *L) {
1364 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1365
1366 // We restrict `Start` to a constant to prevent SCEV from spending too much
1367 // time here. It is correct (but more expensive) to continue with a
1368 // non-constant `Start` and do a general SCEV subtraction to compute
1369 // `PreStart` below.
1370 //
1371 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1372 if (!StartC)
1373 return false;
1374
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001375 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001376
1377 for (unsigned Delta : {-2, -1, 1, 2}) {
1378 const SCEV *PreStart = getConstant(StartAI - Delta);
1379
Sanjoy Das42801102015-10-23 06:57:21 +00001380 FoldingSetNodeID ID;
1381 ID.AddInteger(scAddRecExpr);
1382 ID.AddPointer(PreStart);
1383 ID.AddPointer(Step);
1384 ID.AddPointer(L);
1385 void *IP = nullptr;
1386 const auto *PreAR =
1387 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1388
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001389 // Give up if we don't already have the add recurrence we need because
1390 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001391 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1392 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1393 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1394 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1395 DeltaS, &Pred, this);
1396 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1397 return true;
1398 }
1399 }
1400
1401 return false;
1402}
1403
Dan Gohmanaf752342009-07-07 17:06:11 +00001404const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001405 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001406 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001407 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001408 assert(isSCEVable(Ty) &&
1409 "This is not a conversion to a SCEVable type!");
1410 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001411
Dan Gohman3423e722009-06-30 20:13:32 +00001412 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001413 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1414 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001415 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001416
Dan Gohman79af8542009-04-22 16:20:48 +00001417 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001418 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001419 return getZeroExtendExpr(SZ->getOperand(), Ty);
1420
Dan Gohman74a0ba12009-07-13 20:55:53 +00001421 // Before doing any expensive analysis, check to see if we've already
1422 // computed a SCEV for this Op and Ty.
1423 FoldingSetNodeID ID;
1424 ID.AddInteger(scZeroExtend);
1425 ID.AddPointer(Op);
1426 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001427 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001428 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1429
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001430 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1431 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1432 // It's possible the bits taken off by the truncate were all zero bits. If
1433 // so, we should be able to simplify this further.
1434 const SCEV *X = ST->getOperand();
1435 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001436 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1437 unsigned NewBits = getTypeSizeInBits(Ty);
1438 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001439 CR.zextOrTrunc(NewBits)))
1440 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001441 }
1442
Dan Gohman76466372009-04-27 20:16:15 +00001443 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001444 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001445 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001446 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001447 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001448 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001449 const SCEV *Start = AR->getStart();
1450 const SCEV *Step = AR->getStepRecurrence(*this);
1451 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1452 const Loop *L = AR->getLoop();
1453
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001454 if (!AR->hasNoUnsignedWrap()) {
1455 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1456 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1457 }
1458
Dan Gohman62ef6a72009-07-25 01:22:26 +00001459 // If we have special knowledge that this addrec won't overflow,
1460 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001461 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001462 return getAddRecExpr(
1463 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1464 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001465
Dan Gohman76466372009-04-27 20:16:15 +00001466 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1467 // Note that this serves two purposes: It filters out loops that are
1468 // simply not analyzable, and it covers the case where this code is
1469 // being called from within backedge-taken count analysis, such that
1470 // attempting to ask for the backedge-taken count would likely result
1471 // in infinite recursion. In the later case, the analysis code will
1472 // cope with a conservative value, and it will take care to purge
1473 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001474 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001475 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001476 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001477 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001478
1479 // Check whether the backedge-taken count can be losslessly casted to
1480 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001481 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001482 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001483 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001484 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1485 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001486 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001487 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001488 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001489 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1490 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1491 const SCEV *WideMaxBECount =
1492 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001493 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001494 getAddExpr(WideStart,
1495 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001496 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001497 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001498 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1499 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001500 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001501 return getAddRecExpr(
1502 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1503 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001504 }
Dan Gohman76466372009-04-27 20:16:15 +00001505 // Similar to above, only this time treat the step value as signed.
1506 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001507 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001508 getAddExpr(WideStart,
1509 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001510 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001511 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001512 // Cache knowledge of AR NW, which is propagated to this AddRec.
1513 // Negative step causes unsigned wrap, but it still can't self-wrap.
1514 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001515 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001516 return getAddRecExpr(
1517 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1518 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001519 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001520 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001521 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001522
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001523 // Normally, in the cases we can prove no-overflow via a
1524 // backedge guarding condition, we can also compute a backedge
1525 // taken count for the loop. The exceptions are assumptions and
1526 // guards present in the loop -- SCEV is not great at exploiting
1527 // these to compute max backedge taken counts, but can still use
1528 // these to prove lack of overflow. Use this fact to avoid
1529 // doing extra work that may not pay off.
1530 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1531 !AC.assumptions().empty()) {
1532 // If the backedge is guarded by a comparison with the pre-inc
1533 // value the addrec is safe. Also, if the entry is guarded by
1534 // a comparison with the start value and the backedge is
1535 // guarded by a comparison with the post-inc value, the addrec
1536 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001537 if (isKnownPositive(Step)) {
1538 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1539 getUnsignedRange(Step).getUnsignedMax());
1540 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001541 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001542 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001543 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001544 // Cache knowledge of AR NUW, which is propagated to this
1545 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001546 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001547 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001548 return getAddRecExpr(
1549 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1550 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001551 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001552 } else if (isKnownNegative(Step)) {
1553 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1554 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001555 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1556 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001557 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001558 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001559 // Cache knowledge of AR NW, which is propagated to this
1560 // AddRec. Negative step causes unsigned wrap, but it
1561 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001562 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1563 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001564 return getAddRecExpr(
1565 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1566 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001567 }
Dan Gohman76466372009-04-27 20:16:15 +00001568 }
1569 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001570
1571 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1572 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1573 return getAddRecExpr(
1574 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1575 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1576 }
Dan Gohman76466372009-04-27 20:16:15 +00001577 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001578
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001579 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1580 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001581 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001582 // If the addition does not unsign overflow then we can, by definition,
1583 // commute the zero extension with the addition operation.
1584 SmallVector<const SCEV *, 4> Ops;
1585 for (const auto *Op : SA->operands())
1586 Ops.push_back(getZeroExtendExpr(Op, Ty));
1587 return getAddExpr(Ops, SCEV::FlagNUW);
1588 }
1589 }
1590
Dan Gohman74a0ba12009-07-13 20:55:53 +00001591 // The cast wasn't folded; create an explicit cast node.
1592 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001593 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001594 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1595 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001596 UniqueSCEVs.InsertNode(S, IP);
1597 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001598}
1599
Dan Gohmanaf752342009-07-07 17:06:11 +00001600const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001601 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001602 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001603 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001604 assert(isSCEVable(Ty) &&
1605 "This is not a conversion to a SCEVable type!");
1606 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001607
Dan Gohman3423e722009-06-30 20:13:32 +00001608 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001609 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1610 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001611 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001612
Dan Gohman79af8542009-04-22 16:20:48 +00001613 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001614 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001615 return getSignExtendExpr(SS->getOperand(), Ty);
1616
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001617 // sext(zext(x)) --> zext(x)
1618 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1619 return getZeroExtendExpr(SZ->getOperand(), Ty);
1620
Dan Gohman74a0ba12009-07-13 20:55:53 +00001621 // Before doing any expensive analysis, check to see if we've already
1622 // computed a SCEV for this Op and Ty.
1623 FoldingSetNodeID ID;
1624 ID.AddInteger(scSignExtend);
1625 ID.AddPointer(Op);
1626 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001627 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001628 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1629
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001630 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1631 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1632 // It's possible the bits taken off by the truncate were all sign bits. If
1633 // so, we should be able to simplify this further.
1634 const SCEV *X = ST->getOperand();
1635 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001636 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1637 unsigned NewBits = getTypeSizeInBits(Ty);
1638 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001639 CR.sextOrTrunc(NewBits)))
1640 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001641 }
1642
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001643 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001644 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001645 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001646 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1647 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001648 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001649 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001650 const APInt &C1 = SC1->getAPInt();
1651 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001652 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001653 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001654 return getAddExpr(getSignExtendExpr(SC1, Ty),
1655 getSignExtendExpr(SMul, Ty));
1656 }
1657 }
1658 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001659
1660 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001661 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001662 // If the addition does not sign overflow then we can, by definition,
1663 // commute the sign extension with the addition operation.
1664 SmallVector<const SCEV *, 4> Ops;
1665 for (const auto *Op : SA->operands())
1666 Ops.push_back(getSignExtendExpr(Op, Ty));
1667 return getAddExpr(Ops, SCEV::FlagNSW);
1668 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001669 }
Dan Gohman76466372009-04-27 20:16:15 +00001670 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001671 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001672 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001673 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001674 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001675 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001676 const SCEV *Start = AR->getStart();
1677 const SCEV *Step = AR->getStepRecurrence(*this);
1678 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1679 const Loop *L = AR->getLoop();
1680
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001681 if (!AR->hasNoSignedWrap()) {
1682 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1683 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1684 }
1685
Dan Gohman62ef6a72009-07-25 01:22:26 +00001686 // If we have special knowledge that this addrec won't overflow,
1687 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001688 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001689 return getAddRecExpr(
1690 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1691 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001692
Dan Gohman76466372009-04-27 20:16:15 +00001693 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1694 // Note that this serves two purposes: It filters out loops that are
1695 // simply not analyzable, and it covers the case where this code is
1696 // being called from within backedge-taken count analysis, such that
1697 // attempting to ask for the backedge-taken count would likely result
1698 // in infinite recursion. In the later case, the analysis code will
1699 // cope with a conservative value, and it will take care to purge
1700 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001701 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001702 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001703 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001704 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001705
1706 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001707 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001708 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001709 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001710 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001711 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1712 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001713 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001714 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001715 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001716 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1717 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1718 const SCEV *WideMaxBECount =
1719 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001720 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001721 getAddExpr(WideStart,
1722 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001723 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001724 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001725 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1726 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001727 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001728 return getAddRecExpr(
1729 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1730 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001731 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001732 // Similar to above, only this time treat the step value as unsigned.
1733 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001734 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001735 getAddExpr(WideStart,
1736 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001737 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001738 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001739 // If AR wraps around then
1740 //
1741 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1742 // => SAdd != OperandExtendedAdd
1743 //
1744 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1745 // (SAdd == OperandExtendedAdd => AR is NW)
1746
1747 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1748
Dan Gohman8c129d72009-07-16 17:34:36 +00001749 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001750 return getAddRecExpr(
1751 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1752 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001753 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001754 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001755 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001756
Sanjoy Das787c2462016-05-11 17:41:26 +00001757 // Normally, in the cases we can prove no-overflow via a
1758 // backedge guarding condition, we can also compute a backedge
1759 // taken count for the loop. The exceptions are assumptions and
1760 // guards present in the loop -- SCEV is not great at exploiting
1761 // these to compute max backedge taken counts, but can still use
1762 // these to prove lack of overflow. Use this fact to avoid
1763 // doing extra work that may not pay off.
1764
1765 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1766 !AC.assumptions().empty()) {
1767 // If the backedge is guarded by a comparison with the pre-inc
1768 // value the addrec is safe. Also, if the entry is guarded by
1769 // a comparison with the start value and the backedge is
1770 // guarded by a comparison with the post-inc value, the addrec
1771 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001772 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001773 const SCEV *OverflowLimit =
1774 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001775 if (OverflowLimit &&
1776 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1777 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1778 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1779 OverflowLimit)))) {
1780 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1781 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001782 return getAddRecExpr(
1783 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1784 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001785 }
1786 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001787
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001788 // If Start and Step are constants, check if we can apply this
1789 // transformation:
1790 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001791 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1792 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001793 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001794 const APInt &C1 = SC1->getAPInt();
1795 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001796 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1797 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001798 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001799 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1800 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001801 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1802 }
1803 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001804
1805 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1806 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1807 return getAddRecExpr(
1808 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1809 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1810 }
Dan Gohman76466372009-04-27 20:16:15 +00001811 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001812
Sanjoy Das11ef6062016-03-03 18:31:23 +00001813 // If the input value is provably positive and we could not simplify
1814 // away the sext build a zext instead.
1815 if (isKnownNonNegative(Op))
1816 return getZeroExtendExpr(Op, Ty);
1817
Dan Gohman74a0ba12009-07-13 20:55:53 +00001818 // The cast wasn't folded; create an explicit cast node.
1819 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001820 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001821 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1822 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001823 UniqueSCEVs.InsertNode(S, IP);
1824 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001825}
1826
Dan Gohman8db2edc2009-06-13 15:56:47 +00001827/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1828/// unspecified bits out to the given type.
1829///
Dan Gohmanaf752342009-07-07 17:06:11 +00001830const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001831 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001832 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1833 "This is not an extending conversion!");
1834 assert(isSCEVable(Ty) &&
1835 "This is not a conversion to a SCEVable type!");
1836 Ty = getEffectiveSCEVType(Ty);
1837
1838 // Sign-extend negative constants.
1839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001840 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001841 return getSignExtendExpr(Op, Ty);
1842
1843 // Peel off a truncate cast.
1844 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001845 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001846 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1847 return getAnyExtendExpr(NewOp, Ty);
1848 return getTruncateOrNoop(NewOp, Ty);
1849 }
1850
1851 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001852 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001853 if (!isa<SCEVZeroExtendExpr>(ZExt))
1854 return ZExt;
1855
1856 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001857 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001858 if (!isa<SCEVSignExtendExpr>(SExt))
1859 return SExt;
1860
Dan Gohman51ad99d2010-01-21 02:09:26 +00001861 // Force the cast to be folded into the operands of an addrec.
1862 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1863 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001864 for (const SCEV *Op : AR->operands())
1865 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001866 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001867 }
1868
Dan Gohman8db2edc2009-06-13 15:56:47 +00001869 // If the expression is obviously signed, use the sext cast value.
1870 if (isa<SCEVSMaxExpr>(Op))
1871 return SExt;
1872
1873 // Absent any other information, use the zext cast value.
1874 return ZExt;
1875}
1876
Sanjoy Dasf8570812016-05-29 00:38:22 +00001877/// Process the given Ops list, which is a list of operands to be added under
1878/// the given scale, update the given map. This is a helper function for
1879/// getAddRecExpr. As an example of what it does, given a sequence of operands
1880/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001881///
Tobias Grosserba49e422014-03-05 10:37:17 +00001882/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001883///
1884/// where A and B are constants, update the map with these values:
1885///
1886/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1887///
1888/// and add 13 + A*B*29 to AccumulatedConstant.
1889/// This will allow getAddRecExpr to produce this:
1890///
1891/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1892///
1893/// This form often exposes folding opportunities that are hidden in
1894/// the original operand list.
1895///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001896/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001897/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1898/// the common case where no interesting opportunities are present, and
1899/// is also used as a check to avoid infinite recursion.
1900///
1901static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001902CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001903 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001904 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001905 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001906 const APInt &Scale,
1907 ScalarEvolution &SE) {
1908 bool Interesting = false;
1909
Dan Gohman45073042010-06-18 19:12:32 +00001910 // Iterate over the add operands. They are sorted, with constants first.
1911 unsigned i = 0;
1912 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1913 ++i;
1914 // Pull a buried constant out to the outside.
1915 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1916 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001917 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001918 }
1919
1920 // Next comes everything else. We're especially interested in multiplies
1921 // here, but they're in the middle, so just visit the rest with one loop.
1922 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001923 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1924 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1925 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001926 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001927 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1928 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001929 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001930 Interesting |=
1931 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001932 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001933 NewScale, SE);
1934 } else {
1935 // A multiplication of a constant with some other value. Update
1936 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001937 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1938 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001939 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001940 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001941 NewOps.push_back(Pair.first->first);
1942 } else {
1943 Pair.first->second += NewScale;
1944 // The map already had an entry for this value, which may indicate
1945 // a folding opportunity.
1946 Interesting = true;
1947 }
1948 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001949 } else {
1950 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001951 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001952 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001953 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001954 NewOps.push_back(Pair.first->first);
1955 } else {
1956 Pair.first->second += Scale;
1957 // The map already had an entry for this value, which may indicate
1958 // a folding opportunity.
1959 Interesting = true;
1960 }
1961 }
1962 }
1963
1964 return Interesting;
1965}
1966
Sanjoy Das81401d42015-01-10 23:41:24 +00001967// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1968// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1969// can't-overflow flags for the operation if possible.
1970static SCEV::NoWrapFlags
1971StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1972 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001973 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001974 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001975 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001976
1977 bool CanAnalyze =
1978 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1979 (void)CanAnalyze;
1980 assert(CanAnalyze && "don't call from other places!");
1981
1982 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1983 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001984 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001985
1986 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001987 auto IsKnownNonNegative = [&](const SCEV *S) {
1988 return SE->isKnownNonNegative(S);
1989 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001990
Sanjoy Das3b827c72015-11-29 23:40:53 +00001991 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001992 Flags =
1993 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001994
Sanjoy Das8f274152015-10-22 19:57:19 +00001995 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1996
1997 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1998 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1999
2000 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2001 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2002
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002003 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002004 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002005 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2006 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002007 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2008 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2009 }
2010 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002011 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2012 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002013 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2014 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2015 }
2016 }
2017
2018 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002019}
2020
Sanjoy Dasf8570812016-05-29 00:38:22 +00002021/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002022const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002023 SCEV::NoWrapFlags Flags) {
2024 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2025 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002026 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002027 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002028#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002029 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002030 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002031 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002032 "SCEVAddExpr operand types don't match!");
2033#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002034
2035 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002036 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002037
Sanjoy Das64895612015-10-09 02:44:45 +00002038 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2039
Chris Lattnerd934c702004-04-02 20:23:17 +00002040 // If there are any constants, fold them together.
2041 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002042 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002043 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002044 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002045 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002046 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002047 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002048 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002049 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002050 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002051 }
2052
2053 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002054 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002055 Ops.erase(Ops.begin());
2056 --Idx;
2057 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002058
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002059 if (Ops.size() == 1) return Ops[0];
2060 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002061
Dan Gohman15871f22010-08-27 21:39:59 +00002062 // Okay, check to see if the same value occurs in the operand list more than
2063 // once. If so, merge them together into an multiply expression. Since we
2064 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002065 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002066 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002067 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002068 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002069 // Scan ahead to count how many equal operands there are.
2070 unsigned Count = 2;
2071 while (i+Count != e && Ops[i+Count] == Ops[i])
2072 ++Count;
2073 // Merge the values into a multiply.
2074 const SCEV *Scale = getConstant(Ty, Count);
2075 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2076 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002077 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002078 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002079 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002080 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002081 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002082 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002083 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002084 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002085
Dan Gohman2e55cc52009-05-08 21:03:19 +00002086 // Check for truncates. If all the operands are truncated from the same
2087 // type, see if factoring out the truncate would permit the result to be
2088 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2089 // if the contents of the resulting outer trunc fold to something simple.
2090 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2091 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002092 Type *DstType = Trunc->getType();
2093 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002094 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002095 bool Ok = true;
2096 // Check all the operands to see if they can be represented in the
2097 // source type of the truncate.
2098 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2099 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2100 if (T->getOperand()->getType() != SrcType) {
2101 Ok = false;
2102 break;
2103 }
2104 LargeOps.push_back(T->getOperand());
2105 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002106 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002107 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002108 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002109 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2110 if (const SCEVTruncateExpr *T =
2111 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2112 if (T->getOperand()->getType() != SrcType) {
2113 Ok = false;
2114 break;
2115 }
2116 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002117 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002118 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002119 } else {
2120 Ok = false;
2121 break;
2122 }
2123 }
2124 if (Ok)
2125 LargeOps.push_back(getMulExpr(LargeMulOps));
2126 } else {
2127 Ok = false;
2128 break;
2129 }
2130 }
2131 if (Ok) {
2132 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002133 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002134 // If it folds to something simple, use it. Otherwise, don't.
2135 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2136 return getTruncateExpr(Fold, DstType);
2137 }
2138 }
2139
2140 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002141 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2142 ++Idx;
2143
2144 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002145 if (Idx < Ops.size()) {
2146 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002147 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002148 // If we have an add, expand the add operands onto the end of the operands
2149 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002150 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002151 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002152 DeletedAdd = true;
2153 }
2154
2155 // If we deleted at least one add, we added operands to the end of the list,
2156 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002157 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002158 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002159 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002160 }
2161
2162 // Skip over the add expression until we get to a multiply.
2163 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2164 ++Idx;
2165
Dan Gohman038d02e2009-06-14 22:58:51 +00002166 // Check to see if there are any folding opportunities present with
2167 // operands multiplied by constant values.
2168 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2169 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002170 DenseMap<const SCEV *, APInt> M;
2171 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002172 APInt AccumulatedConstant(BitWidth, 0);
2173 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002174 Ops.data(), Ops.size(),
2175 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002176 struct APIntCompare {
2177 bool operator()(const APInt &LHS, const APInt &RHS) const {
2178 return LHS.ult(RHS);
2179 }
2180 };
2181
Dan Gohman038d02e2009-06-14 22:58:51 +00002182 // Some interesting folding opportunity is present, so its worthwhile to
2183 // re-generate the operands list. Group the operands by constant scale,
2184 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002185 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002186 for (const SCEV *NewOp : NewOps)
2187 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002188 // Re-generate the operands list.
2189 Ops.clear();
2190 if (AccumulatedConstant != 0)
2191 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002192 for (auto &MulOp : MulOpLists)
2193 if (MulOp.first != 0)
2194 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2195 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002196 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002197 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002198 if (Ops.size() == 1)
2199 return Ops[0];
2200 return getAddExpr(Ops);
2201 }
2202 }
2203
Chris Lattnerd934c702004-04-02 20:23:17 +00002204 // If we are adding something to a multiply expression, make sure the
2205 // something is not already an operand of the multiply. If so, merge it into
2206 // the multiply.
2207 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002208 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002209 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002210 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002211 if (isa<SCEVConstant>(MulOpSCEV))
2212 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002213 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002214 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002215 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002216 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002217 if (Mul->getNumOperands() != 2) {
2218 // If the multiply has more than two operands, we must get the
2219 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002220 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2221 Mul->op_begin()+MulOp);
2222 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002223 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002224 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002225 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002226 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002227 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002228 if (Ops.size() == 2) return OuterMul;
2229 if (AddOp < Idx) {
2230 Ops.erase(Ops.begin()+AddOp);
2231 Ops.erase(Ops.begin()+Idx-1);
2232 } else {
2233 Ops.erase(Ops.begin()+Idx);
2234 Ops.erase(Ops.begin()+AddOp-1);
2235 }
2236 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002237 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002238 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002239
Chris Lattnerd934c702004-04-02 20:23:17 +00002240 // Check this multiply against other multiplies being added together.
2241 for (unsigned OtherMulIdx = Idx+1;
2242 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2243 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002244 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002245 // If MulOp occurs in OtherMul, we can fold the two multiplies
2246 // together.
2247 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2248 OMulOp != e; ++OMulOp)
2249 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2250 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002251 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002252 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002253 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002254 Mul->op_begin()+MulOp);
2255 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002256 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002257 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002258 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002259 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002260 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002261 OtherMul->op_begin()+OMulOp);
2262 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002263 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002264 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002265 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2266 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002267 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002268 Ops.erase(Ops.begin()+Idx);
2269 Ops.erase(Ops.begin()+OtherMulIdx-1);
2270 Ops.push_back(OuterMul);
2271 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002272 }
2273 }
2274 }
2275 }
2276
2277 // If there are any add recurrences in the operands list, see if any other
2278 // added values are loop invariant. If so, we can fold them into the
2279 // recurrence.
2280 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2281 ++Idx;
2282
2283 // Scan over all recurrences, trying to fold loop invariants into them.
2284 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2285 // Scan all of the other operands to this add and add them to the vector if
2286 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002287 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002288 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002289 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002290 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002291 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002292 LIOps.push_back(Ops[i]);
2293 Ops.erase(Ops.begin()+i);
2294 --i; --e;
2295 }
2296
2297 // If we found some loop invariants, fold them into the recurrence.
2298 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002299 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002300 LIOps.push_back(AddRec->getStart());
2301
Dan Gohmanaf752342009-07-07 17:06:11 +00002302 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002303 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002304 // This follows from the fact that the no-wrap flags on the outer add
2305 // expression are applicable on the 0th iteration, when the add recurrence
2306 // will be equal to its start value.
2307 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002308
Dan Gohman16206132010-06-30 07:16:37 +00002309 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002310 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002311 // Always propagate NW.
2312 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002313 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002314
Chris Lattnerd934c702004-04-02 20:23:17 +00002315 // If all of the other operands were loop invariant, we are done.
2316 if (Ops.size() == 1) return NewRec;
2317
Nick Lewyckydb66b822011-09-06 05:08:09 +00002318 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002319 for (unsigned i = 0;; ++i)
2320 if (Ops[i] == AddRec) {
2321 Ops[i] = NewRec;
2322 break;
2323 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002324 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002325 }
2326
2327 // Okay, if there weren't any loop invariants to be folded, check to see if
2328 // there are multiple AddRec's with the same loop induction variable being
2329 // added together. If so, we can fold them.
2330 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002331 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2332 ++OtherIdx)
2333 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2334 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2335 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2336 AddRec->op_end());
2337 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2338 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002339 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002340 if (OtherAddRec->getLoop() == AddRecLoop) {
2341 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2342 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002343 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002344 AddRecOps.append(OtherAddRec->op_begin()+i,
2345 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002346 break;
2347 }
Dan Gohman028c1812010-08-29 14:53:34 +00002348 AddRecOps[i] = getAddExpr(AddRecOps[i],
2349 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002350 }
2351 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002352 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002353 // Step size has changed, so we cannot guarantee no self-wraparound.
2354 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002355 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002356 }
2357
2358 // Otherwise couldn't fold anything into this recurrence. Move onto the
2359 // next one.
2360 }
2361
2362 // Okay, it looks like we really DO need an add expr. Check to see if we
2363 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002364 FoldingSetNodeID ID;
2365 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002366 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2367 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002368 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002369 SCEVAddExpr *S =
2370 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2371 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002372 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2373 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002374 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2375 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002376 UniqueSCEVs.InsertNode(S, IP);
2377 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002378 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002379 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002380}
2381
Nick Lewycky287682e2011-10-04 06:51:26 +00002382static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2383 uint64_t k = i*j;
2384 if (j > 1 && k / j != i) Overflow = true;
2385 return k;
2386}
2387
2388/// Compute the result of "n choose k", the binomial coefficient. If an
2389/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002390/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002391static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2392 // We use the multiplicative formula:
2393 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2394 // At each iteration, we take the n-th term of the numeral and divide by the
2395 // (k-n)th term of the denominator. This division will always produce an
2396 // integral result, and helps reduce the chance of overflow in the
2397 // intermediate computations. However, we can still overflow even when the
2398 // final result would fit.
2399
2400 if (n == 0 || n == k) return 1;
2401 if (k > n) return 0;
2402
2403 if (k > n/2)
2404 k = n-k;
2405
2406 uint64_t r = 1;
2407 for (uint64_t i = 1; i <= k; ++i) {
2408 r = umul_ov(r, n-(i-1), Overflow);
2409 r /= i;
2410 }
2411 return r;
2412}
2413
Nick Lewycky05044c22014-12-06 00:45:50 +00002414/// Determine if any of the operands in this SCEV are a constant or if
2415/// any of the add or multiply expressions in this SCEV contain a constant.
2416static bool containsConstantSomewhere(const SCEV *StartExpr) {
2417 SmallVector<const SCEV *, 4> Ops;
2418 Ops.push_back(StartExpr);
2419 while (!Ops.empty()) {
2420 const SCEV *CurrentExpr = Ops.pop_back_val();
2421 if (isa<SCEVConstant>(*CurrentExpr))
2422 return true;
2423
2424 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2425 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002426 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002427 }
2428 }
2429 return false;
2430}
2431
Sanjoy Dasf8570812016-05-29 00:38:22 +00002432/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002433const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002434 SCEV::NoWrapFlags Flags) {
2435 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2436 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002437 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002438 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002439#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002440 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002441 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002442 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002443 "SCEVMulExpr operand types don't match!");
2444#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002445
2446 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002447 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002448
Sanjoy Das64895612015-10-09 02:44:45 +00002449 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2450
Chris Lattnerd934c702004-04-02 20:23:17 +00002451 // If there are any constants, fold them together.
2452 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002453 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002454
2455 // C1*(C2+V) -> C1*C2 + C1*V
2456 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002457 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2458 // If any of Add's ops are Adds or Muls with a constant,
2459 // apply this transformation as well.
2460 if (Add->getNumOperands() == 2)
2461 if (containsConstantSomewhere(Add))
2462 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2463 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002464
Chris Lattnerd934c702004-04-02 20:23:17 +00002465 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002466 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002467 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002468 ConstantInt *Fold =
2469 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002470 Ops[0] = getConstant(Fold);
2471 Ops.erase(Ops.begin()+1); // Erase the folded element
2472 if (Ops.size() == 1) return Ops[0];
2473 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002474 }
2475
2476 // If we are left with a constant one being multiplied, strip it off.
2477 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2478 Ops.erase(Ops.begin());
2479 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002480 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002481 // If we have a multiply of zero, it will always be zero.
2482 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002483 } else if (Ops[0]->isAllOnesValue()) {
2484 // If we have a mul by -1 of an add, try distributing the -1 among the
2485 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002486 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002487 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2488 SmallVector<const SCEV *, 4> NewOps;
2489 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002490 for (const SCEV *AddOp : Add->operands()) {
2491 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002492 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2493 NewOps.push_back(Mul);
2494 }
2495 if (AnyFolded)
2496 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002497 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002498 // Negation preserves a recurrence's no self-wrap property.
2499 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002500 for (const SCEV *AddRecOp : AddRec->operands())
2501 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2502
Andrew Tricke92dcce2011-03-14 17:38:54 +00002503 return getAddRecExpr(Operands, AddRec->getLoop(),
2504 AddRec->getNoWrapFlags(SCEV::FlagNW));
2505 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002506 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002507 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002508
2509 if (Ops.size() == 1)
2510 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002511 }
2512
2513 // Skip over the add expression until we get to a multiply.
2514 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2515 ++Idx;
2516
Chris Lattnerd934c702004-04-02 20:23:17 +00002517 // If there are mul operands inline them all into this expression.
2518 if (Idx < Ops.size()) {
2519 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002520 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002521 // If we have an mul, expand the mul operands onto the end of the operands
2522 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002523 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002524 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002525 DeletedMul = true;
2526 }
2527
2528 // If we deleted at least one mul, we added operands to the end of the list,
2529 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002530 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002531 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002532 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002533 }
2534
2535 // If there are any add recurrences in the operands list, see if any other
2536 // added values are loop invariant. If so, we can fold them into the
2537 // recurrence.
2538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2539 ++Idx;
2540
2541 // Scan over all recurrences, trying to fold loop invariants into them.
2542 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2543 // Scan all of the other operands to this mul and add them to the vector if
2544 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002545 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002546 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002547 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002548 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002549 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002550 LIOps.push_back(Ops[i]);
2551 Ops.erase(Ops.begin()+i);
2552 --i; --e;
2553 }
2554
2555 // If we found some loop invariants, fold them into the recurrence.
2556 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002557 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002558 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002559 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002560 const SCEV *Scale = getMulExpr(LIOps);
2561 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2562 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002563
Dan Gohman16206132010-06-30 07:16:37 +00002564 // Build the new addrec. Propagate the NUW and NSW flags if both the
2565 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002566 //
2567 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002568 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002569 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2570 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002571
2572 // If all of the other operands were loop invariant, we are done.
2573 if (Ops.size() == 1) return NewRec;
2574
Nick Lewyckydb66b822011-09-06 05:08:09 +00002575 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002576 for (unsigned i = 0;; ++i)
2577 if (Ops[i] == AddRec) {
2578 Ops[i] = NewRec;
2579 break;
2580 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002581 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002582 }
2583
2584 // Okay, if there weren't any loop invariants to be folded, check to see if
2585 // there are multiple AddRec's with the same loop induction variable being
2586 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002587
2588 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2589 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2590 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2591 // ]]],+,...up to x=2n}.
2592 // Note that the arguments to choose() are always integers with values
2593 // known at compile time, never SCEV objects.
2594 //
2595 // The implementation avoids pointless extra computations when the two
2596 // addrec's are of different length (mathematically, it's equivalent to
2597 // an infinite stream of zeros on the right).
2598 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002599 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002600 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002601 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002602 const SCEVAddRecExpr *OtherAddRec =
2603 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2604 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002605 continue;
2606
Nick Lewycky97756402014-09-01 05:17:15 +00002607 bool Overflow = false;
2608 Type *Ty = AddRec->getType();
2609 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2610 SmallVector<const SCEV*, 7> AddRecOps;
2611 for (int x = 0, xe = AddRec->getNumOperands() +
2612 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002613 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002614 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2615 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2616 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2617 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2618 z < ze && !Overflow; ++z) {
2619 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2620 uint64_t Coeff;
2621 if (LargerThan64Bits)
2622 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2623 else
2624 Coeff = Coeff1*Coeff2;
2625 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2626 const SCEV *Term1 = AddRec->getOperand(y-z);
2627 const SCEV *Term2 = OtherAddRec->getOperand(z);
2628 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002629 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002630 }
Nick Lewycky97756402014-09-01 05:17:15 +00002631 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002632 }
Nick Lewycky97756402014-09-01 05:17:15 +00002633 if (!Overflow) {
2634 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2635 SCEV::FlagAnyWrap);
2636 if (Ops.size() == 2) return NewAddRec;
2637 Ops[Idx] = NewAddRec;
2638 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2639 OpsModified = true;
2640 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2641 if (!AddRec)
2642 break;
2643 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002644 }
Nick Lewycky97756402014-09-01 05:17:15 +00002645 if (OpsModified)
2646 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002647
2648 // Otherwise couldn't fold anything into this recurrence. Move onto the
2649 // next one.
2650 }
2651
2652 // Okay, it looks like we really DO need an mul expr. Check to see if we
2653 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002654 FoldingSetNodeID ID;
2655 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002656 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2657 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002658 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002659 SCEVMulExpr *S =
2660 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2661 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002662 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2663 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002664 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2665 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002666 UniqueSCEVs.InsertNode(S, IP);
2667 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002668 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002669 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002670}
2671
Sanjoy Dasf8570812016-05-29 00:38:22 +00002672/// Get a canonical unsigned division expression, or something simpler if
2673/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002674const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2675 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002676 assert(getEffectiveSCEVType(LHS->getType()) ==
2677 getEffectiveSCEVType(RHS->getType()) &&
2678 "SCEVUDivExpr operand types don't match!");
2679
Dan Gohmana30370b2009-05-04 22:02:23 +00002680 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002681 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002682 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002683 // If the denominator is zero, the result of the udiv is undefined. Don't
2684 // try to analyze it, because the resolution chosen here may differ from
2685 // the resolution chosen in other parts of the compiler.
2686 if (!RHSC->getValue()->isZero()) {
2687 // Determine if the division can be folded into the operands of
2688 // its operands.
2689 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002690 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002691 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002692 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002693 // For non-power-of-two values, effectively round the value up to the
2694 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002695 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002696 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002697 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002698 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002699 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2700 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002701 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2702 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002703 const APInt &StepInt = Step->getAPInt();
2704 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002705 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002706 getZeroExtendExpr(AR, ExtTy) ==
2707 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2708 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002709 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002710 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002711 for (const SCEV *Op : AR->operands())
2712 Operands.push_back(getUDivExpr(Op, RHS));
2713 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002714 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002715 /// Get a canonical UDivExpr for a recurrence.
2716 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2717 // We can currently only fold X%N if X is constant.
2718 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2719 if (StartC && !DivInt.urem(StepInt) &&
2720 getZeroExtendExpr(AR, ExtTy) ==
2721 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2722 getZeroExtendExpr(Step, ExtTy),
2723 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002724 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002725 const APInt &StartRem = StartInt.urem(StepInt);
2726 if (StartRem != 0)
2727 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2728 AR->getLoop(), SCEV::FlagNW);
2729 }
2730 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002731 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2732 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2733 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002734 for (const SCEV *Op : M->operands())
2735 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002736 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2737 // Find an operand that's safely divisible.
2738 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2739 const SCEV *Op = M->getOperand(i);
2740 const SCEV *Div = getUDivExpr(Op, RHSC);
2741 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2742 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2743 M->op_end());
2744 Operands[i] = Div;
2745 return getMulExpr(Operands);
2746 }
2747 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002748 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002749 // (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 +00002750 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002751 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002752 for (const SCEV *Op : A->operands())
2753 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002754 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2755 Operands.clear();
2756 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2757 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2758 if (isa<SCEVUDivExpr>(Op) ||
2759 getMulExpr(Op, RHS) != A->getOperand(i))
2760 break;
2761 Operands.push_back(Op);
2762 }
2763 if (Operands.size() == A->getNumOperands())
2764 return getAddExpr(Operands);
2765 }
2766 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002767
Dan Gohmanacd700a2010-04-22 01:35:11 +00002768 // Fold if both operands are constant.
2769 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2770 Constant *LHSCV = LHSC->getValue();
2771 Constant *RHSCV = RHSC->getValue();
2772 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2773 RHSCV)));
2774 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002775 }
2776 }
2777
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002778 FoldingSetNodeID ID;
2779 ID.AddInteger(scUDivExpr);
2780 ID.AddPointer(LHS);
2781 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002782 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002784 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2785 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002786 UniqueSCEVs.InsertNode(S, IP);
2787 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002788}
2789
Nick Lewycky31eaca52014-01-27 10:04:03 +00002790static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002791 APInt A = C1->getAPInt().abs();
2792 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002793 uint32_t ABW = A.getBitWidth();
2794 uint32_t BBW = B.getBitWidth();
2795
2796 if (ABW > BBW)
2797 B = B.zext(ABW);
2798 else if (ABW < BBW)
2799 A = A.zext(BBW);
2800
2801 return APIntOps::GreatestCommonDivisor(A, B);
2802}
2803
Sanjoy Dasf8570812016-05-29 00:38:22 +00002804/// Get a canonical unsigned division expression, or something simpler if
2805/// possible. There is no representation for an exact udiv in SCEV IR, but we
2806/// can attempt to remove factors from the LHS and RHS. We can't do this when
2807/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002808const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2809 const SCEV *RHS) {
2810 // TODO: we could try to find factors in all sorts of things, but for now we
2811 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2812 // end of this file for inspiration.
2813
2814 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2815 if (!Mul)
2816 return getUDivExpr(LHS, RHS);
2817
2818 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2819 // If the mulexpr multiplies by a constant, then that constant must be the
2820 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002821 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002822 if (LHSCst == RHSCst) {
2823 SmallVector<const SCEV *, 2> Operands;
2824 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2825 return getMulExpr(Operands);
2826 }
2827
2828 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2829 // that there's a factor provided by one of the other terms. We need to
2830 // check.
2831 APInt Factor = gcd(LHSCst, RHSCst);
2832 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002833 LHSCst =
2834 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2835 RHSCst =
2836 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002837 SmallVector<const SCEV *, 2> Operands;
2838 Operands.push_back(LHSCst);
2839 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2840 LHS = getMulExpr(Operands);
2841 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002842 Mul = dyn_cast<SCEVMulExpr>(LHS);
2843 if (!Mul)
2844 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002845 }
2846 }
2847 }
2848
2849 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2850 if (Mul->getOperand(i) == RHS) {
2851 SmallVector<const SCEV *, 2> Operands;
2852 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2853 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2854 return getMulExpr(Operands);
2855 }
2856 }
2857
2858 return getUDivExpr(LHS, RHS);
2859}
Chris Lattnerd934c702004-04-02 20:23:17 +00002860
Sanjoy Dasf8570812016-05-29 00:38:22 +00002861/// Get an add recurrence expression for the specified loop. Simplify the
2862/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002863const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2864 const Loop *L,
2865 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002866 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002867 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002868 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002869 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002870 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002871 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002872 }
2873
2874 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002875 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002876}
2877
Sanjoy Dasf8570812016-05-29 00:38:22 +00002878/// Get an add recurrence expression for the specified loop. Simplify the
2879/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002880const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002881ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002882 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002883 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002884#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002885 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002886 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002887 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002888 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002889 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002890 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002891 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002892#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002893
Dan Gohmanbe928e32008-06-18 16:23:07 +00002894 if (Operands.back()->isZero()) {
2895 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002896 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002897 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002898
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002899 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2900 // use that information to infer NUW and NSW flags. However, computing a
2901 // BE count requires calling getAddRecExpr, so we may not yet have a
2902 // meaningful BE count at this point (and if we don't, we'd be stuck
2903 // with a SCEVCouldNotCompute as the cached BE count).
2904
Sanjoy Das81401d42015-01-10 23:41:24 +00002905 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002906
Dan Gohman223a5d22008-08-08 18:33:12 +00002907 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002908 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002909 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002910 if (L->contains(NestedLoop)
2911 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2912 : (!NestedLoop->contains(L) &&
2913 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002914 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002915 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002916 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002917 // AddRecs require their operands be loop-invariant with respect to their
2918 // loops. Don't perform this transformation if it would break this
2919 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002920 bool AllInvariant = all_of(
2921 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002922
Dan Gohmancc030b72009-06-26 22:36:20 +00002923 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002924 // Create a recurrence for the outer loop with the same step size.
2925 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002926 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2927 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002928 SCEV::NoWrapFlags OuterFlags =
2929 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002930
2931 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002932 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2933 return isLoopInvariant(Op, NestedLoop);
2934 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002935
Andrew Trick8b55b732011-03-14 16:50:06 +00002936 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002937 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002938 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002939 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2940 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002941 SCEV::NoWrapFlags InnerFlags =
2942 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002943 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2944 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002945 }
2946 // Reset Operands to its original state.
2947 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002948 }
2949 }
2950
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002951 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2952 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002953 FoldingSetNodeID ID;
2954 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002955 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2956 ID.AddPointer(Operands[i]);
2957 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002958 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002959 SCEVAddRecExpr *S =
2960 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2961 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002962 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2963 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002964 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2965 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002966 UniqueSCEVs.InsertNode(S, IP);
2967 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002968 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002969 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002970}
2971
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002972const SCEV *
2973ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2974 const SmallVectorImpl<const SCEV *> &IndexExprs,
2975 bool InBounds) {
2976 // getSCEV(Base)->getType() has the same address space as Base->getType()
2977 // because SCEV::getType() preserves the address space.
2978 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2979 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2980 // instruction to its SCEV, because the Instruction may be guarded by control
2981 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002982 // context. This can be fixed similarly to how these flags are handled for
2983 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002984 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2985
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002986 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002987 // The address space is unimportant. The first thing we do on CurTy is getting
2988 // its element type.
2989 Type *CurTy = PointerType::getUnqual(PointeeType);
2990 for (const SCEV *IndexExpr : IndexExprs) {
2991 // Compute the (potentially symbolic) offset in bytes for this index.
2992 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2993 // For a struct, add the member offset.
2994 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2995 unsigned FieldNo = Index->getZExtValue();
2996 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2997
2998 // Add the field offset to the running total offset.
2999 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3000
3001 // Update CurTy to the type of the field at Index.
3002 CurTy = STy->getTypeAtIndex(Index);
3003 } else {
3004 // Update CurTy to its element type.
3005 CurTy = cast<SequentialType>(CurTy)->getElementType();
3006 // For an array, add the element offset, explicitly scaled.
3007 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3008 // Getelementptr indices are signed.
3009 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3010
3011 // Multiply the index by the element size to compute the element offset.
3012 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3013
3014 // Add the element offset to the running total offset.
3015 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3016 }
3017 }
3018
3019 // Add the total offset from all the GEP indices to the base.
3020 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3021}
3022
Dan Gohmanabd17092009-06-24 14:49:00 +00003023const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3024 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003025 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003026 return getSMaxExpr(Ops);
3027}
3028
Dan Gohmanaf752342009-07-07 17:06:11 +00003029const SCEV *
3030ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003031 assert(!Ops.empty() && "Cannot get empty smax!");
3032 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003033#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003034 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003035 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003036 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003037 "SCEVSMaxExpr operand types don't match!");
3038#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003039
3040 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003041 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003042
3043 // If there are any constants, fold them together.
3044 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003045 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003046 ++Idx;
3047 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003048 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003049 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003050 ConstantInt *Fold = ConstantInt::get(
3051 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003052 Ops[0] = getConstant(Fold);
3053 Ops.erase(Ops.begin()+1); // Erase the folded element
3054 if (Ops.size() == 1) return Ops[0];
3055 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003056 }
3057
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003058 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003059 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3060 Ops.erase(Ops.begin());
3061 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003062 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3063 // If we have an smax with a constant maximum-int, it will always be
3064 // maximum-int.
3065 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003066 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003067
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003068 if (Ops.size() == 1) return Ops[0];
3069 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003070
3071 // Find the first SMax
3072 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3073 ++Idx;
3074
3075 // Check to see if one of the operands is an SMax. If so, expand its operands
3076 // onto our operand list, and recurse to simplify.
3077 if (Idx < Ops.size()) {
3078 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003079 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003080 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003081 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003082 DeletedSMax = true;
3083 }
3084
3085 if (DeletedSMax)
3086 return getSMaxExpr(Ops);
3087 }
3088
3089 // Okay, check to see if the same value occurs in the operand list twice. If
3090 // so, delete one. Since we sorted the list, these values are required to
3091 // be adjacent.
3092 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003093 // X smax Y smax Y --> X smax Y
3094 // X smax Y --> X, if X is always greater than Y
3095 if (Ops[i] == Ops[i+1] ||
3096 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3097 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3098 --i; --e;
3099 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003100 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3101 --i; --e;
3102 }
3103
3104 if (Ops.size() == 1) return Ops[0];
3105
3106 assert(!Ops.empty() && "Reduced smax down to nothing!");
3107
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003108 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003109 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003110 FoldingSetNodeID ID;
3111 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003112 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3113 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003114 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003115 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003116 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3117 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003118 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3119 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003120 UniqueSCEVs.InsertNode(S, IP);
3121 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003122}
3123
Dan Gohmanabd17092009-06-24 14:49:00 +00003124const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3125 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003126 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003127 return getUMaxExpr(Ops);
3128}
3129
Dan Gohmanaf752342009-07-07 17:06:11 +00003130const SCEV *
3131ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003132 assert(!Ops.empty() && "Cannot get empty umax!");
3133 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003134#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003135 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003136 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003137 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003138 "SCEVUMaxExpr operand types don't match!");
3139#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003140
3141 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003142 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003143
3144 // If there are any constants, fold them together.
3145 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003146 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003147 ++Idx;
3148 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003149 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003150 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003151 ConstantInt *Fold = ConstantInt::get(
3152 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003153 Ops[0] = getConstant(Fold);
3154 Ops.erase(Ops.begin()+1); // Erase the folded element
3155 if (Ops.size() == 1) return Ops[0];
3156 LHSC = cast<SCEVConstant>(Ops[0]);
3157 }
3158
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003159 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003160 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3161 Ops.erase(Ops.begin());
3162 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003163 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3164 // If we have an umax with a constant maximum-int, it will always be
3165 // maximum-int.
3166 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003167 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003168
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003169 if (Ops.size() == 1) return Ops[0];
3170 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003171
3172 // Find the first UMax
3173 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3174 ++Idx;
3175
3176 // Check to see if one of the operands is a UMax. If so, expand its operands
3177 // onto our operand list, and recurse to simplify.
3178 if (Idx < Ops.size()) {
3179 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003180 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003181 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003182 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003183 DeletedUMax = true;
3184 }
3185
3186 if (DeletedUMax)
3187 return getUMaxExpr(Ops);
3188 }
3189
3190 // Okay, check to see if the same value occurs in the operand list twice. If
3191 // so, delete one. Since we sorted the list, these values are required to
3192 // be adjacent.
3193 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003194 // X umax Y umax Y --> X umax Y
3195 // X umax Y --> X, if X is always greater than Y
3196 if (Ops[i] == Ops[i+1] ||
3197 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3198 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3199 --i; --e;
3200 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003201 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3202 --i; --e;
3203 }
3204
3205 if (Ops.size() == 1) return Ops[0];
3206
3207 assert(!Ops.empty() && "Reduced umax down to nothing!");
3208
3209 // Okay, it looks like we really DO need a umax expr. Check to see if we
3210 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003211 FoldingSetNodeID ID;
3212 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003213 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3214 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003215 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003216 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003217 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3218 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003219 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3220 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003221 UniqueSCEVs.InsertNode(S, IP);
3222 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003223}
3224
Dan Gohmanabd17092009-06-24 14:49:00 +00003225const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3226 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003227 // ~smax(~x, ~y) == smin(x, y).
3228 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3229}
3230
Dan Gohmanabd17092009-06-24 14:49:00 +00003231const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3232 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003233 // ~umax(~x, ~y) == umin(x, y)
3234 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3235}
3236
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003237const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003238 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003239 // constant expression and then folding it back into a ConstantInt.
3240 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003241 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003242}
3243
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003244const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3245 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003246 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003247 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003248 // constant expression and then folding it back into a ConstantInt.
3249 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003250 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003251 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003252}
3253
Dan Gohmanaf752342009-07-07 17:06:11 +00003254const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003255 // Don't attempt to do anything other than create a SCEVUnknown object
3256 // here. createSCEV only calls getUnknown after checking for all other
3257 // interesting possibilities, and any other code that calls getUnknown
3258 // is doing so in order to hide a value from SCEV canonicalization.
3259
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003260 FoldingSetNodeID ID;
3261 ID.AddInteger(scUnknown);
3262 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003263 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003264 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3265 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3266 "Stale SCEVUnknown in uniquing map!");
3267 return S;
3268 }
3269 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3270 FirstUnknown);
3271 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003272 UniqueSCEVs.InsertNode(S, IP);
3273 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003274}
3275
Chris Lattnerd934c702004-04-02 20:23:17 +00003276//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003277// Basic SCEV Analysis and PHI Idiom Recognition Code
3278//
3279
Sanjoy Dasf8570812016-05-29 00:38:22 +00003280/// Test if values of the given type are analyzable within the SCEV
3281/// framework. This primarily includes integer types, and it can optionally
3282/// include pointer types if the ScalarEvolution class has access to
3283/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003284bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003285 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003286 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003287}
3288
Sanjoy Dasf8570812016-05-29 00:38:22 +00003289/// Return the size in bits of the specified type, for which isSCEVable must
3290/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003291uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003292 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003293 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003294}
3295
Sanjoy Dasf8570812016-05-29 00:38:22 +00003296/// Return a type with the same bitwidth as the given type and which represents
3297/// how SCEV will treat the given type, for which isSCEVable must return
3298/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003299Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003300 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3301
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003302 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003303 return Ty;
3304
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003305 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003306 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003307 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003308}
Chris Lattnerd934c702004-04-02 20:23:17 +00003309
Dan Gohmanaf752342009-07-07 17:06:11 +00003310const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003311 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003312}
3313
Sanjoy Das7d752672015-12-08 04:32:54 +00003314
3315bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003316 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3317 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3318 // is set iff if find such SCEVUnknown.
3319 //
3320 struct FindInvalidSCEVUnknown {
3321 bool FindOne;
3322 FindInvalidSCEVUnknown() { FindOne = false; }
3323 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003324 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003325 case scConstant:
3326 return false;
3327 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003328 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003329 FindOne = true;
3330 return false;
3331 default:
3332 return true;
3333 }
3334 }
3335 bool isDone() const { return FindOne; }
3336 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003337
Shuxin Yangefc4c012013-07-08 17:33:13 +00003338 FindInvalidSCEVUnknown F;
3339 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3340 ST.visitAll(S);
3341
3342 return !F.FindOne;
3343}
3344
Wei Mia49559b2016-02-04 01:27:38 +00003345namespace {
3346// Helper class working with SCEVTraversal to figure out if a SCEV contains
3347// a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set
3348// iff if such sub scAddRecExpr type SCEV is found.
3349struct FindAddRecurrence {
3350 bool FoundOne;
3351 FindAddRecurrence() : FoundOne(false) {}
3352
3353 bool follow(const SCEV *S) {
3354 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3355 case scAddRecExpr:
3356 FoundOne = true;
3357 case scConstant:
3358 case scUnknown:
3359 case scCouldNotCompute:
3360 return false;
3361 default:
3362 return true;
3363 }
3364 }
3365 bool isDone() const { return FoundOne; }
3366};
3367}
3368
3369bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3370 HasRecMapType::iterator I = HasRecMap.find_as(S);
3371 if (I != HasRecMap.end())
3372 return I->second;
3373
3374 FindAddRecurrence F;
3375 SCEVTraversal<FindAddRecurrence> ST(F);
3376 ST.visitAll(S);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003377 HasRecMap.insert({S, F.FoundOne});
Wei Mia49559b2016-02-04 01:27:38 +00003378 return F.FoundOne;
3379}
3380
Wei Mi785858c2016-08-09 20:37:50 +00003381/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3382/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3383/// offset I, then return {S', I}, else return {\p S, nullptr}.
3384static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3385 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3386 if (!Add)
3387 return {S, nullptr};
3388
3389 if (Add->getNumOperands() != 2)
3390 return {S, nullptr};
3391
3392 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3393 if (!ConstOp)
3394 return {S, nullptr};
3395
3396 return {Add->getOperand(1), ConstOp->getValue()};
3397}
3398
3399/// Return the ValueOffsetPair set for \p S. \p S can be represented
3400/// by the value and offset from any ValueOffsetPair in the set.
3401SetVector<ScalarEvolution::ValueOffsetPair> *
3402ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003403 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3404 if (SI == ExprValueMap.end())
3405 return nullptr;
3406#ifndef NDEBUG
3407 if (VerifySCEVMap) {
3408 // Check there is no dangling Value in the set returned.
3409 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003410 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003411 }
3412#endif
3413 return &SI->second;
3414}
3415
Wei Mi785858c2016-08-09 20:37:50 +00003416/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3417/// cannot be used separately. eraseValueFromMap should be used to remove
3418/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003419void ScalarEvolution::eraseValueFromMap(Value *V) {
3420 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3421 if (I != ValueExprMap.end()) {
3422 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003423 // Remove {V, 0} from the set of ExprValueMap[S]
3424 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3425 SV->remove({V, nullptr});
3426
3427 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3428 const SCEV *Stripped;
3429 ConstantInt *Offset;
3430 std::tie(Stripped, Offset) = splitAddExpr(S);
3431 if (Offset != nullptr) {
3432 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3433 SV->remove({V, Offset});
3434 }
Wei Mia49559b2016-02-04 01:27:38 +00003435 ValueExprMap.erase(V);
3436 }
3437}
3438
Sanjoy Dasf8570812016-05-29 00:38:22 +00003439/// Return an existing SCEV if it exists, otherwise analyze the expression and
3440/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003441const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003442 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003443
Jingyue Wu42f1d672015-07-28 18:22:40 +00003444 const SCEV *S = getExistingSCEV(V);
3445 if (S == nullptr) {
3446 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003447 // During PHI resolution, it is possible to create two SCEVs for the same
3448 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003449 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003450 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003451 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003452 if (Pair.second) {
3453 ExprValueMap[S].insert({V, nullptr});
3454
3455 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3456 // ExprValueMap.
3457 const SCEV *Stripped = S;
3458 ConstantInt *Offset = nullptr;
3459 std::tie(Stripped, Offset) = splitAddExpr(S);
3460 // If stripped is SCEVUnknown, don't bother to save
3461 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3462 // increase the complexity of the expansion code.
3463 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3464 // because it may generate add/sub instead of GEP in SCEV expansion.
3465 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3466 !isa<GetElementPtrInst>(V))
3467 ExprValueMap[Stripped].insert({V, Offset});
3468 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003469 }
3470 return S;
3471}
3472
3473const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3474 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3475
Shuxin Yangefc4c012013-07-08 17:33:13 +00003476 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3477 if (I != ValueExprMap.end()) {
3478 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003479 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003480 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003481 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003482 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003483 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003484 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003485}
3486
Sanjoy Dasf8570812016-05-29 00:38:22 +00003487/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003488///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003489const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3490 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003491 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003492 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003493 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003494
Chris Lattner229907c2011-07-18 04:54:35 +00003495 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003496 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003497 return getMulExpr(
3498 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003499}
3500
Sanjoy Dasf8570812016-05-29 00:38:22 +00003501/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003502const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003503 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003504 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003505 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003506
Chris Lattner229907c2011-07-18 04:54:35 +00003507 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003508 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003509 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003510 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003511 return getMinusSCEV(AllOnes, V);
3512}
3513
Chris Lattnerfc877522011-01-09 22:26:35 +00003514const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003515 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003516 // Fast path: X - X --> 0.
3517 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003518 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003519
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003520 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3521 // makes it so that we cannot make much use of NUW.
3522 auto AddFlags = SCEV::FlagAnyWrap;
3523 const bool RHSIsNotMinSigned =
3524 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3525 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3526 // Let M be the minimum representable signed value. Then (-1)*RHS
3527 // signed-wraps if and only if RHS is M. That can happen even for
3528 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3529 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3530 // (-1)*RHS, we need to prove that RHS != M.
3531 //
3532 // If LHS is non-negative and we know that LHS - RHS does not
3533 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3534 // either by proving that RHS > M or that LHS >= 0.
3535 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3536 AddFlags = SCEV::FlagNSW;
3537 }
3538 }
3539
3540 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3541 // RHS is NSW and LHS >= 0.
3542 //
3543 // The difficulty here is that the NSW flag may have been proven
3544 // relative to a loop that is to be found in a recurrence in LHS and
3545 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3546 // larger scope than intended.
3547 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3548
3549 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003550}
3551
Dan Gohmanaf752342009-07-07 17:06:11 +00003552const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003553ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3554 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3556 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003557 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003559 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003560 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003561 return getTruncateExpr(V, Ty);
3562 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003563}
3564
Dan Gohmanaf752342009-07-07 17:06:11 +00003565const SCEV *
3566ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003567 Type *Ty) {
3568 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003569 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3570 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003571 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003573 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003574 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003575 return getTruncateExpr(V, Ty);
3576 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003577}
3578
Dan Gohmanaf752342009-07-07 17:06:11 +00003579const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003580ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3581 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003582 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3583 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003584 "Cannot noop or zero extend with non-integer arguments!");
3585 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3586 "getNoopOrZeroExtend cannot truncate!");
3587 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3588 return V; // No conversion
3589 return getZeroExtendExpr(V, Ty);
3590}
3591
Dan Gohmanaf752342009-07-07 17:06:11 +00003592const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003593ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3594 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003595 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3596 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003597 "Cannot noop or sign extend with non-integer arguments!");
3598 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3599 "getNoopOrSignExtend cannot truncate!");
3600 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3601 return V; // No conversion
3602 return getSignExtendExpr(V, Ty);
3603}
3604
Dan Gohmanaf752342009-07-07 17:06:11 +00003605const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003606ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3607 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003608 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3609 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003610 "Cannot noop or any extend with non-integer arguments!");
3611 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3612 "getNoopOrAnyExtend cannot truncate!");
3613 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3614 return V; // No conversion
3615 return getAnyExtendExpr(V, Ty);
3616}
3617
Dan Gohmanaf752342009-07-07 17:06:11 +00003618const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003619ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3620 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003621 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3622 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003623 "Cannot truncate or noop with non-integer arguments!");
3624 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3625 "getTruncateOrNoop cannot extend!");
3626 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3627 return V; // No conversion
3628 return getTruncateExpr(V, Ty);
3629}
3630
Dan Gohmanabd17092009-06-24 14:49:00 +00003631const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3632 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003633 const SCEV *PromotedLHS = LHS;
3634 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003635
3636 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3637 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3638 else
3639 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3640
3641 return getUMaxExpr(PromotedLHS, PromotedRHS);
3642}
3643
Dan Gohmanabd17092009-06-24 14:49:00 +00003644const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3645 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003646 const SCEV *PromotedLHS = LHS;
3647 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003648
3649 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3650 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3651 else
3652 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3653
3654 return getUMinExpr(PromotedLHS, PromotedRHS);
3655}
3656
Andrew Trick87716c92011-03-17 23:51:11 +00003657const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3658 // A pointer operand may evaluate to a nonpointer expression, such as null.
3659 if (!V->getType()->isPointerTy())
3660 return V;
3661
3662 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3663 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003664 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003665 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003666 for (const SCEV *NAryOp : NAry->operands()) {
3667 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003668 // Cannot find the base of an expression with multiple pointer operands.
3669 if (PtrOp)
3670 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003671 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003672 }
3673 }
3674 if (!PtrOp)
3675 return V;
3676 return getPointerBase(PtrOp);
3677 }
3678 return V;
3679}
3680
Sanjoy Dasf8570812016-05-29 00:38:22 +00003681/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003682static void
3683PushDefUseChildren(Instruction *I,
3684 SmallVectorImpl<Instruction *> &Worklist) {
3685 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003686 for (User *U : I->users())
3687 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003688}
3689
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003690void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003691 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003692 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003693
Dan Gohman0b89dff2009-07-25 01:13:03 +00003694 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003695 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003696 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003697 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003698 if (!Visited.insert(I).second)
3699 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003700
Sanjoy Das63914592015-10-18 00:29:20 +00003701 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003702 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003703 const SCEV *Old = It->second;
3704
Dan Gohman0b89dff2009-07-25 01:13:03 +00003705 // Short-circuit the def-use traversal if the symbolic name
3706 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003707 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003708 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003709
Dan Gohman0b89dff2009-07-25 01:13:03 +00003710 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003711 // structure, it's a PHI that's in the progress of being computed
3712 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3713 // additional loop trip count information isn't going to change anything.
3714 // In the second case, createNodeForPHI will perform the necessary
3715 // updates on its own when it gets to that point. In the third, we do
3716 // want to forget the SCEVUnknown.
3717 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003718 !isa<SCEVUnknown>(Old) ||
3719 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003720 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003721 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003722 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003723 }
3724
3725 PushDefUseChildren(I, Worklist);
3726 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003727}
Chris Lattnerd934c702004-04-02 20:23:17 +00003728
Benjamin Kramer83709b12015-11-16 09:01:28 +00003729namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003730class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3731public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003732 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003733 ScalarEvolution &SE) {
3734 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003735 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003736 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3737 }
3738
3739 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3740 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3741
3742 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3743 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3744 Valid = false;
3745 return Expr;
3746 }
3747
3748 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3749 // Only allow AddRecExprs for this loop.
3750 if (Expr->getLoop() == L)
3751 return Expr->getStart();
3752 Valid = false;
3753 return Expr;
3754 }
3755
3756 bool isValid() { return Valid; }
3757
3758private:
3759 const Loop *L;
3760 bool Valid;
3761};
3762
3763class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3764public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003765 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003766 ScalarEvolution &SE) {
3767 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003768 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003769 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3770 }
3771
3772 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3773 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3774
3775 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3776 // Only allow AddRecExprs for this loop.
3777 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3778 Valid = false;
3779 return Expr;
3780 }
3781
3782 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3783 if (Expr->getLoop() == L && Expr->isAffine())
3784 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3785 Valid = false;
3786 return Expr;
3787 }
3788 bool isValid() { return Valid; }
3789
3790private:
3791 const Loop *L;
3792 bool Valid;
3793};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003794} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003795
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003796SCEV::NoWrapFlags
3797ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3798 if (!AR->isAffine())
3799 return SCEV::FlagAnyWrap;
3800
3801 typedef OverflowingBinaryOperator OBO;
3802 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3803
3804 if (!AR->hasNoSignedWrap()) {
3805 ConstantRange AddRecRange = getSignedRange(AR);
3806 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3807
3808 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3809 Instruction::Add, IncRange, OBO::NoSignedWrap);
3810 if (NSWRegion.contains(AddRecRange))
3811 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3812 }
3813
3814 if (!AR->hasNoUnsignedWrap()) {
3815 ConstantRange AddRecRange = getUnsignedRange(AR);
3816 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3817
3818 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3819 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3820 if (NUWRegion.contains(AddRecRange))
3821 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3822 }
3823
3824 return Result;
3825}
3826
Sanjoy Das118d9192016-03-31 05:14:22 +00003827namespace {
3828/// Represents an abstract binary operation. This may exist as a
3829/// normal instruction or constant expression, or may have been
3830/// derived from an expression tree.
3831struct BinaryOp {
3832 unsigned Opcode;
3833 Value *LHS;
3834 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003835 bool IsNSW;
3836 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003837
3838 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3839 /// constant expression.
3840 Operator *Op;
3841
3842 explicit BinaryOp(Operator *Op)
3843 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003844 IsNSW(false), IsNUW(false), Op(Op) {
3845 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3846 IsNSW = OBO->hasNoSignedWrap();
3847 IsNUW = OBO->hasNoUnsignedWrap();
3848 }
3849 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003850
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003851 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3852 bool IsNUW = false)
3853 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3854 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003855};
3856}
3857
3858
3859/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003860static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003861 auto *Op = dyn_cast<Operator>(V);
3862 if (!Op)
3863 return None;
3864
3865 // Implementation detail: all the cleverness here should happen without
3866 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3867 // SCEV expressions when possible, and we should not break that.
3868
3869 switch (Op->getOpcode()) {
3870 case Instruction::Add:
3871 case Instruction::Sub:
3872 case Instruction::Mul:
3873 case Instruction::UDiv:
3874 case Instruction::And:
3875 case Instruction::Or:
3876 case Instruction::AShr:
3877 case Instruction::Shl:
3878 return BinaryOp(Op);
3879
3880 case Instruction::Xor:
3881 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3882 // If the RHS of the xor is a signbit, then this is just an add.
3883 // Instcombine turns add of signbit into xor as a strength reduction step.
3884 if (RHSC->getValue().isSignBit())
3885 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3886 return BinaryOp(Op);
3887
3888 case Instruction::LShr:
3889 // Turn logical shift right of a constant into a unsigned divide.
3890 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3891 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3892
3893 // If the shift count is not less than the bitwidth, the result of
3894 // the shift is undefined. Don't try to analyze it, because the
3895 // resolution chosen here may differ from the resolution chosen in
3896 // other parts of the compiler.
3897 if (SA->getValue().ult(BitWidth)) {
3898 Constant *X =
3899 ConstantInt::get(SA->getContext(),
3900 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3901 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3902 }
3903 }
3904 return BinaryOp(Op);
3905
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003906 case Instruction::ExtractValue: {
3907 auto *EVI = cast<ExtractValueInst>(Op);
3908 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3909 break;
3910
3911 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3912 if (!CI)
3913 break;
3914
3915 if (auto *F = CI->getCalledFunction())
3916 switch (F->getIntrinsicID()) {
3917 case Intrinsic::sadd_with_overflow:
3918 case Intrinsic::uadd_with_overflow: {
3919 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3920 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3921 CI->getArgOperand(1));
3922
3923 // Now that we know that all uses of the arithmetic-result component of
3924 // CI are guarded by the overflow check, we can go ahead and pretend
3925 // that the arithmetic is non-overflowing.
3926 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3927 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3928 CI->getArgOperand(1), /* IsNSW = */ true,
3929 /* IsNUW = */ false);
3930 else
3931 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3932 CI->getArgOperand(1), /* IsNSW = */ false,
3933 /* IsNUW*/ true);
3934 }
3935
3936 case Intrinsic::ssub_with_overflow:
3937 case Intrinsic::usub_with_overflow:
3938 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3939 CI->getArgOperand(1));
3940
3941 case Intrinsic::smul_with_overflow:
3942 case Intrinsic::umul_with_overflow:
3943 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3944 CI->getArgOperand(1));
3945 default:
3946 break;
3947 }
3948 }
3949
Sanjoy Das118d9192016-03-31 05:14:22 +00003950 default:
3951 break;
3952 }
3953
3954 return None;
3955}
3956
Sanjoy Das55015d22015-10-02 23:09:44 +00003957const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3958 const Loop *L = LI.getLoopFor(PN->getParent());
3959 if (!L || L->getHeader() != PN->getParent())
3960 return nullptr;
3961
3962 // The loop may have multiple entrances or multiple exits; we can analyze
3963 // this phi as an addrec if it has a unique entry value and a unique
3964 // backedge value.
3965 Value *BEValueV = nullptr, *StartValueV = nullptr;
3966 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3967 Value *V = PN->getIncomingValue(i);
3968 if (L->contains(PN->getIncomingBlock(i))) {
3969 if (!BEValueV) {
3970 BEValueV = V;
3971 } else if (BEValueV != V) {
3972 BEValueV = nullptr;
3973 break;
3974 }
3975 } else if (!StartValueV) {
3976 StartValueV = V;
3977 } else if (StartValueV != V) {
3978 StartValueV = nullptr;
3979 break;
3980 }
3981 }
3982 if (BEValueV && StartValueV) {
3983 // While we are analyzing this PHI node, handle its value symbolically.
3984 const SCEV *SymbolicName = getUnknown(PN);
3985 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3986 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003987 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003988
3989 // Using this symbolic name for the PHI, analyze the value coming around
3990 // the back-edge.
3991 const SCEV *BEValue = getSCEV(BEValueV);
3992
3993 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3994 // has a special value for the first iteration of the loop.
3995
3996 // If the value coming around the backedge is an add with the symbolic
3997 // value we just inserted, then we found a simple induction variable!
3998 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3999 // If there is a single occurrence of the symbolic value, replace it
4000 // with a recurrence.
4001 unsigned FoundIndex = Add->getNumOperands();
4002 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4003 if (Add->getOperand(i) == SymbolicName)
4004 if (FoundIndex == e) {
4005 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004006 break;
4007 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004008
4009 if (FoundIndex != Add->getNumOperands()) {
4010 // Create an add with everything but the specified operand.
4011 SmallVector<const SCEV *, 8> Ops;
4012 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4013 if (i != FoundIndex)
4014 Ops.push_back(Add->getOperand(i));
4015 const SCEV *Accum = getAddExpr(Ops);
4016
4017 // This is not a valid addrec if the step amount is varying each
4018 // loop iteration, but is not itself an addrec in this loop.
4019 if (isLoopInvariant(Accum, L) ||
4020 (isa<SCEVAddRecExpr>(Accum) &&
4021 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4022 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4023
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004024 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004025 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4026 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004027 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004028 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004029 Flags = setFlags(Flags, SCEV::FlagNSW);
4030 }
4031 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4032 // If the increment is an inbounds GEP, then we know the address
4033 // space cannot be wrapped around. We cannot make any guarantee
4034 // about signed or unsigned overflow because pointers are
4035 // unsigned but we may have a negative index from the base
4036 // pointer. We can guarantee that no unsigned wrap occurs if the
4037 // indices form a positive value.
4038 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4039 Flags = setFlags(Flags, SCEV::FlagNW);
4040
4041 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4042 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4043 Flags = setFlags(Flags, SCEV::FlagNUW);
4044 }
4045
4046 // We cannot transfer nuw and nsw flags from subtraction
4047 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4048 // for instance.
4049 }
4050
4051 const SCEV *StartVal = getSCEV(StartValueV);
4052 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4053
Sanjoy Das55015d22015-10-02 23:09:44 +00004054 // Okay, for the entire analysis of this edge we assumed the PHI
4055 // to be symbolic. We now need to go back and purge all of the
4056 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004057 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004058 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004059
4060 // We can add Flags to the post-inc expression only if we
4061 // know that it us *undefined behavior* for BEValueV to
4062 // overflow.
4063 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4064 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4065 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4066
Sanjoy Das55015d22015-10-02 23:09:44 +00004067 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004068 }
4069 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004070 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004071 // Otherwise, this could be a loop like this:
4072 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4073 // In this case, j = {1,+,1} and BEValue is j.
4074 // Because the other in-value of i (0) fits the evolution of BEValue
4075 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004076 //
4077 // We can generalize this saying that i is the shifted value of BEValue
4078 // by one iteration:
4079 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4080 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4081 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4082 if (Shifted != getCouldNotCompute() &&
4083 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004084 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004085 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004086 // Okay, for the entire analysis of this edge we assumed the PHI
4087 // to be symbolic. We now need to go back and purge all of the
4088 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004089 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004090 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4091 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004092 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004093 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004094 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004095
4096 // Remove the temporary PHI node SCEV that has been inserted while intending
4097 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4098 // as it will prevent later (possibly simpler) SCEV expressions to be added
4099 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004100 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004101 }
4102
4103 return nullptr;
4104}
4105
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004106// Checks if the SCEV S is available at BB. S is considered available at BB
4107// if S can be materialized at BB without introducing a fault.
4108static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4109 BasicBlock *BB) {
4110 struct CheckAvailable {
4111 bool TraversalDone = false;
4112 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004113
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004114 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4115 BasicBlock *BB = nullptr;
4116 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004117
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004118 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4119 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004120
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004121 bool setUnavailable() {
4122 TraversalDone = true;
4123 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004124 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004125 }
4126
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004127 bool follow(const SCEV *S) {
4128 switch (S->getSCEVType()) {
4129 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4130 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004131 // These expressions are available if their operand(s) is/are.
4132 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004133
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004134 case scAddRecExpr: {
4135 // We allow add recurrences that are on the loop BB is in, or some
4136 // outer loop. This guarantees availability because the value of the
4137 // add recurrence at BB is simply the "current" value of the induction
4138 // variable. We can relax this in the future; for instance an add
4139 // recurrence on a sibling dominating loop is also available at BB.
4140 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4141 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004142 return true;
4143
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004144 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004145 }
4146
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004147 case scUnknown: {
4148 // For SCEVUnknown, we check for simple dominance.
4149 const auto *SU = cast<SCEVUnknown>(S);
4150 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004151
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004152 if (isa<Argument>(V))
4153 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004154
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004155 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4156 return false;
4157
4158 return setUnavailable();
4159 }
4160
4161 case scUDivExpr:
4162 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004163 // We do not try to smart about these at all.
4164 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004165 }
4166 llvm_unreachable("switch should be fully covered!");
4167 }
4168
4169 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004170 };
4171
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004172 CheckAvailable CA(L, BB, DT);
4173 SCEVTraversal<CheckAvailable> ST(CA);
4174
4175 ST.visitAll(S);
4176 return CA.Available;
4177}
4178
4179// Try to match a control flow sequence that branches out at BI and merges back
4180// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4181// match.
4182static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4183 Value *&C, Value *&LHS, Value *&RHS) {
4184 C = BI->getCondition();
4185
4186 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4187 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4188
4189 if (!LeftEdge.isSingleEdge())
4190 return false;
4191
4192 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4193
4194 Use &LeftUse = Merge->getOperandUse(0);
4195 Use &RightUse = Merge->getOperandUse(1);
4196
4197 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4198 LHS = LeftUse;
4199 RHS = RightUse;
4200 return true;
4201 }
4202
4203 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4204 LHS = RightUse;
4205 RHS = LeftUse;
4206 return true;
4207 }
4208
4209 return false;
4210}
4211
4212const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004213 auto IsReachable =
4214 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4215 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004216 const Loop *L = LI.getLoopFor(PN->getParent());
4217
Sanjoy Das337d4782015-10-31 23:21:40 +00004218 // We don't want to break LCSSA, even in a SCEV expression tree.
4219 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4220 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4221 return nullptr;
4222
Sanjoy Das55015d22015-10-02 23:09:44 +00004223 // Try to match
4224 //
4225 // br %cond, label %left, label %right
4226 // left:
4227 // br label %merge
4228 // right:
4229 // br label %merge
4230 // merge:
4231 // V = phi [ %x, %left ], [ %y, %right ]
4232 //
4233 // as "select %cond, %x, %y"
4234
4235 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4236 assert(IDom && "At least the entry block should dominate PN");
4237
4238 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4239 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4240
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004241 if (BI && BI->isConditional() &&
4242 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4243 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4244 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004245 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4246 }
4247
4248 return nullptr;
4249}
4250
4251const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4252 if (const SCEV *S = createAddRecFromPHI(PN))
4253 return S;
4254
4255 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4256 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004257
Dan Gohmana9c205c2010-02-25 06:57:05 +00004258 // If the PHI has a single incoming value, follow that value, unless the
4259 // PHI's incoming blocks are in a different loop, in which case doing so
4260 // risks breaking LCSSA form. Instcombine would normally zap these, but
4261 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004262 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004263 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004264 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004265
Chris Lattnerd934c702004-04-02 20:23:17 +00004266 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004267 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004268}
4269
Sanjoy Das55015d22015-10-02 23:09:44 +00004270const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4271 Value *Cond,
4272 Value *TrueVal,
4273 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004274 // Handle "constant" branch or select. This can occur for instance when a
4275 // loop pass transforms an inner loop and moves on to process the outer loop.
4276 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4277 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4278
Sanjoy Dasd0671342015-10-02 19:39:59 +00004279 // Try to match some simple smax or umax patterns.
4280 auto *ICI = dyn_cast<ICmpInst>(Cond);
4281 if (!ICI)
4282 return getUnknown(I);
4283
4284 Value *LHS = ICI->getOperand(0);
4285 Value *RHS = ICI->getOperand(1);
4286
4287 switch (ICI->getPredicate()) {
4288 case ICmpInst::ICMP_SLT:
4289 case ICmpInst::ICMP_SLE:
4290 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004291 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004292 case ICmpInst::ICMP_SGT:
4293 case ICmpInst::ICMP_SGE:
4294 // a >s b ? a+x : b+x -> smax(a, b)+x
4295 // a >s b ? b+x : a+x -> smin(a, b)+x
4296 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4297 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4298 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4299 const SCEV *LA = getSCEV(TrueVal);
4300 const SCEV *RA = getSCEV(FalseVal);
4301 const SCEV *LDiff = getMinusSCEV(LA, LS);
4302 const SCEV *RDiff = getMinusSCEV(RA, RS);
4303 if (LDiff == RDiff)
4304 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4305 LDiff = getMinusSCEV(LA, RS);
4306 RDiff = getMinusSCEV(RA, LS);
4307 if (LDiff == RDiff)
4308 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4309 }
4310 break;
4311 case ICmpInst::ICMP_ULT:
4312 case ICmpInst::ICMP_ULE:
4313 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004314 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004315 case ICmpInst::ICMP_UGT:
4316 case ICmpInst::ICMP_UGE:
4317 // a >u b ? a+x : b+x -> umax(a, b)+x
4318 // a >u b ? b+x : a+x -> umin(a, b)+x
4319 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4320 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4321 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4322 const SCEV *LA = getSCEV(TrueVal);
4323 const SCEV *RA = getSCEV(FalseVal);
4324 const SCEV *LDiff = getMinusSCEV(LA, LS);
4325 const SCEV *RDiff = getMinusSCEV(RA, RS);
4326 if (LDiff == RDiff)
4327 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4328 LDiff = getMinusSCEV(LA, RS);
4329 RDiff = getMinusSCEV(RA, LS);
4330 if (LDiff == RDiff)
4331 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4332 }
4333 break;
4334 case ICmpInst::ICMP_NE:
4335 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4336 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4337 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4338 const SCEV *One = getOne(I->getType());
4339 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4340 const SCEV *LA = getSCEV(TrueVal);
4341 const SCEV *RA = getSCEV(FalseVal);
4342 const SCEV *LDiff = getMinusSCEV(LA, LS);
4343 const SCEV *RDiff = getMinusSCEV(RA, One);
4344 if (LDiff == RDiff)
4345 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4346 }
4347 break;
4348 case ICmpInst::ICMP_EQ:
4349 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4350 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4351 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4352 const SCEV *One = getOne(I->getType());
4353 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4354 const SCEV *LA = getSCEV(TrueVal);
4355 const SCEV *RA = getSCEV(FalseVal);
4356 const SCEV *LDiff = getMinusSCEV(LA, One);
4357 const SCEV *RDiff = getMinusSCEV(RA, LS);
4358 if (LDiff == RDiff)
4359 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4360 }
4361 break;
4362 default:
4363 break;
4364 }
4365
4366 return getUnknown(I);
4367}
4368
Sanjoy Dasf8570812016-05-29 00:38:22 +00004369/// Expand GEP instructions into add and multiply operations. This allows them
4370/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004371const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004372 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004373 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004374 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004375
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004376 SmallVector<const SCEV *, 4> IndexExprs;
4377 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4378 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004379 return getGEPExpr(GEP->getSourceElementType(),
4380 getSCEV(GEP->getPointerOperand()),
4381 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004382}
4383
Dan Gohmanc702fc02009-06-19 23:29:04 +00004384uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004385ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004386 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004387 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004388
Dan Gohmana30370b2009-05-04 22:02:23 +00004389 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004390 return std::min(GetMinTrailingZeros(T->getOperand()),
4391 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004392
Dan Gohmana30370b2009-05-04 22:02:23 +00004393 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004394 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4395 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4396 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004397 }
4398
Dan Gohmana30370b2009-05-04 22:02:23 +00004399 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(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 SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004406 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004407 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004408 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004409 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004410 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004411 }
4412
Dan Gohmana30370b2009-05-04 22:02:23 +00004413 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004414 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004415 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4416 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004417 for (unsigned i = 1, e = M->getNumOperands();
4418 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004419 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004420 BitWidth);
4421 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004422 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004423
Dan Gohmana30370b2009-05-04 22:02:23 +00004424 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004425 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004426 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004427 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004428 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004429 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004430 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004431
Dan Gohmana30370b2009-05-04 22:02:23 +00004432 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004433 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004434 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004435 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004436 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004437 return MinOpRes;
4438 }
4439
Dan Gohmana30370b2009-05-04 22:02:23 +00004440 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004441 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004442 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004443 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004444 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004445 return MinOpRes;
4446 }
4447
Dan Gohmanc702fc02009-06-19 23:29:04 +00004448 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4449 // For a SCEVUnknown, ask ValueTracking.
4450 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004451 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004452 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4453 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004454 return Zeros.countTrailingOnes();
4455 }
4456
4457 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004458 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004459}
Chris Lattnerd934c702004-04-02 20:23:17 +00004460
Sanjoy Dasf8570812016-05-29 00:38:22 +00004461/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004462static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004463 if (Instruction *I = dyn_cast<Instruction>(V))
4464 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4465 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004466
4467 return None;
4468}
4469
Sanjoy Dasf8570812016-05-29 00:38:22 +00004470/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004471/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4472/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004473ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004474ScalarEvolution::getRange(const SCEV *S,
4475 ScalarEvolution::RangeSignHint SignHint) {
4476 DenseMap<const SCEV *, ConstantRange> &Cache =
4477 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4478 : SignedRanges;
4479
Dan Gohman761065e2010-11-17 02:44:44 +00004480 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004481 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4482 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004483 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004484
4485 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004486 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004487
Dan Gohman85be4332010-01-26 19:19:05 +00004488 unsigned BitWidth = getTypeSizeInBits(S->getType());
4489 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4490
Sanjoy Das91b54772015-03-09 21:43:43 +00004491 // If the value has known zeros, the maximum value will have those known zeros
4492 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004493 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004494 if (TZ != 0) {
4495 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4496 ConservativeResult =
4497 ConstantRange(APInt::getMinValue(BitWidth),
4498 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4499 else
4500 ConservativeResult = ConstantRange(
4501 APInt::getSignedMinValue(BitWidth),
4502 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4503 }
Dan Gohman85be4332010-01-26 19:19:05 +00004504
Dan Gohmane65c9172009-07-13 21:35:55 +00004505 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004506 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004507 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004508 X = X.add(getRange(Add->getOperand(i), SignHint));
4509 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004510 }
4511
4512 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004513 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004514 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004515 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4516 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004517 }
4518
4519 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004520 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004521 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004522 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4523 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004524 }
4525
4526 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004527 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004528 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004529 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4530 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004531 }
4532
4533 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004534 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4535 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4536 return setRange(UDiv, SignHint,
4537 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004538 }
4539
4540 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004541 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4542 return setRange(ZExt, SignHint,
4543 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004544 }
4545
4546 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004547 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4548 return setRange(SExt, SignHint,
4549 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004550 }
4551
4552 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004553 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4554 return setRange(Trunc, SignHint,
4555 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004556 }
4557
Dan Gohmane65c9172009-07-13 21:35:55 +00004558 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004559 // If there's no unsigned wrap, the value will never be less than its
4560 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004561 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004562 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004563 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004564 ConservativeResult = ConservativeResult.intersectWith(
4565 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004566
Dan Gohman51ad99d2010-01-21 02:09:26 +00004567 // If there's no signed wrap, and all the operands have the same sign or
4568 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004569 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004570 bool AllNonNeg = true;
4571 bool AllNonPos = true;
4572 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4573 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4574 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4575 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004576 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004577 ConservativeResult = ConservativeResult.intersectWith(
4578 ConstantRange(APInt(BitWidth, 0),
4579 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004580 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004581 ConservativeResult = ConservativeResult.intersectWith(
4582 ConstantRange(APInt::getSignedMinValue(BitWidth),
4583 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004584 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004585
4586 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004587 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004588 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004589 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4590 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004591 auto RangeFromAffine = getRangeForAffineAR(
4592 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4593 BitWidth);
4594 if (!RangeFromAffine.isFullSet())
4595 ConservativeResult =
4596 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004597
4598 auto RangeFromFactoring = getRangeViaFactoring(
4599 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4600 BitWidth);
4601 if (!RangeFromFactoring.isFullSet())
4602 ConservativeResult =
4603 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004604 }
Dan Gohmand261d272009-06-24 01:05:09 +00004605 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004606
Sanjoy Das91b54772015-03-09 21:43:43 +00004607 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004608 }
4609
Dan Gohmanc702fc02009-06-19 23:29:04 +00004610 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004611 // Check if the IR explicitly contains !range metadata.
4612 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4613 if (MDRange.hasValue())
4614 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4615
Sanjoy Das91b54772015-03-09 21:43:43 +00004616 // Split here to avoid paying the compile-time cost of calling both
4617 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4618 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004619 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004620 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4621 // For a SCEVUnknown, ask ValueTracking.
4622 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004623 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004624 if (Ones != ~Zeros + 1)
4625 ConservativeResult =
4626 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4627 } else {
4628 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4629 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004630 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004631 if (NS > 1)
4632 ConservativeResult = ConservativeResult.intersectWith(
4633 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4634 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004635 }
4636
4637 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004638 }
4639
Sanjoy Das91b54772015-03-09 21:43:43 +00004640 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004641}
4642
Sanjoy Dasb765b632016-03-02 00:57:39 +00004643ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4644 const SCEV *Step,
4645 const SCEV *MaxBECount,
4646 unsigned BitWidth) {
4647 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4648 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4649 "Precondition!");
4650
4651 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4652
4653 // Check for overflow. This must be done with ConstantRange arithmetic
4654 // because we could be called from within the ScalarEvolution overflow
4655 // checking code.
4656
4657 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4658 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4659 ConstantRange ZExtMaxBECountRange =
4660 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4661
4662 ConstantRange StepSRange = getSignedRange(Step);
4663 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4664
4665 ConstantRange StartURange = getUnsignedRange(Start);
4666 ConstantRange EndURange =
4667 StartURange.add(MaxBECountRange.multiply(StepSRange));
4668
4669 // Check for unsigned overflow.
4670 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4671 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4672 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4673 ZExtEndURange) {
4674 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4675 EndURange.getUnsignedMin());
4676 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4677 EndURange.getUnsignedMax());
4678 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4679 if (!IsFullRange)
4680 Result =
4681 Result.intersectWith(ConstantRange(Min, Max + 1));
4682 }
4683
4684 ConstantRange StartSRange = getSignedRange(Start);
4685 ConstantRange EndSRange =
4686 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4687
4688 // Check for signed overflow. This must be done with ConstantRange
4689 // arithmetic because we could be called from within the ScalarEvolution
4690 // overflow checking code.
4691 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4692 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4693 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4694 SExtEndSRange) {
4695 APInt Min =
4696 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4697 APInt Max =
4698 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4699 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4700 if (!IsFullRange)
4701 Result =
4702 Result.intersectWith(ConstantRange(Min, Max + 1));
4703 }
4704
4705 return Result;
4706}
4707
Sanjoy Dasbf730982016-03-02 00:57:54 +00004708ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4709 const SCEV *Step,
4710 const SCEV *MaxBECount,
4711 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004712 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4713 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4714
4715 struct SelectPattern {
4716 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004717 APInt TrueValue;
4718 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004719
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004720 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4721 const SCEV *S) {
4722 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004723 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004724
4725 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4726 "Should be!");
4727
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004728 // Peel off a constant offset:
4729 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4730 // In the future we could consider being smarter here and handle
4731 // {Start+Step,+,Step} too.
4732 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4733 return;
4734
4735 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4736 S = SA->getOperand(1);
4737 }
4738
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004739 // Peel off a cast operation
4740 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4741 CastOp = SCast->getSCEVType();
4742 S = SCast->getOperand();
4743 }
4744
Sanjoy Dasbf730982016-03-02 00:57:54 +00004745 using namespace llvm::PatternMatch;
4746
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004747 auto *SU = dyn_cast<SCEVUnknown>(S);
4748 const APInt *TrueVal, *FalseVal;
4749 if (!SU ||
4750 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4751 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004752 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004753 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004754 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004755
4756 TrueValue = *TrueVal;
4757 FalseValue = *FalseVal;
4758
4759 // Re-apply the cast we peeled off earlier
4760 if (CastOp.hasValue())
4761 switch (*CastOp) {
4762 default:
4763 llvm_unreachable("Unknown SCEV cast type!");
4764
4765 case scTruncate:
4766 TrueValue = TrueValue.trunc(BitWidth);
4767 FalseValue = FalseValue.trunc(BitWidth);
4768 break;
4769 case scZeroExtend:
4770 TrueValue = TrueValue.zext(BitWidth);
4771 FalseValue = FalseValue.zext(BitWidth);
4772 break;
4773 case scSignExtend:
4774 TrueValue = TrueValue.sext(BitWidth);
4775 FalseValue = FalseValue.sext(BitWidth);
4776 break;
4777 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004778
4779 // Re-apply the constant offset we peeled off earlier
4780 TrueValue += Offset;
4781 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004782 }
4783
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004784 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004785 };
4786
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004787 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004788 if (!StartPattern.isRecognized())
4789 return ConstantRange(BitWidth, /* isFullSet = */ true);
4790
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004791 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004792 if (!StepPattern.isRecognized())
4793 return ConstantRange(BitWidth, /* isFullSet = */ true);
4794
4795 if (StartPattern.Condition != StepPattern.Condition) {
4796 // We don't handle this case today; but we could, by considering four
4797 // possibilities below instead of two. I'm not sure if there are cases where
4798 // that will help over what getRange already does, though.
4799 return ConstantRange(BitWidth, /* isFullSet = */ true);
4800 }
4801
4802 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4803 // construct arbitrary general SCEV expressions here. This function is called
4804 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4805 // say) can end up caching a suboptimal value.
4806
Sanjoy Das6b017a12016-03-02 02:56:29 +00004807 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4808 // C2352 and C2512 (otherwise it isn't needed).
4809
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004810 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004811 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004812 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004813 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004814
Sanjoy Das1168f932016-03-02 02:34:20 +00004815 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004816 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004817 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004818 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004819
4820 return TrueRange.unionWith(FalseRange);
4821}
4822
Jingyue Wu42f1d672015-07-28 18:22:40 +00004823SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004824 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004825 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4826
4827 // Return early if there are no flags to propagate to the SCEV.
4828 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4829 if (BinOp->hasNoUnsignedWrap())
4830 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4831 if (BinOp->hasNoSignedWrap())
4832 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004833 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004834 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004835
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004836 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4837}
4838
4839bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4840 // Here we check that I is in the header of the innermost loop containing I,
4841 // since we only deal with instructions in the loop header. The actual loop we
4842 // need to check later will come from an add recurrence, but getting that
4843 // requires computing the SCEV of the operands, which can be expensive. This
4844 // check we can do cheaply to rule out some cases early.
4845 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004846 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004847 InnermostContainingLoop->getHeader() != I->getParent())
4848 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004849
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004850 // Only proceed if we can prove that I does not yield poison.
4851 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004852
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004853 // At this point we know that if I is executed, then it does not wrap
4854 // according to at least one of NSW or NUW. If I is not executed, then we do
4855 // not know if the calculation that I represents would wrap. Multiple
4856 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004857 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4858 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004859 // that guarantee for cases where I is not executed. So we need to find the
4860 // loop that I is considered in relation to and prove that I is executed for
4861 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004862 // calculates does not wrap anywhere in the loop, so then we can apply the
4863 // flags to the SCEV.
4864 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004865 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4866 // from different loops, so that we know which loop to prove that I is
4867 // executed in.
4868 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004869 // I could be an extractvalue from a call to an overflow intrinsic.
4870 // TODO: We can do better here in some cases.
4871 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4872 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004873 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004874 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004875 bool AllOtherOpsLoopInvariant = true;
4876 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4877 ++OtherOpIndex) {
4878 if (OtherOpIndex != OpIndex) {
4879 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4880 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4881 AllOtherOpsLoopInvariant = false;
4882 break;
4883 }
4884 }
4885 }
4886 if (AllOtherOpsLoopInvariant &&
4887 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4888 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004889 }
4890 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004891 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004892}
4893
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004894bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4895 // If we know that \c I can never be poison period, then that's enough.
4896 if (isSCEVExprNeverPoison(I))
4897 return true;
4898
4899 // For an add recurrence specifically, we assume that infinite loops without
4900 // side effects are undefined behavior, and then reason as follows:
4901 //
4902 // If the add recurrence is poison in any iteration, it is poison on all
4903 // future iterations (since incrementing poison yields poison). If the result
4904 // of the add recurrence is fed into the loop latch condition and the loop
4905 // does not contain any throws or exiting blocks other than the latch, we now
4906 // have the ability to "choose" whether the backedge is taken or not (by
4907 // choosing a sufficiently evil value for the poison feeding into the branch)
4908 // for every iteration including and after the one in which \p I first became
4909 // poison. There are two possibilities (let's call the iteration in which \p
4910 // I first became poison as K):
4911 //
4912 // 1. In the set of iterations including and after K, the loop body executes
4913 // no side effects. In this case executing the backege an infinte number
4914 // of times will yield undefined behavior.
4915 //
4916 // 2. In the set of iterations including and after K, the loop body executes
4917 // at least one side effect. In this case, that specific instance of side
4918 // effect is control dependent on poison, which also yields undefined
4919 // behavior.
4920
4921 auto *ExitingBB = L->getExitingBlock();
4922 auto *LatchBB = L->getLoopLatch();
4923 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4924 return false;
4925
4926 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004927 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004928
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004929 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4930 // things that are known to be fully poison under that assumption go on the
4931 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004932 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004933 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004934
4935 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004936 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004937 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004938
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004939 for (auto *PoisonUser : Poison->users()) {
4940 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4941 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4942 PoisonStack.push_back(cast<Instruction>(PoisonUser));
4943 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004944 assert(BI->isConditional() && "Only possibility!");
4945 if (BI->getParent() == LatchBB) {
4946 LatchControlDependentOnPoison = true;
4947 break;
4948 }
4949 }
4950 }
4951 }
4952
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004953 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4954}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004955
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004956bool ScalarEvolution::loopHasNoSideEffects(const Loop *L) {
4957 auto Itr = LoopHasNoSideEffects.find(L);
4958 if (Itr == LoopHasNoSideEffects.end()) {
4959 auto NoSideEffectsInBB = [&](BasicBlock *BB) {
4960 return all_of(*BB, [](Instruction &I) {
4961 // Non-atomic, non-volatile stores are ok.
4962 if (auto *SI = dyn_cast<StoreInst>(&I))
4963 return SI->isSimple();
4964
4965 return !I.mayHaveSideEffects();
4966 });
4967 };
4968
4969 auto InsertPair = LoopHasNoSideEffects.insert(
4970 {L, all_of(L->getBlocks(), NoSideEffectsInBB)});
4971 assert(InsertPair.second && "We just checked!");
4972 Itr = InsertPair.first;
4973 }
4974
4975 return Itr->second;
4976}
4977
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004978bool ScalarEvolution::loopHasNoAbnormalExits(const Loop *L) {
4979 auto Itr = LoopHasNoAbnormalExits.find(L);
4980 if (Itr == LoopHasNoAbnormalExits.end()) {
Sanjoy Das1eade912016-06-09 01:14:03 +00004981 auto NoAbnormalExitInBB = [&](BasicBlock *BB) {
4982 return all_of(*BB, [](Instruction &I) {
4983 return isGuaranteedToTransferExecutionToSuccessor(&I);
Sanjoy Das85984122016-06-08 17:48:42 +00004984 });
Sanjoy Das1eade912016-06-09 01:14:03 +00004985 };
4986
4987 auto InsertPair = LoopHasNoAbnormalExits.insert(
4988 {L, all_of(L->getBlocks(), NoAbnormalExitInBB)});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004989 assert(InsertPair.second && "We just checked!");
4990 Itr = InsertPair.first;
4991 }
4992
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004993 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004994}
4995
Dan Gohmanaf752342009-07-07 17:06:11 +00004996const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004997 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004998 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004999
Dan Gohman69451a02010-03-09 23:46:50 +00005000 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005001 // Don't attempt to analyze instructions in blocks that aren't
5002 // reachable. Such instructions don't matter, and they aren't required
5003 // to obey basic rules for definitions dominating uses which this
5004 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005005 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005006 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005007 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005008 return getConstant(CI);
5009 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005010 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005011 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005012 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005013 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005014 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005015
Dan Gohman80ca01c2009-07-17 20:47:02 +00005016 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005017 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005018 switch (BO->Opcode) {
5019 case Instruction::Add: {
5020 // The simple thing to do would be to just call getSCEV on both operands
5021 // and call getAddExpr with the result. However if we're looking at a
5022 // bunch of things all added together, this can be quite inefficient,
5023 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5024 // Instead, gather up all the operands and make a single getAddExpr call.
5025 // LLVM IR canonical form means we need only traverse the left operands.
5026 SmallVector<const SCEV *, 4> AddOps;
5027 do {
5028 if (BO->Op) {
5029 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5030 AddOps.push_back(OpSCEV);
5031 break;
5032 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005033
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005034 // If a NUW or NSW flag can be applied to the SCEV for this
5035 // addition, then compute the SCEV for this addition by itself
5036 // with a separate call to getAddExpr. We need to do that
5037 // instead of pushing the operands of the addition onto AddOps,
5038 // since the flags are only known to apply to this particular
5039 // addition - they may not apply to other additions that can be
5040 // formed with operands from AddOps.
5041 const SCEV *RHS = getSCEV(BO->RHS);
5042 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5043 if (Flags != SCEV::FlagAnyWrap) {
5044 const SCEV *LHS = getSCEV(BO->LHS);
5045 if (BO->Opcode == Instruction::Sub)
5046 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5047 else
5048 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5049 break;
5050 }
Dan Gohman36bad002009-09-17 18:05:20 +00005051 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005052
5053 if (BO->Opcode == Instruction::Sub)
5054 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5055 else
5056 AddOps.push_back(getSCEV(BO->RHS));
5057
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005058 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005059 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5060 NewBO->Opcode != Instruction::Sub)) {
5061 AddOps.push_back(getSCEV(BO->LHS));
5062 break;
5063 }
5064 BO = NewBO;
5065 } while (true);
5066
5067 return getAddExpr(AddOps);
5068 }
5069
5070 case Instruction::Mul: {
5071 SmallVector<const SCEV *, 4> MulOps;
5072 do {
5073 if (BO->Op) {
5074 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5075 MulOps.push_back(OpSCEV);
5076 break;
5077 }
5078
5079 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5080 if (Flags != SCEV::FlagAnyWrap) {
5081 MulOps.push_back(
5082 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5083 break;
5084 }
5085 }
5086
5087 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005088 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005089 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5090 MulOps.push_back(getSCEV(BO->LHS));
5091 break;
5092 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005093 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005094 } while (true);
5095
5096 return getMulExpr(MulOps);
5097 }
5098 case Instruction::UDiv:
5099 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5100 case Instruction::Sub: {
5101 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5102 if (BO->Op)
5103 Flags = getNoWrapFlagsFromUB(BO->Op);
5104 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5105 }
5106 case Instruction::And:
5107 // For an expression like x&255 that merely masks off the high bits,
5108 // use zext(trunc(x)) as the SCEV expression.
5109 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5110 if (CI->isNullValue())
5111 return getSCEV(BO->RHS);
5112 if (CI->isAllOnesValue())
5113 return getSCEV(BO->LHS);
5114 const APInt &A = CI->getValue();
5115
5116 // Instcombine's ShrinkDemandedConstant may strip bits out of
5117 // constants, obscuring what would otherwise be a low-bits mask.
5118 // Use computeKnownBits to compute what ShrinkDemandedConstant
5119 // knew about to reconstruct a low-bits mask value.
5120 unsigned LZ = A.countLeadingZeros();
5121 unsigned TZ = A.countTrailingZeros();
5122 unsigned BitWidth = A.getBitWidth();
5123 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5124 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5125 0, &AC, nullptr, &DT);
5126
5127 APInt EffectiveMask =
5128 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5129 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5130 const SCEV *MulCount = getConstant(ConstantInt::get(
5131 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5132 return getMulExpr(
5133 getZeroExtendExpr(
5134 getTruncateExpr(
5135 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5136 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5137 BO->LHS->getType()),
5138 MulCount);
5139 }
Dan Gohman36bad002009-09-17 18:05:20 +00005140 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005141 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005142
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005143 case Instruction::Or:
5144 // If the RHS of the Or is a constant, we may have something like:
5145 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5146 // optimizations will transparently handle this case.
5147 //
5148 // In order for this transformation to be safe, the LHS must be of the
5149 // form X*(2^n) and the Or constant must be less than 2^n.
5150 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5151 const SCEV *LHS = getSCEV(BO->LHS);
5152 const APInt &CIVal = CI->getValue();
5153 if (GetMinTrailingZeros(LHS) >=
5154 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5155 // Build a plain add SCEV.
5156 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5157 // If the LHS of the add was an addrec and it has no-wrap flags,
5158 // transfer the no-wrap flags, since an or won't introduce a wrap.
5159 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5160 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5161 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5162 OldAR->getNoWrapFlags());
5163 }
5164 return S;
5165 }
5166 }
5167 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005168
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005169 case Instruction::Xor:
5170 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5171 // If the RHS of xor is -1, then this is a not operation.
5172 if (CI->isAllOnesValue())
5173 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005174
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005175 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5176 // This is a variant of the check for xor with -1, and it handles
5177 // the case where instcombine has trimmed non-demanded bits out
5178 // of an xor with -1.
5179 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5180 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5181 if (LBO->getOpcode() == Instruction::And &&
5182 LCI->getValue() == CI->getValue())
5183 if (const SCEVZeroExtendExpr *Z =
5184 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5185 Type *UTy = BO->LHS->getType();
5186 const SCEV *Z0 = Z->getOperand();
5187 Type *Z0Ty = Z0->getType();
5188 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005189
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005190 // If C is a low-bits mask, the zero extend is serving to
5191 // mask off the high bits. Complement the operand and
5192 // re-apply the zext.
5193 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5194 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5195
5196 // If C is a single bit, it may be in the sign-bit position
5197 // before the zero-extend. In this case, represent the xor
5198 // using an add, which is equivalent, and re-apply the zext.
5199 APInt Trunc = CI->getValue().trunc(Z0TySize);
5200 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5201 Trunc.isSignBit())
5202 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5203 UTy);
5204 }
5205 }
5206 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005207
5208 case Instruction::Shl:
5209 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005210 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5211 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005212
5213 // If the shift count is not less than the bitwidth, the result of
5214 // the shift is undefined. Don't try to analyze it, because the
5215 // resolution chosen here may differ from the resolution chosen in
5216 // other parts of the compiler.
5217 if (SA->getValue().uge(BitWidth))
5218 break;
5219
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005220 // It is currently not resolved how to interpret NSW for left
5221 // shift by BitWidth - 1, so we avoid applying flags in that
5222 // case. Remove this check (or this comment) once the situation
5223 // is resolved. See
5224 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5225 // and http://reviews.llvm.org/D8890 .
5226 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005227 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5228 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005229
Owen Andersonedb4a702009-07-24 23:12:02 +00005230 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005231 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005232 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005233 }
5234 break;
5235
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005236 case Instruction::AShr:
5237 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5238 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5239 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5240 if (L->getOpcode() == Instruction::Shl &&
5241 L->getOperand(1) == BO->RHS) {
5242 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005243
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005244 // If the shift count is not less than the bitwidth, the result of
5245 // the shift is undefined. Don't try to analyze it, because the
5246 // resolution chosen here may differ from the resolution chosen in
5247 // other parts of the compiler.
5248 if (CI->getValue().uge(BitWidth))
5249 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005250
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005251 uint64_t Amt = BitWidth - CI->getZExtValue();
5252 if (Amt == BitWidth)
5253 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5254 return getSignExtendExpr(
5255 getTruncateExpr(getSCEV(L->getOperand(0)),
5256 IntegerType::get(getContext(), Amt)),
5257 BO->LHS->getType());
5258 }
5259 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005260 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005261 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005262
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005263 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005264 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005265 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005266
5267 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005268 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005269
5270 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005271 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005272
5273 case Instruction::BitCast:
5274 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005275 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005276 return getSCEV(U->getOperand(0));
5277 break;
5278
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005279 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5280 // lead to pointer expressions which cannot safely be expanded to GEPs,
5281 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5282 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005283
Dan Gohmanee750d12009-05-08 20:26:55 +00005284 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005285 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005286
Dan Gohman05e89732008-06-22 19:56:46 +00005287 case Instruction::PHI:
5288 return createNodeForPHI(cast<PHINode>(U));
5289
5290 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005291 // U can also be a select constant expr, which let fall through. Since
5292 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5293 // constant expressions cannot have instructions as operands, we'd have
5294 // returned getUnknown for a select constant expressions anyway.
5295 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005296 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5297 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005298 break;
5299
5300 case Instruction::Call:
5301 case Instruction::Invoke:
5302 if (Value *RV = CallSite(U).getReturnedArgOperand())
5303 return getSCEV(RV);
5304 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005305 }
5306
Dan Gohmanc8e23622009-04-21 23:15:49 +00005307 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005308}
5309
5310
5311
5312//===----------------------------------------------------------------------===//
5313// Iteration Count Computation Code
5314//
5315
Chandler Carruth6666c272014-10-11 00:12:11 +00005316unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5317 if (BasicBlock *ExitingBB = L->getExitingBlock())
5318 return getSmallConstantTripCount(L, ExitingBB);
5319
5320 // No trip count information for multiple exits.
5321 return 0;
5322}
5323
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005324unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5325 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005326 assert(ExitingBlock && "Must pass a non-null exiting block!");
5327 assert(L->isLoopExiting(ExitingBlock) &&
5328 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005329 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005330 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005331 if (!ExitCount)
5332 return 0;
5333
5334 ConstantInt *ExitConst = ExitCount->getValue();
5335
5336 // Guard against huge trip counts.
5337 if (ExitConst->getValue().getActiveBits() > 32)
5338 return 0;
5339
5340 // In case of integer overflow, this returns 0, which is correct.
5341 return ((unsigned)ExitConst->getZExtValue()) + 1;
5342}
5343
Chandler Carruth6666c272014-10-11 00:12:11 +00005344unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5345 if (BasicBlock *ExitingBB = L->getExitingBlock())
5346 return getSmallConstantTripMultiple(L, ExitingBB);
5347
5348 // No trip multiple information for multiple exits.
5349 return 0;
5350}
5351
Sanjoy Dasf8570812016-05-29 00:38:22 +00005352/// Returns the largest constant divisor of the trip count of this loop as a
5353/// normal unsigned value, if possible. This means that the actual trip count is
5354/// always a multiple of the returned value (don't forget the trip count could
5355/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005356///
5357/// Returns 1 if the trip count is unknown or not guaranteed to be the
5358/// multiple of a constant (which is also the case if the trip count is simply
5359/// constant, use getSmallConstantTripCount for that case), Will also return 1
5360/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005361///
5362/// As explained in the comments for getSmallConstantTripCount, this assumes
5363/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005364unsigned
5365ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5366 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005367 assert(ExitingBlock && "Must pass a non-null exiting block!");
5368 assert(L->isLoopExiting(ExitingBlock) &&
5369 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005370 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005371 if (ExitCount == getCouldNotCompute())
5372 return 1;
5373
5374 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005375 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005376 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5377 // to factor simple cases.
5378 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5379 TCMul = Mul->getOperand(0);
5380
5381 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5382 if (!MulC)
5383 return 1;
5384
5385 ConstantInt *Result = MulC->getValue();
5386
Hal Finkel30bd9342012-10-24 19:46:44 +00005387 // Guard against huge trip counts (this requires checking
5388 // for zero to handle the case where the trip count == -1 and the
5389 // addition wraps).
5390 if (!Result || Result->getValue().getActiveBits() > 32 ||
5391 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005392 return 1;
5393
5394 return (unsigned)Result->getZExtValue();
5395}
5396
Sanjoy Dasf8570812016-05-29 00:38:22 +00005397/// Get the expression for the number of loop iterations for which this loop is
5398/// guaranteed not to exit via ExitingBlock. Otherwise return
5399/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005400const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5401 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005402}
5403
Silviu Baranga6f444df2016-04-08 14:29:09 +00005404const SCEV *
5405ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5406 SCEVUnionPredicate &Preds) {
5407 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5408}
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
Sanjoy Dasf8570812016-05-29 00:38:22 +00005414/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5415/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005416const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005417 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005418}
5419
Sanjoy Dasf8570812016-05-29 00:38:22 +00005420/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005421static void
5422PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5423 BasicBlock *Header = L->getHeader();
5424
5425 // Push all Loop-header PHIs onto the Worklist stack.
5426 for (BasicBlock::iterator I = Header->begin();
5427 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5428 Worklist.push_back(PN);
5429}
5430
Dan Gohman2b8da352009-04-30 20:47:05 +00005431const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005432ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5433 auto &BTI = getBackedgeTakenInfo(L);
5434 if (BTI.hasFullInfo())
5435 return BTI;
5436
5437 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5438
5439 if (!Pair.second)
5440 return Pair.first->second;
5441
5442 BackedgeTakenInfo Result =
5443 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5444
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005445 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005446}
5447
5448const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005449ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005450 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005451 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005452 // update the value. The temporary CouldNotCompute value tells SCEV
5453 // code elsewhere that it shouldn't attempt to request a new
5454 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005455 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005456 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005457 if (!Pair.second)
5458 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005459
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005460 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005461 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5462 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005463 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005464
5465 if (Result.getExact(this) != getCouldNotCompute()) {
5466 assert(isLoopInvariant(Result.getExact(this), L) &&
5467 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005468 "Computed backedge-taken count isn't loop invariant for loop!");
5469 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005470 }
5471 else if (Result.getMax(this) == getCouldNotCompute() &&
5472 isa<PHINode>(L->getHeader()->begin())) {
5473 // Only count loops that have phi nodes as not being computable.
5474 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005475 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005476
Chris Lattnera337f5e2011-01-09 02:16:18 +00005477 // Now that we know more about the trip count for this loop, forget any
5478 // existing SCEV values for PHI nodes in this loop since they are only
5479 // conservative estimates made without the benefit of trip count
5480 // information. This is similar to the code in forgetLoop, except that
5481 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005482 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005483 SmallVector<Instruction *, 16> Worklist;
5484 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005485
Chris Lattnera337f5e2011-01-09 02:16:18 +00005486 SmallPtrSet<Instruction *, 8> Visited;
5487 while (!Worklist.empty()) {
5488 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005489 if (!Visited.insert(I).second)
5490 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005491
Chris Lattnera337f5e2011-01-09 02:16:18 +00005492 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005493 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005494 if (It != ValueExprMap.end()) {
5495 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005496
Chris Lattnera337f5e2011-01-09 02:16:18 +00005497 // SCEVUnknown for a PHI either means that it has an unrecognized
5498 // structure, or it's a PHI that's in the progress of being computed
5499 // by createNodeForPHI. In the former case, additional loop trip
5500 // count information isn't going to change anything. In the later
5501 // case, createNodeForPHI will perform the necessary updates on its
5502 // own when it gets to that point.
5503 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005504 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005505 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005506 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005507 if (PHINode *PN = dyn_cast<PHINode>(I))
5508 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005509 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005510
5511 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005512 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005513 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005514
5515 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005516 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005517 // recusive call to getBackedgeTakenInfo (on a different
5518 // loop), which would invalidate the iterator computed
5519 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005520 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005521}
5522
Dan Gohman880c92a2009-10-31 15:04:55 +00005523void ScalarEvolution::forgetLoop(const Loop *L) {
5524 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005525 auto RemoveLoopFromBackedgeMap =
5526 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5527 auto BTCPos = Map.find(L);
5528 if (BTCPos != Map.end()) {
5529 BTCPos->second.clear();
5530 Map.erase(BTCPos);
5531 }
5532 };
5533
5534 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5535 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005536
Dan Gohman880c92a2009-10-31 15:04:55 +00005537 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005538 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005539 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005540
Dan Gohmandc191042009-07-08 19:23:34 +00005541 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005542 while (!Worklist.empty()) {
5543 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005544 if (!Visited.insert(I).second)
5545 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005546
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005547 ValueExprMapType::iterator It =
5548 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005549 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005550 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005551 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005552 if (PHINode *PN = dyn_cast<PHINode>(I))
5553 ConstantEvolutionLoopExitValue.erase(PN);
5554 }
5555
5556 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005557 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005558
5559 // Forget all contained loops too, to avoid dangling entries in the
5560 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005561 for (Loop *I : *L)
5562 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005563
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005564 LoopHasNoAbnormalExits.erase(L);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005565 LoopHasNoSideEffects.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005566}
5567
Eric Christopheref6d5932010-07-29 01:25:38 +00005568void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005569 Instruction *I = dyn_cast<Instruction>(V);
5570 if (!I) return;
5571
5572 // Drop information about expressions based on loop-header PHIs.
5573 SmallVector<Instruction *, 16> Worklist;
5574 Worklist.push_back(I);
5575
5576 SmallPtrSet<Instruction *, 8> Visited;
5577 while (!Worklist.empty()) {
5578 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005579 if (!Visited.insert(I).second)
5580 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005581
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005582 ValueExprMapType::iterator It =
5583 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005584 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005585 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005586 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005587 if (PHINode *PN = dyn_cast<PHINode>(I))
5588 ConstantEvolutionLoopExitValue.erase(PN);
5589 }
5590
5591 PushDefUseChildren(I, Worklist);
5592 }
5593}
5594
Sanjoy Dasf8570812016-05-29 00:38:22 +00005595/// Get the exact loop backedge taken count considering all loop exits. A
5596/// computable result can only be returned for loops with a single exit.
5597/// Returning the minimum taken count among all exits is incorrect because one
5598/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5599/// the limit of each loop test is never skipped. This is a valid assumption as
5600/// long as the loop exits via that test. For precise results, it is the
5601/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005602/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005603const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005604ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5605 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005606 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005607 if (!isComplete() || ExitNotTaken.empty())
5608 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005609
Craig Topper9f008862014-04-15 04:59:12 +00005610 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005611 for (auto &ENT : ExitNotTaken) {
5612 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005613
5614 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005615 BECount = ENT.ExactNotTaken;
5616 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005617 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005618 if (Preds && !ENT.hasAlwaysTruePredicate())
5619 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005620
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005621 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005622 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005623 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005624
Andrew Trickbbb226a2011-09-02 21:20:46 +00005625 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005626 return BECount;
5627}
5628
Sanjoy Dasf8570812016-05-29 00:38:22 +00005629/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005630const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005631ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005632 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005633 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005634 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005635 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005636
Andrew Trick3ca3f982011-07-26 17:19:55 +00005637 return SE->getCouldNotCompute();
5638}
5639
5640/// getMax - Get the max backedge taken count for the loop.
5641const SCEV *
5642ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005643 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5644 return !ENT.hasAlwaysTruePredicate();
5645 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005646
Sanjoy Das73268612016-09-26 01:10:22 +00005647 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5648 return SE->getCouldNotCompute();
5649
5650 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005651}
5652
Andrew Trick9093e152013-03-26 03:14:53 +00005653bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5654 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005655 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5656 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005657 return true;
5658
Silviu Baranga6f444df2016-04-08 14:29:09 +00005659 for (auto &ENT : ExitNotTaken)
5660 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5661 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005662 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005663
Andrew Trick9093e152013-03-26 03:14:53 +00005664 return false;
5665}
5666
Andrew Trick3ca3f982011-07-26 17:19:55 +00005667/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5668/// computable exit into a persistent ExitNotTakenInfo array.
5669ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005670 ArrayRef<ScalarEvolution::EdgeExitInfo> ExitCounts, bool Complete,
5671 const SCEV *MaxCount)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005672 : MaxAndComplete(MaxCount, Complete) {
Sanjoy Dase935c772016-09-25 23:12:08 +00005673 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005674 std::transform(
5675 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5676 [&](const ScalarEvolution::EdgeExitInfo &EEI) {
5677 BasicBlock *ExitBB = EEI.first;
5678 const ExitLimit &EL = EEI.second;
5679 if (EL.Predicate.isAlwaysTrue())
5680 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5681 return ExitNotTakenInfo(
5682 ExitBB, EL.ExactNotTaken,
5683 llvm::make_unique<SCEVUnionPredicate>(std::move(EL.Predicate)));
5684 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005685}
5686
Sanjoy Dasf8570812016-05-29 00:38:22 +00005687/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005688void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005689 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005690}
5691
Sanjoy Dasf8570812016-05-29 00:38:22 +00005692/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005693ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005694ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5695 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005696 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005697 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005698
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005699 SmallVector<ScalarEvolution::EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005700 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005701 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005702 const SCEV *MustExitMaxBECount = nullptr;
5703 const SCEV *MayExitMaxBECount = nullptr;
5704
5705 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5706 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005707 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005708 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005709 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005710 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5711
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005712 assert((AllowPredicates || EL.Predicate.isAlwaysTrue()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005713 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005714
5715 // 1. For each exit that can be computed, add an entry to ExitCounts.
5716 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005717 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005718 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005719 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005720 CouldComputeBECount = false;
5721 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005722 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005723
Andrew Trick839e30b2014-05-23 19:47:13 +00005724 // 2. Derive the loop's MaxBECount from each exit's max number of
5725 // non-exiting iterations. Partition the loop exits into two kinds:
5726 // LoopMustExits and LoopMayExits.
5727 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005728 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5729 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005730 // MaxBECount is the minimum EL.MaxNotTaken of computable
5731 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5732 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5733 // computable EL.MaxNotTaken.
5734 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005735 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005736 if (!MustExitMaxBECount)
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005737 MustExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005738 else {
5739 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005740 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005741 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005742 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005743 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5744 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005745 else {
5746 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005747 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005748 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005749 }
Dan Gohman96212b62009-06-22 00:31:57 +00005750 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005751 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5752 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005753 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005754}
5755
Andrew Trick3ca3f982011-07-26 17:19:55 +00005756ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005757ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5758 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005759
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005760 // Okay, we've chosen an exiting block. See what condition causes us to exit
5761 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005762 // lead to the loop header.
5763 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005764 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005765 for (auto *SBB : successors(ExitingBlock))
5766 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005767 if (Exit) // Multiple exit successors.
5768 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005769 Exit = SBB;
5770 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005771 MustExecuteLoopHeader = false;
5772 }
Dan Gohmance973df2009-06-24 04:48:43 +00005773
Chris Lattner18954852007-01-07 02:24:26 +00005774 // At this point, we know we have a conditional branch that determines whether
5775 // the loop is exited. However, we don't know if the branch is executed each
5776 // time through the loop. If not, then the execution count of the branch will
5777 // not be equal to the trip count of the loop.
5778 //
5779 // Currently we check for this by checking to see if the Exit branch goes to
5780 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005781 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005782 // loop header. This is common for un-rotated loops.
5783 //
5784 // If both of those tests fail, walk up the unique predecessor chain to the
5785 // header, stopping if there is an edge that doesn't exit the loop. If the
5786 // header is reached, the execution count of the branch will be equal to the
5787 // trip count of the loop.
5788 //
5789 // More extensive analysis could be done to handle more cases here.
5790 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005791 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005792 // The simple checks failed, try climbing the unique predecessor chain
5793 // up to the header.
5794 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005795 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005796 BasicBlock *Pred = BB->getUniquePredecessor();
5797 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005798 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005799 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005800 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005801 if (PredSucc == BB)
5802 continue;
5803 // If the predecessor has a successor that isn't BB and isn't
5804 // outside the loop, assume the worst.
5805 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005806 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005807 }
5808 if (Pred == L->getHeader()) {
5809 Ok = true;
5810 break;
5811 }
5812 BB = Pred;
5813 }
5814 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005815 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005816 }
5817
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005818 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005819 TerminatorInst *Term = ExitingBlock->getTerminator();
5820 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5821 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5822 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005823 return computeExitLimitFromCond(
5824 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5825 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005826 }
5827
5828 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005829 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005830 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005831
5832 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005833}
5834
Andrew Trick3ca3f982011-07-26 17:19:55 +00005835ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005836ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005837 Value *ExitCond,
5838 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005839 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005840 bool ControlsExit,
5841 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005842 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005843 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5844 if (BO->getOpcode() == Instruction::And) {
5845 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005846 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005847 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005848 ControlsExit && !EitherMayExit,
5849 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005850 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005851 ControlsExit && !EitherMayExit,
5852 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005853 const SCEV *BECount = getCouldNotCompute();
5854 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005855 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005856 // Both conditions must be true for the loop to continue executing.
5857 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005858 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5859 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005860 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005861 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005862 BECount =
5863 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5864 if (EL0.MaxNotTaken == getCouldNotCompute())
5865 MaxBECount = EL1.MaxNotTaken;
5866 else if (EL1.MaxNotTaken == getCouldNotCompute())
5867 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005868 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005869 MaxBECount =
5870 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005871 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005872 // Both conditions must be true at the same time for the loop to exit.
5873 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005874 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005875 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5876 MaxBECount = EL0.MaxNotTaken;
5877 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5878 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005879 }
5880
Silviu Baranga6f444df2016-04-08 14:29:09 +00005881 SCEVUnionPredicate NP;
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005882 NP.add(&EL0.Predicate);
5883 NP.add(&EL1.Predicate);
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005884 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5885 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005886 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
5887 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5888 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005889 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5890 !isa<SCEVCouldNotCompute>(BECount))
5891 MaxBECount = BECount;
5892
Silviu Baranga6f444df2016-04-08 14:29:09 +00005893 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005894 }
5895 if (BO->getOpcode() == Instruction::Or) {
5896 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005897 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005898 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005899 ControlsExit && !EitherMayExit,
5900 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005901 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005902 ControlsExit && !EitherMayExit,
5903 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005904 const SCEV *BECount = getCouldNotCompute();
5905 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005906 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005907 // Both conditions must be false for the loop to continue executing.
5908 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005909 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5910 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005911 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005912 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005913 BECount =
5914 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5915 if (EL0.MaxNotTaken == getCouldNotCompute())
5916 MaxBECount = EL1.MaxNotTaken;
5917 else if (EL1.MaxNotTaken == getCouldNotCompute())
5918 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005919 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005920 MaxBECount =
5921 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005922 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005923 // Both conditions must be false 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(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005926 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5927 MaxBECount = EL0.MaxNotTaken;
5928 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5929 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005930 }
5931
Silviu Baranga6f444df2016-04-08 14:29:09 +00005932 SCEVUnionPredicate NP;
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005933 NP.add(&EL0.Predicate);
5934 NP.add(&EL1.Predicate);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005935 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005936 }
5937 }
5938
5939 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005940 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005941 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5942 ExitLimit EL =
5943 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5944 if (EL.hasFullInfo() || !AllowPredicates)
5945 return EL;
5946
5947 // Try again, but use SCEV predicates this time.
5948 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5949 /*AllowPredicates=*/true);
5950 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005951
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005952 // Check for a constant condition. These are normally stripped out by
5953 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5954 // preserve the CFG and is temporarily leaving constant conditions
5955 // in place.
5956 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5957 if (L->contains(FBB) == !CI->getZExtValue())
5958 // The backedge is always taken.
5959 return getCouldNotCompute();
5960 else
5961 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005962 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005963 }
5964
Eli Friedmanebf98b02009-05-09 12:32:42 +00005965 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005966 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005967}
5968
Andrew Trick3ca3f982011-07-26 17:19:55 +00005969ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005970ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005971 ICmpInst *ExitCond,
5972 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005973 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005974 bool ControlsExit,
5975 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005976
Reid Spencer266e42b2006-12-23 06:05:41 +00005977 // If the condition was exit on true, convert the condition to exit on false
5978 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005979 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005980 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005981 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005982 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005983
5984 // Handle common loops like: for (X = "string"; *X; ++X)
5985 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5986 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005987 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005988 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005989 if (ItCnt.hasAnyInfo())
5990 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005991 }
5992
Dan Gohmanaf752342009-07-07 17:06:11 +00005993 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5994 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005995
5996 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005997 LHS = getSCEVAtScope(LHS, L);
5998 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005999
Dan Gohmance973df2009-06-24 04:48:43 +00006000 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006001 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006002 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006003 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006004 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006005 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006006 }
6007
Dan Gohman81585c12010-05-03 16:35:17 +00006008 // Simplify the operands before analyzing them.
6009 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6010
Chris Lattnerd934c702004-04-02 20:23:17 +00006011 // If we have a comparison of a chrec against a constant, try to use value
6012 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006013 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6014 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006015 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006016 // Form the constant range.
6017 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006018 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00006019
Dan Gohmanaf752342009-07-07 17:06:11 +00006020 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006021 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006022 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006023
Chris Lattnerd934c702004-04-02 20:23:17 +00006024 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006025 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006026 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006027 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006028 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006029 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006030 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006031 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006032 case ICmpInst::ICMP_EQ: { // while (X == Y)
6033 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006034 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006035 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006036 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006037 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006038 case ICmpInst::ICMP_SLT:
6039 case ICmpInst::ICMP_ULT: { // while (X < Y)
6040 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006041 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006042 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006043 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006044 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006045 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006046 case ICmpInst::ICMP_SGT:
6047 case ICmpInst::ICMP_UGT: { // while (X > Y)
6048 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006049 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006050 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006051 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006052 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006053 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006054 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006055 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006056 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006057 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006058
6059 auto *ExhaustiveCount =
6060 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6061
6062 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6063 return ExhaustiveCount;
6064
6065 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6066 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006067}
6068
Benjamin Kramer5a188542014-02-11 15:44:32 +00006069ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006070ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006071 SwitchInst *Switch,
6072 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006073 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006074 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6075
6076 // Give up if the exit is the default dest of a switch.
6077 if (Switch->getDefaultDest() == ExitingBlock)
6078 return getCouldNotCompute();
6079
6080 assert(L->contains(Switch->getDefaultDest()) &&
6081 "Default case must not exit the loop!");
6082 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6083 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6084
6085 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006086 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006087 if (EL.hasAnyInfo())
6088 return EL;
6089
6090 return getCouldNotCompute();
6091}
6092
Chris Lattnerec901cc2004-10-12 01:49:27 +00006093static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006094EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6095 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006096 const SCEV *InVal = SE.getConstant(C);
6097 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006098 assert(isa<SCEVConstant>(Val) &&
6099 "Evaluation of SCEV at constant didn't fold correctly?");
6100 return cast<SCEVConstant>(Val)->getValue();
6101}
6102
Sanjoy Dasf8570812016-05-29 00:38:22 +00006103/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6104/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006105ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006106ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006107 LoadInst *LI,
6108 Constant *RHS,
6109 const Loop *L,
6110 ICmpInst::Predicate predicate) {
6111
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006112 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006113
6114 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006115 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006116 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006117 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006118
6119 // Make sure that it is really a constant global we are gepping, with an
6120 // initializer, and make sure the first IDX is really 0.
6121 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006122 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006123 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6124 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006125 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006126
6127 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006128 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006129 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006130 unsigned VarIdxNum = 0;
6131 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6132 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6133 Indexes.push_back(CI);
6134 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006135 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006136 VarIdx = GEP->getOperand(i);
6137 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006138 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006139 }
6140
Andrew Trick7004e4b2012-03-26 22:33:59 +00006141 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6142 if (!VarIdx)
6143 return getCouldNotCompute();
6144
Chris Lattnerec901cc2004-10-12 01:49:27 +00006145 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6146 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006147 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006148 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006149
6150 // We can only recognize very limited forms of loop index expressions, in
6151 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006152 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006153 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006154 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6155 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006156 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006157
6158 unsigned MaxSteps = MaxBruteForceIterations;
6159 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006160 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006161 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006162 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006163
6164 // Form the GEP offset.
6165 Indexes[VarIdxNum] = Val;
6166
Chris Lattnere166a852012-01-24 05:49:24 +00006167 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6168 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006169 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006170
6171 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006172 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006173 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006174 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006175 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006176 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006177 }
6178 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006179 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006180}
6181
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006182ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6183 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6184 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6185 if (!RHS)
6186 return getCouldNotCompute();
6187
6188 const BasicBlock *Latch = L->getLoopLatch();
6189 if (!Latch)
6190 return getCouldNotCompute();
6191
6192 const BasicBlock *Predecessor = L->getLoopPredecessor();
6193 if (!Predecessor)
6194 return getCouldNotCompute();
6195
6196 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6197 // Return LHS in OutLHS and shift_opt in OutOpCode.
6198 auto MatchPositiveShift =
6199 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6200
6201 using namespace PatternMatch;
6202
6203 ConstantInt *ShiftAmt;
6204 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6205 OutOpCode = Instruction::LShr;
6206 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6207 OutOpCode = Instruction::AShr;
6208 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6209 OutOpCode = Instruction::Shl;
6210 else
6211 return false;
6212
6213 return ShiftAmt->getValue().isStrictlyPositive();
6214 };
6215
6216 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6217 //
6218 // loop:
6219 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6220 // %iv.shifted = lshr i32 %iv, <positive constant>
6221 //
6222 // Return true on a succesful match. Return the corresponding PHI node (%iv
6223 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6224 auto MatchShiftRecurrence =
6225 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6226 Optional<Instruction::BinaryOps> PostShiftOpCode;
6227
6228 {
6229 Instruction::BinaryOps OpC;
6230 Value *V;
6231
6232 // If we encounter a shift instruction, "peel off" the shift operation,
6233 // and remember that we did so. Later when we inspect %iv's backedge
6234 // value, we will make sure that the backedge value uses the same
6235 // operation.
6236 //
6237 // Note: the peeled shift operation does not have to be the same
6238 // instruction as the one feeding into the PHI's backedge value. We only
6239 // really care about it being the same *kind* of shift instruction --
6240 // that's all that is required for our later inferences to hold.
6241 if (MatchPositiveShift(LHS, V, OpC)) {
6242 PostShiftOpCode = OpC;
6243 LHS = V;
6244 }
6245 }
6246
6247 PNOut = dyn_cast<PHINode>(LHS);
6248 if (!PNOut || PNOut->getParent() != L->getHeader())
6249 return false;
6250
6251 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6252 Value *OpLHS;
6253
6254 return
6255 // The backedge value for the PHI node must be a shift by a positive
6256 // amount
6257 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6258
6259 // of the PHI node itself
6260 OpLHS == PNOut &&
6261
6262 // and the kind of shift should be match the kind of shift we peeled
6263 // off, if any.
6264 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6265 };
6266
6267 PHINode *PN;
6268 Instruction::BinaryOps OpCode;
6269 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6270 return getCouldNotCompute();
6271
6272 const DataLayout &DL = getDataLayout();
6273
6274 // The key rationale for this optimization is that for some kinds of shift
6275 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6276 // within a finite number of iterations. If the condition guarding the
6277 // backedge (in the sense that the backedge is taken if the condition is true)
6278 // is false for the value the shift recurrence stabilizes to, then we know
6279 // that the backedge is taken only a finite number of times.
6280
6281 ConstantInt *StableValue = nullptr;
6282 switch (OpCode) {
6283 default:
6284 llvm_unreachable("Impossible case!");
6285
6286 case Instruction::AShr: {
6287 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6288 // bitwidth(K) iterations.
6289 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6290 bool KnownZero, KnownOne;
6291 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6292 Predecessor->getTerminator(), &DT);
6293 auto *Ty = cast<IntegerType>(RHS->getType());
6294 if (KnownZero)
6295 StableValue = ConstantInt::get(Ty, 0);
6296 else if (KnownOne)
6297 StableValue = ConstantInt::get(Ty, -1, true);
6298 else
6299 return getCouldNotCompute();
6300
6301 break;
6302 }
6303 case Instruction::LShr:
6304 case Instruction::Shl:
6305 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6306 // stabilize to 0 in at most bitwidth(K) iterations.
6307 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6308 break;
6309 }
6310
6311 auto *Result =
6312 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6313 assert(Result->getType()->isIntegerTy(1) &&
6314 "Otherwise cannot be an operand to a branch instruction");
6315
6316 if (Result->isZeroValue()) {
6317 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6318 const SCEV *UpperBound =
6319 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
Silviu Baranga6f444df2016-04-08 14:29:09 +00006320 SCEVUnionPredicate P;
6321 return ExitLimit(getCouldNotCompute(), UpperBound, P);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006322 }
6323
6324 return getCouldNotCompute();
6325}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006326
Sanjoy Dasf8570812016-05-29 00:38:22 +00006327/// Return true if we can constant fold an instruction of the specified type,
6328/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006329static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006330 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006331 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6332 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006333 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006334
Chris Lattnerdd730472004-04-17 22:58:41 +00006335 if (const CallInst *CI = dyn_cast<CallInst>(I))
6336 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006337 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006338 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006339}
6340
Andrew Trick3a86ba72011-10-05 03:25:31 +00006341/// Determine whether this instruction can constant evolve within this loop
6342/// assuming its operands can all constant evolve.
6343static bool canConstantEvolve(Instruction *I, const Loop *L) {
6344 // An instruction outside of the loop can't be derived from a loop PHI.
6345 if (!L->contains(I)) return false;
6346
6347 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006348 // We don't currently keep track of the control flow needed to evaluate
6349 // PHIs, so we cannot handle PHIs inside of loops.
6350 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006351 }
6352
6353 // If we won't be able to constant fold this expression even if the operands
6354 // are constants, bail early.
6355 return CanConstantFold(I);
6356}
6357
6358/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6359/// recursing through each instruction operand until reaching a loop header phi.
6360static PHINode *
6361getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006362 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006363
6364 // Otherwise, we can evaluate this instruction if all of its operands are
6365 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006366 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006367 for (Value *Op : UseInst->operands()) {
6368 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006369
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006370 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006371 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006372
6373 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006374 if (!P)
6375 // If this operand is already visited, reuse the prior result.
6376 // We may have P != PHI if this is the deepest point at which the
6377 // inconsistent paths meet.
6378 P = PHIMap.lookup(OpInst);
6379 if (!P) {
6380 // Recurse and memoize the results, whether a phi is found or not.
6381 // This recursive call invalidates pointers into PHIMap.
6382 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6383 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006384 }
Craig Topper9f008862014-04-15 04:59:12 +00006385 if (!P)
6386 return nullptr; // Not evolving from PHI
6387 if (PHI && PHI != P)
6388 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006389 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006390 }
6391 // This is a expression evolving from a constant PHI!
6392 return PHI;
6393}
6394
Chris Lattnerdd730472004-04-17 22:58:41 +00006395/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6396/// in the loop that V is derived from. We allow arbitrary operations along the
6397/// way, but the operands of an operation must either be constants or a value
6398/// derived from a constant PHI. If this expression does not fit with these
6399/// constraints, return null.
6400static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006401 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006402 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006403
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006404 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006405 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006406
Andrew Trick3a86ba72011-10-05 03:25:31 +00006407 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006408 DenseMap<Instruction *, PHINode *> PHIMap;
6409 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006410}
6411
6412/// EvaluateExpression - Given an expression that passes the
6413/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6414/// in the loop has the value PHIVal. If we can't fold this expression for some
6415/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006416static Constant *EvaluateExpression(Value *V, const Loop *L,
6417 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006418 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006419 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006420 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006421 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006422 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006423 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006424
Andrew Trick3a86ba72011-10-05 03:25:31 +00006425 if (Constant *C = Vals.lookup(I)) return C;
6426
Nick Lewyckya6674c72011-10-22 19:58:20 +00006427 // An instruction inside the loop depends on a value outside the loop that we
6428 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006429 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006430
6431 // An unmapped PHI can be due to a branch or another loop inside this loop,
6432 // or due to this not being the initial iteration through a loop where we
6433 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006434 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006435
Dan Gohmanf820bd32010-06-22 13:15:46 +00006436 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006437
6438 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006439 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6440 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006441 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006442 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006443 continue;
6444 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006445 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006446 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006447 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006448 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006449 }
6450
Nick Lewyckya6674c72011-10-22 19:58:20 +00006451 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006452 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006453 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006454 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6455 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006456 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006457 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006458 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006459}
6460
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006461
6462// If every incoming value to PN except the one for BB is a specific Constant,
6463// return that, else return nullptr.
6464static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6465 Constant *IncomingVal = nullptr;
6466
6467 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6468 if (PN->getIncomingBlock(i) == BB)
6469 continue;
6470
6471 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6472 if (!CurrentVal)
6473 return nullptr;
6474
6475 if (IncomingVal != CurrentVal) {
6476 if (IncomingVal)
6477 return nullptr;
6478 IncomingVal = CurrentVal;
6479 }
6480 }
6481
6482 return IncomingVal;
6483}
6484
Chris Lattnerdd730472004-04-17 22:58:41 +00006485/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6486/// in the header of its containing loop, we know the loop executes a
6487/// constant number of times, and the PHI node is just a recurrence
6488/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006489Constant *
6490ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006491 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006492 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006493 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006494 if (I != ConstantEvolutionLoopExitValue.end())
6495 return I->second;
6496
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006497 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006498 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006499
6500 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6501
Andrew Trick3a86ba72011-10-05 03:25:31 +00006502 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006503 BasicBlock *Header = L->getHeader();
6504 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006505
Sanjoy Dasdd709962015-10-08 18:28:36 +00006506 BasicBlock *Latch = L->getLoopLatch();
6507 if (!Latch)
6508 return nullptr;
6509
Sanjoy Das4493b402015-10-07 17:38:25 +00006510 for (auto &I : *Header) {
6511 PHINode *PHI = dyn_cast<PHINode>(&I);
6512 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006513 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006514 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006515 CurrentIterVals[PHI] = StartCST;
6516 }
6517 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006518 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006519
Sanjoy Dasdd709962015-10-08 18:28:36 +00006520 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006521
6522 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006523 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006524 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006525
Dan Gohman0bddac12009-02-24 18:55:53 +00006526 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006527 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006528 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006529 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006530 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006531 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006532
Nick Lewyckya6674c72011-10-22 19:58:20 +00006533 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006534 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006535 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006536 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006537 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006538 if (!NextPHI)
6539 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006540 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006541
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006542 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6543
Nick Lewyckya6674c72011-10-22 19:58:20 +00006544 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6545 // cease to be able to evaluate one of them or if they stop evolving,
6546 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006547 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006548 for (const auto &I : CurrentIterVals) {
6549 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006550 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006551 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006552 }
6553 // We use two distinct loops because EvaluateExpression may invalidate any
6554 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006555 for (const auto &I : PHIsToCompute) {
6556 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006557 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006558 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006559 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006560 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006561 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006562 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006563 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006564 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006565
6566 // If all entries in CurrentIterVals == NextIterVals then we can stop
6567 // iterating, the loop can't continue to change.
6568 if (StoppedEvolving)
6569 return RetVal = CurrentIterVals[PN];
6570
Andrew Trick3a86ba72011-10-05 03:25:31 +00006571 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006572 }
6573}
6574
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006575const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006576 Value *Cond,
6577 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006578 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006579 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006580
Dan Gohman866971e2010-06-19 14:17:24 +00006581 // If the loop is canonicalized, the PHI will have exactly two entries.
6582 // That's the only form we support here.
6583 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6584
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006585 DenseMap<Instruction *, Constant *> CurrentIterVals;
6586 BasicBlock *Header = L->getHeader();
6587 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6588
Sanjoy Dasdd709962015-10-08 18:28:36 +00006589 BasicBlock *Latch = L->getLoopLatch();
6590 assert(Latch && "Should follow from NumIncomingValues == 2!");
6591
Sanjoy Das4493b402015-10-07 17:38:25 +00006592 for (auto &I : *Header) {
6593 PHINode *PHI = dyn_cast<PHINode>(&I);
6594 if (!PHI)
6595 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006596 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006597 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006598 CurrentIterVals[PHI] = StartCST;
6599 }
6600 if (!CurrentIterVals.count(PN))
6601 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006602
6603 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6604 // the loop symbolically to determine when the condition gets a value of
6605 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006606 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006607 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006608 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006609 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006610 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006611
Zhou Sheng75b871f2007-01-11 12:24:14 +00006612 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006613 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006614
Reid Spencer983e3b32007-03-01 07:25:48 +00006615 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006616 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006617 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006618 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006619
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006620 // Update all the PHI nodes for the next iteration.
6621 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006622
6623 // Create a list of which PHIs we need to compute. We want to do this before
6624 // calling EvaluateExpression on them because that may invalidate iterators
6625 // into CurrentIterVals.
6626 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006627 for (const auto &I : CurrentIterVals) {
6628 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006629 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006630 PHIsToCompute.push_back(PHI);
6631 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006632 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006633 Constant *&NextPHI = NextIterVals[PHI];
6634 if (NextPHI) continue; // Already computed!
6635
Sanjoy Dasdd709962015-10-08 18:28:36 +00006636 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006637 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006638 }
6639 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006640 }
6641
6642 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006643 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006644}
6645
Dan Gohmanaf752342009-07-07 17:06:11 +00006646const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006647 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6648 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006649 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006650 for (auto &LS : Values)
6651 if (LS.first == L)
6652 return LS.second ? LS.second : V;
6653
6654 Values.emplace_back(L, nullptr);
6655
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006656 // Otherwise compute it.
6657 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006658 for (auto &LS : reverse(ValuesAtScopes[V]))
6659 if (LS.first == L) {
6660 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006661 break;
6662 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006663 return C;
6664}
6665
Nick Lewyckya6674c72011-10-22 19:58:20 +00006666/// This builds up a Constant using the ConstantExpr interface. That way, we
6667/// will return Constants for objects which aren't represented by a
6668/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6669/// Returns NULL if the SCEV isn't representable as a Constant.
6670static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006671 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006672 case scCouldNotCompute:
6673 case scAddRecExpr:
6674 break;
6675 case scConstant:
6676 return cast<SCEVConstant>(V)->getValue();
6677 case scUnknown:
6678 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6679 case scSignExtend: {
6680 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6681 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6682 return ConstantExpr::getSExt(CastOp, SS->getType());
6683 break;
6684 }
6685 case scZeroExtend: {
6686 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6687 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6688 return ConstantExpr::getZExt(CastOp, SZ->getType());
6689 break;
6690 }
6691 case scTruncate: {
6692 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6693 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6694 return ConstantExpr::getTrunc(CastOp, ST->getType());
6695 break;
6696 }
6697 case scAddExpr: {
6698 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6699 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006700 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6701 unsigned AS = PTy->getAddressSpace();
6702 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6703 C = ConstantExpr::getBitCast(C, DestPtrTy);
6704 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006705 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6706 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006707 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006708
6709 // First pointer!
6710 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006711 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006712 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006713 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006714 // The offsets have been converted to bytes. We can add bytes to an
6715 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006716 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006717 }
6718
6719 // Don't bother trying to sum two pointers. We probably can't
6720 // statically compute a load that results from it anyway.
6721 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006722 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006723
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006724 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6725 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006726 C2 = ConstantExpr::getIntegerCast(
6727 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006728 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006729 } else
6730 C = ConstantExpr::getAdd(C, C2);
6731 }
6732 return C;
6733 }
6734 break;
6735 }
6736 case scMulExpr: {
6737 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6738 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6739 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006740 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006741 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6742 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006743 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006744 C = ConstantExpr::getMul(C, C2);
6745 }
6746 return C;
6747 }
6748 break;
6749 }
6750 case scUDivExpr: {
6751 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6752 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6753 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6754 if (LHS->getType() == RHS->getType())
6755 return ConstantExpr::getUDiv(LHS, RHS);
6756 break;
6757 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006758 case scSMaxExpr:
6759 case scUMaxExpr:
6760 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006761 }
Craig Topper9f008862014-04-15 04:59:12 +00006762 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006763}
6764
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006765const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006766 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006767
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006768 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006769 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006770 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006771 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006772 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006773 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6774 if (PHINode *PN = dyn_cast<PHINode>(I))
6775 if (PN->getParent() == LI->getHeader()) {
6776 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006777 // to see if the loop that contains it has a known backedge-taken
6778 // count. If so, we may be able to force computation of the exit
6779 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006780 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006781 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006782 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006783 // Okay, we know how many times the containing loop executes. If
6784 // this is a constant evolving PHI node, get the final value at
6785 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006786 Constant *RV =
6787 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006788 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006789 }
6790 }
6791
Reid Spencere6328ca2006-12-04 21:33:23 +00006792 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006793 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006794 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006795 // result. This is particularly useful for computing loop exit values.
6796 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006797 SmallVector<Constant *, 4> Operands;
6798 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006799 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006800 if (Constant *C = dyn_cast<Constant>(Op)) {
6801 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006802 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006803 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006804
6805 // If any of the operands is non-constant and if they are
6806 // non-integer and non-pointer, don't even try to analyze them
6807 // with scev techniques.
6808 if (!isSCEVable(Op->getType()))
6809 return V;
6810
6811 const SCEV *OrigV = getSCEV(Op);
6812 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6813 MadeImprovement |= OrigV != OpV;
6814
Nick Lewyckya6674c72011-10-22 19:58:20 +00006815 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006816 if (!C) return V;
6817 if (C->getType() != Op->getType())
6818 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6819 Op->getType(),
6820 false),
6821 C, Op->getType());
6822 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006823 }
Dan Gohmance973df2009-06-24 04:48:43 +00006824
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006825 // Check to see if getSCEVAtScope actually made an improvement.
6826 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006827 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006828 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006829 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006830 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006831 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006832 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6833 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006834 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006835 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006836 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006837 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006838 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006839 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006840 }
6841 }
6842
6843 // This is some other type of SCEVUnknown, just return it.
6844 return V;
6845 }
6846
Dan Gohmana30370b2009-05-04 22:02:23 +00006847 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006848 // Avoid performing the look-up in the common case where the specified
6849 // expression has no loop-variant portions.
6850 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006851 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006852 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006853 // Okay, at least one of these operands is loop variant but might be
6854 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006855 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6856 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006857 NewOps.push_back(OpAtScope);
6858
6859 for (++i; i != e; ++i) {
6860 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006861 NewOps.push_back(OpAtScope);
6862 }
6863 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006864 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006865 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006866 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006867 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006868 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006869 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006870 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006871 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006872 }
6873 }
6874 // If we got here, all operands are loop invariant.
6875 return Comm;
6876 }
6877
Dan Gohmana30370b2009-05-04 22:02:23 +00006878 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006879 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6880 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006881 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6882 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006883 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006884 }
6885
6886 // If this is a loop recurrence for a loop that does not contain L, then we
6887 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006888 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006889 // First, attempt to evaluate each operand.
6890 // Avoid performing the look-up in the common case where the specified
6891 // expression has no loop-variant portions.
6892 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6893 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6894 if (OpAtScope == AddRec->getOperand(i))
6895 continue;
6896
6897 // Okay, at least one of these operands is loop variant but might be
6898 // foldable. Build a new instance of the folded commutative expression.
6899 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6900 AddRec->op_begin()+i);
6901 NewOps.push_back(OpAtScope);
6902 for (++i; i != e; ++i)
6903 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6904
Andrew Trick759ba082011-04-27 01:21:25 +00006905 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006906 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006907 AddRec->getNoWrapFlags(SCEV::FlagNW));
6908 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006909 // The addrec may be folded to a nonrecurrence, for example, if the
6910 // induction variable is multiplied by zero after constant folding. Go
6911 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006912 if (!AddRec)
6913 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006914 break;
6915 }
6916
6917 // If the scope is outside the addrec's loop, evaluate it by using the
6918 // loop exit value of the addrec.
6919 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006920 // To evaluate this recurrence, we need to know how many times the AddRec
6921 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006922 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006923 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006924
Eli Friedman61f67622008-08-04 23:49:06 +00006925 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006926 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006927 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006928
Dan Gohman8ca08852009-05-24 23:25:42 +00006929 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006930 }
6931
Dan Gohmana30370b2009-05-04 22:02:23 +00006932 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006933 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006934 if (Op == Cast->getOperand())
6935 return Cast; // must be loop invariant
6936 return getZeroExtendExpr(Op, Cast->getType());
6937 }
6938
Dan Gohmana30370b2009-05-04 22:02:23 +00006939 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006940 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006941 if (Op == Cast->getOperand())
6942 return Cast; // must be loop invariant
6943 return getSignExtendExpr(Op, Cast->getType());
6944 }
6945
Dan Gohmana30370b2009-05-04 22:02:23 +00006946 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006947 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006948 if (Op == Cast->getOperand())
6949 return Cast; // must be loop invariant
6950 return getTruncateExpr(Op, Cast->getType());
6951 }
6952
Torok Edwinfbcc6632009-07-14 16:55:14 +00006953 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006954}
6955
Dan Gohmanaf752342009-07-07 17:06:11 +00006956const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006957 return getSCEVAtScope(getSCEV(V), L);
6958}
6959
Sanjoy Dasf8570812016-05-29 00:38:22 +00006960/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006961///
6962/// A * X = B (mod N)
6963///
6964/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6965/// A and B isn't important.
6966///
6967/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006968static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006969 ScalarEvolution &SE) {
6970 uint32_t BW = A.getBitWidth();
6971 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6972 assert(A != 0 && "A must be non-zero.");
6973
6974 // 1. D = gcd(A, N)
6975 //
6976 // The gcd of A and N may have only one prime factor: 2. The number of
6977 // trailing zeros in A is its multiplicity
6978 uint32_t Mult2 = A.countTrailingZeros();
6979 // D = 2^Mult2
6980
6981 // 2. Check if B is divisible by D.
6982 //
6983 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6984 // is not less than multiplicity of this prime factor for D.
6985 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006986 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006987
6988 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6989 // modulo (N / D).
6990 //
6991 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6992 // bit width during computations.
6993 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6994 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006995 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006996 APInt I = AD.multiplicativeInverse(Mod);
6997
6998 // 4. Compute the minimum unsigned root of the equation:
6999 // I * (B / D) mod (N / D)
7000 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7001
7002 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7003 // bits.
7004 return SE.getConstant(Result.trunc(BW));
7005}
Chris Lattnerd934c702004-04-02 20:23:17 +00007006
Sanjoy Dasf8570812016-05-29 00:38:22 +00007007/// Find the roots of the quadratic equation for the given quadratic chrec
7008/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7009/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007010///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007011static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007012SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007013 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007014 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7015 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7016 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007017
Chris Lattnerd934c702004-04-02 20:23:17 +00007018 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007019 if (!LC || !MC || !NC)
7020 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007021
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007022 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7023 const APInt &L = LC->getAPInt();
7024 const APInt &M = MC->getAPInt();
7025 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007026 APInt Two(BitWidth, 2);
7027 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007028
Dan Gohmance973df2009-06-24 04:48:43 +00007029 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007030 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007031 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007032 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7033 // The B coefficient is M-N/2
7034 APInt B(M);
7035 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007036
Reid Spencer983e3b32007-03-01 07:25:48 +00007037 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007038 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007039
Reid Spencer983e3b32007-03-01 07:25:48 +00007040 // Compute the B^2-4ac term.
7041 APInt SqrtTerm(B);
7042 SqrtTerm *= B;
7043 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007044
Nick Lewyckyfb780832012-08-01 09:14:36 +00007045 if (SqrtTerm.isNegative()) {
7046 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007047 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007048 }
7049
Reid Spencer983e3b32007-03-01 07:25:48 +00007050 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7051 // integer value or else APInt::sqrt() will assert.
7052 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007053
Dan Gohmance973df2009-06-24 04:48:43 +00007054 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007055 // The divisions must be performed as signed divisions.
7056 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007057 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007058 if (TwoA.isMinValue())
7059 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007060
Owen Anderson47db9412009-07-22 00:24:57 +00007061 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007062
7063 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007064 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007065 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007066 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007067
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007068 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7069 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007070 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007071}
7072
Andrew Trick3ca3f982011-07-26 17:19:55 +00007073ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007074ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007075 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007076
7077 // This is only used for loops with a "x != y" exit test. The exit condition
7078 // is now expressed as a single expression, V = x-y. So the exit test is
7079 // effectively V != 0. We know and take advantage of the fact that this
7080 // expression only being used in a comparison by zero context.
7081
Silviu Baranga6f444df2016-04-08 14:29:09 +00007082 SCEVUnionPredicate P;
Chris Lattnerd934c702004-04-02 20:23:17 +00007083 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007084 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007085 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007086 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007087 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007088 }
7089
Dan Gohman48f82222009-05-04 22:30:44 +00007090 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007091 if (!AddRec && AllowPredicates)
7092 // Try to make this an AddRec using runtime tests, in the first X
7093 // iterations of this loop, where X is the SCEV expression found by the
7094 // algorithm below.
7095 AddRec = convertSCEVToAddRecWithPredicates(V, L, P);
7096
Chris Lattnerd934c702004-04-02 20:23:17 +00007097 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007098 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007099
Chris Lattnerdff679f2011-01-09 22:39:48 +00007100 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7101 // the quadratic equation to solve it.
7102 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007103 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7104 const SCEVConstant *R1 = Roots->first;
7105 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007106 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007107 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7108 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007109 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007110 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007111
Chris Lattnerd934c702004-04-02 20:23:17 +00007112 // We can only use this value if the chrec ends up with an exact zero
7113 // value at this index. When solving for "X*X != 5", for example, we
7114 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007115 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007116 if (Val->isZero())
Silviu Baranga6f444df2016-04-08 14:29:09 +00007117 return ExitLimit(R1, R1, P); // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00007118 }
7119 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007120 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007121 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007122
Chris Lattnerdff679f2011-01-09 22:39:48 +00007123 // Otherwise we can only handle this if it is affine.
7124 if (!AddRec->isAffine())
7125 return getCouldNotCompute();
7126
7127 // If this is an affine expression, the execution count of this branch is
7128 // the minimum unsigned root of the following equation:
7129 //
7130 // Start + Step*N = 0 (mod 2^BW)
7131 //
7132 // equivalent to:
7133 //
7134 // Step*N = -Start (mod 2^BW)
7135 //
7136 // where BW is the common bit width of Start and Step.
7137
7138 // Get the initial value for the loop.
7139 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7140 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7141
7142 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007143 //
7144 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7145 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7146 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7147 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007148 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007149 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007150 return getCouldNotCompute();
7151
Andrew Trick8b55b732011-03-14 16:50:06 +00007152 // For positive steps (counting up until unsigned overflow):
7153 // N = -Start/Step (as unsigned)
7154 // For negative steps (counting down to zero):
7155 // N = Start/-Step
7156 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007157 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007158 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007159
7160 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007161 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7162 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007163 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7164 ConstantRange CR = getUnsignedRange(Start);
7165 const SCEV *MaxBECount;
7166 if (!CountDown && CR.getUnsignedMin().isMinValue())
7167 // When counting up, the worst starting value is 1, not 0.
7168 MaxBECount = CR.getUnsignedMax().isMinValue()
7169 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7170 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7171 else
7172 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7173 : -CR.getUnsignedMin());
Silviu Baranga6f444df2016-04-08 14:29:09 +00007174 return ExitLimit(Distance, MaxBECount, P);
Nick Lewycky31555522011-10-03 07:10:45 +00007175 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007176
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007177 // As a special case, handle the instance where Step is a positive power of
7178 // two. In this case, determining whether Step divides Distance evenly can be
7179 // done by counting and comparing the number of trailing zeros of Step and
7180 // Distance.
7181 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007182 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007183 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7184 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7185 // case is not handled as this code is guarded by !CountDown.
7186 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007187 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7188 // Here we've constrained the equation to be of the form
7189 //
7190 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7191 //
7192 // where we're operating on a W bit wide integer domain and k is
7193 // non-negative. The smallest unsigned solution for X is the trip count.
7194 //
7195 // (0) is equivalent to:
7196 //
7197 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7198 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7199 // <=> 2^k * Distance' - X = L * 2^(W - N)
7200 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7201 //
7202 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7203 // by 2^(W - N).
7204 //
7205 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7206 //
7207 // E.g. say we're solving
7208 //
7209 // 2 * Val = 2 * X (in i8) ... (3)
7210 //
7211 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7212 //
7213 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7214 // necessarily the smallest unsigned value of X that satisfies (3).
7215 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7216 // is i8 1, not i8 -127
7217
7218 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7219
7220 // Since SCEV does not have a URem node, we construct one using a truncate
7221 // and a zero extend.
7222
7223 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7224 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7225 auto *WideTy = Distance->getType();
7226
Silviu Baranga6f444df2016-04-08 14:29:09 +00007227 const SCEV *Limit =
7228 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7229 return ExitLimit(Limit, Limit, P);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007230 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007231 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007232
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007233 // If the condition controls loop exit (the loop exits only if the expression
7234 // is true) and the addition is no-wrap we can use unsigned divide to
7235 // compute the backedge count. In this case, the step may not divide the
7236 // distance, but we don't care because if the condition is "missed" the loop
7237 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007238 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7239 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007240 const SCEV *Exact =
7241 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007242 return ExitLimit(Exact, Exact, P);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007243 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007244
Chris Lattnerdff679f2011-01-09 22:39:48 +00007245 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007246 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7247 const SCEV *E = SolveLinEquationWithOverflow(
7248 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7249 return ExitLimit(E, E, P);
7250 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007251 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007252}
7253
Andrew Trick3ca3f982011-07-26 17:19:55 +00007254ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007255ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007256 // Loops that look like: while (X == 0) are very strange indeed. We don't
7257 // handle them yet except for the trivial case. This could be expanded in the
7258 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007259
Chris Lattnerd934c702004-04-02 20:23:17 +00007260 // If the value is a constant, check to see if it is known to be non-zero
7261 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007262 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007263 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007264 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007265 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007266 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007267
Chris Lattnerd934c702004-04-02 20:23:17 +00007268 // We could implement others, but I really doubt anyone writes loops like
7269 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007270 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007271}
7272
Dan Gohman4e3c1132010-04-15 16:19:08 +00007273std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007274ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007275 // If the block has a unique predecessor, then there is no path from the
7276 // predecessor to the block that does not go through the direct edge
7277 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007278 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007279 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007280
7281 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007282 // If the header has a unique predecessor outside the loop, it must be
7283 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007284 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007285 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007286
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007287 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007288}
7289
Sanjoy Dasf8570812016-05-29 00:38:22 +00007290/// SCEV structural equivalence is usually sufficient for testing whether two
7291/// expressions are equal, however for the purposes of looking for a condition
7292/// guarding a loop, it can be useful to be a little more general, since a
7293/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007294///
Dan Gohmanaf752342009-07-07 17:06:11 +00007295static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007296 // Quick check to see if they are the same SCEV.
7297 if (A == B) return true;
7298
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007299 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7300 // Not all instructions that are "identical" compute the same value. For
7301 // instance, two distinct alloca instructions allocating the same type are
7302 // identical and do not read memory; but compute distinct values.
7303 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7304 };
7305
Dan Gohman450f4e02009-06-20 00:35:32 +00007306 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7307 // two different instructions with the same value. Check for this case.
7308 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7309 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7310 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7311 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007312 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007313 return true;
7314
7315 // Otherwise assume they may have a different value.
7316 return false;
7317}
7318
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007319bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007320 const SCEV *&LHS, const SCEV *&RHS,
7321 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007322 bool Changed = false;
7323
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007324 // If we hit the max recursion limit bail out.
7325 if (Depth >= 3)
7326 return false;
7327
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007328 // Canonicalize a constant to the right side.
7329 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7330 // Check for both operands constant.
7331 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7332 if (ConstantExpr::getICmp(Pred,
7333 LHSC->getValue(),
7334 RHSC->getValue())->isNullValue())
7335 goto trivially_false;
7336 else
7337 goto trivially_true;
7338 }
7339 // Otherwise swap the operands to put the constant on the right.
7340 std::swap(LHS, RHS);
7341 Pred = ICmpInst::getSwappedPredicate(Pred);
7342 Changed = true;
7343 }
7344
7345 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007346 // addrec's loop, put the addrec on the left. Also make a dominance check,
7347 // as both operands could be addrecs loop-invariant in each other's loop.
7348 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7349 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007350 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007351 std::swap(LHS, RHS);
7352 Pred = ICmpInst::getSwappedPredicate(Pred);
7353 Changed = true;
7354 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007355 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007356
7357 // If there's a constant operand, canonicalize comparisons with boundary
7358 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7359 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007360 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007361 switch (Pred) {
7362 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7363 case ICmpInst::ICMP_EQ:
7364 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007365 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7366 if (!RA)
7367 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7368 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00007369 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7370 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007371 RHS = AE->getOperand(1);
7372 LHS = ME->getOperand(1);
7373 Changed = true;
7374 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007375 break;
7376 case ICmpInst::ICMP_UGE:
7377 if ((RA - 1).isMinValue()) {
7378 Pred = ICmpInst::ICMP_NE;
7379 RHS = getConstant(RA - 1);
7380 Changed = true;
7381 break;
7382 }
7383 if (RA.isMaxValue()) {
7384 Pred = ICmpInst::ICMP_EQ;
7385 Changed = true;
7386 break;
7387 }
7388 if (RA.isMinValue()) goto trivially_true;
7389
7390 Pred = ICmpInst::ICMP_UGT;
7391 RHS = getConstant(RA - 1);
7392 Changed = true;
7393 break;
7394 case ICmpInst::ICMP_ULE:
7395 if ((RA + 1).isMaxValue()) {
7396 Pred = ICmpInst::ICMP_NE;
7397 RHS = getConstant(RA + 1);
7398 Changed = true;
7399 break;
7400 }
7401 if (RA.isMinValue()) {
7402 Pred = ICmpInst::ICMP_EQ;
7403 Changed = true;
7404 break;
7405 }
7406 if (RA.isMaxValue()) goto trivially_true;
7407
7408 Pred = ICmpInst::ICMP_ULT;
7409 RHS = getConstant(RA + 1);
7410 Changed = true;
7411 break;
7412 case ICmpInst::ICMP_SGE:
7413 if ((RA - 1).isMinSignedValue()) {
7414 Pred = ICmpInst::ICMP_NE;
7415 RHS = getConstant(RA - 1);
7416 Changed = true;
7417 break;
7418 }
7419 if (RA.isMaxSignedValue()) {
7420 Pred = ICmpInst::ICMP_EQ;
7421 Changed = true;
7422 break;
7423 }
7424 if (RA.isMinSignedValue()) goto trivially_true;
7425
7426 Pred = ICmpInst::ICMP_SGT;
7427 RHS = getConstant(RA - 1);
7428 Changed = true;
7429 break;
7430 case ICmpInst::ICMP_SLE:
7431 if ((RA + 1).isMaxSignedValue()) {
7432 Pred = ICmpInst::ICMP_NE;
7433 RHS = getConstant(RA + 1);
7434 Changed = true;
7435 break;
7436 }
7437 if (RA.isMinSignedValue()) {
7438 Pred = ICmpInst::ICMP_EQ;
7439 Changed = true;
7440 break;
7441 }
7442 if (RA.isMaxSignedValue()) goto trivially_true;
7443
7444 Pred = ICmpInst::ICMP_SLT;
7445 RHS = getConstant(RA + 1);
7446 Changed = true;
7447 break;
7448 case ICmpInst::ICMP_UGT:
7449 if (RA.isMinValue()) {
7450 Pred = ICmpInst::ICMP_NE;
7451 Changed = true;
7452 break;
7453 }
7454 if ((RA + 1).isMaxValue()) {
7455 Pred = ICmpInst::ICMP_EQ;
7456 RHS = getConstant(RA + 1);
7457 Changed = true;
7458 break;
7459 }
7460 if (RA.isMaxValue()) goto trivially_false;
7461 break;
7462 case ICmpInst::ICMP_ULT:
7463 if (RA.isMaxValue()) {
7464 Pred = ICmpInst::ICMP_NE;
7465 Changed = true;
7466 break;
7467 }
7468 if ((RA - 1).isMinValue()) {
7469 Pred = ICmpInst::ICMP_EQ;
7470 RHS = getConstant(RA - 1);
7471 Changed = true;
7472 break;
7473 }
7474 if (RA.isMinValue()) goto trivially_false;
7475 break;
7476 case ICmpInst::ICMP_SGT:
7477 if (RA.isMinSignedValue()) {
7478 Pred = ICmpInst::ICMP_NE;
7479 Changed = true;
7480 break;
7481 }
7482 if ((RA + 1).isMaxSignedValue()) {
7483 Pred = ICmpInst::ICMP_EQ;
7484 RHS = getConstant(RA + 1);
7485 Changed = true;
7486 break;
7487 }
7488 if (RA.isMaxSignedValue()) goto trivially_false;
7489 break;
7490 case ICmpInst::ICMP_SLT:
7491 if (RA.isMaxSignedValue()) {
7492 Pred = ICmpInst::ICMP_NE;
7493 Changed = true;
7494 break;
7495 }
7496 if ((RA - 1).isMinSignedValue()) {
7497 Pred = ICmpInst::ICMP_EQ;
7498 RHS = getConstant(RA - 1);
7499 Changed = true;
7500 break;
7501 }
7502 if (RA.isMinSignedValue()) goto trivially_false;
7503 break;
7504 }
7505 }
7506
7507 // Check for obvious equality.
7508 if (HasSameValue(LHS, RHS)) {
7509 if (ICmpInst::isTrueWhenEqual(Pred))
7510 goto trivially_true;
7511 if (ICmpInst::isFalseWhenEqual(Pred))
7512 goto trivially_false;
7513 }
7514
Dan Gohman81585c12010-05-03 16:35:17 +00007515 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7516 // adding or subtracting 1 from one of the operands.
7517 switch (Pred) {
7518 case ICmpInst::ICMP_SLE:
7519 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7520 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007521 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007522 Pred = ICmpInst::ICMP_SLT;
7523 Changed = true;
7524 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007525 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007526 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007527 Pred = ICmpInst::ICMP_SLT;
7528 Changed = true;
7529 }
7530 break;
7531 case ICmpInst::ICMP_SGE:
7532 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007533 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007534 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007535 Pred = ICmpInst::ICMP_SGT;
7536 Changed = true;
7537 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7538 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007539 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007540 Pred = ICmpInst::ICMP_SGT;
7541 Changed = true;
7542 }
7543 break;
7544 case ICmpInst::ICMP_ULE:
7545 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007546 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007547 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007548 Pred = ICmpInst::ICMP_ULT;
7549 Changed = true;
7550 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007551 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007552 Pred = ICmpInst::ICMP_ULT;
7553 Changed = true;
7554 }
7555 break;
7556 case ICmpInst::ICMP_UGE:
7557 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007558 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007559 Pred = ICmpInst::ICMP_UGT;
7560 Changed = true;
7561 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007562 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007563 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007564 Pred = ICmpInst::ICMP_UGT;
7565 Changed = true;
7566 }
7567 break;
7568 default:
7569 break;
7570 }
7571
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007572 // TODO: More simplifications are possible here.
7573
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007574 // Recursively simplify until we either hit a recursion limit or nothing
7575 // changes.
7576 if (Changed)
7577 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7578
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007579 return Changed;
7580
7581trivially_true:
7582 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007583 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007584 Pred = ICmpInst::ICMP_EQ;
7585 return true;
7586
7587trivially_false:
7588 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007589 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007590 Pred = ICmpInst::ICMP_NE;
7591 return true;
7592}
7593
Dan Gohmane65c9172009-07-13 21:35:55 +00007594bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7595 return getSignedRange(S).getSignedMax().isNegative();
7596}
7597
7598bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7599 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7600}
7601
7602bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7603 return !getSignedRange(S).getSignedMin().isNegative();
7604}
7605
7606bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7607 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7608}
7609
7610bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7611 return isKnownNegative(S) || isKnownPositive(S);
7612}
7613
7614bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7615 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007616 // Canonicalize the inputs first.
7617 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7618
Dan Gohman07591692010-04-11 22:16:48 +00007619 // If LHS or RHS is an addrec, check to see if the condition is true in
7620 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007621 // If LHS and RHS are both addrec, both conditions must be true in
7622 // every iteration of the loop.
7623 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7624 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7625 bool LeftGuarded = false;
7626 bool RightGuarded = false;
7627 if (LAR) {
7628 const Loop *L = LAR->getLoop();
7629 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7630 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7631 if (!RAR) return true;
7632 LeftGuarded = true;
7633 }
7634 }
7635 if (RAR) {
7636 const Loop *L = RAR->getLoop();
7637 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7638 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7639 if (!LAR) return true;
7640 RightGuarded = true;
7641 }
7642 }
7643 if (LeftGuarded && RightGuarded)
7644 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007645
Sanjoy Das7d910f22015-10-02 18:50:30 +00007646 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7647 return true;
7648
Dan Gohman07591692010-04-11 22:16:48 +00007649 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007650 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007651}
7652
Sanjoy Das5dab2052015-07-27 21:42:49 +00007653bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7654 ICmpInst::Predicate Pred,
7655 bool &Increasing) {
7656 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7657
7658#ifndef NDEBUG
7659 // Verify an invariant: inverting the predicate should turn a monotonically
7660 // increasing change to a monotonically decreasing one, and vice versa.
7661 bool IncreasingSwapped;
7662 bool ResultSwapped = isMonotonicPredicateImpl(
7663 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7664
7665 assert(Result == ResultSwapped && "should be able to analyze both!");
7666 if (ResultSwapped)
7667 assert(Increasing == !IncreasingSwapped &&
7668 "monotonicity should flip as we flip the predicate");
7669#endif
7670
7671 return Result;
7672}
7673
7674bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7675 ICmpInst::Predicate Pred,
7676 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007677
7678 // A zero step value for LHS means the induction variable is essentially a
7679 // loop invariant value. We don't really depend on the predicate actually
7680 // flipping from false to true (for increasing predicates, and the other way
7681 // around for decreasing predicates), all we care about is that *if* the
7682 // predicate changes then it only changes from false to true.
7683 //
7684 // A zero step value in itself is not very useful, but there may be places
7685 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7686 // as general as possible.
7687
Sanjoy Das366acc12015-08-06 20:43:41 +00007688 switch (Pred) {
7689 default:
7690 return false; // Conservative answer
7691
7692 case ICmpInst::ICMP_UGT:
7693 case ICmpInst::ICMP_UGE:
7694 case ICmpInst::ICMP_ULT:
7695 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007696 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007697 return false;
7698
7699 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007700 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007701
7702 case ICmpInst::ICMP_SGT:
7703 case ICmpInst::ICMP_SGE:
7704 case ICmpInst::ICMP_SLT:
7705 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007706 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007707 return false;
7708
7709 const SCEV *Step = LHS->getStepRecurrence(*this);
7710
7711 if (isKnownNonNegative(Step)) {
7712 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7713 return true;
7714 }
7715
7716 if (isKnownNonPositive(Step)) {
7717 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7718 return true;
7719 }
7720
7721 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007722 }
7723
Sanjoy Das5dab2052015-07-27 21:42:49 +00007724 }
7725
Sanjoy Das366acc12015-08-06 20:43:41 +00007726 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007727}
7728
7729bool ScalarEvolution::isLoopInvariantPredicate(
7730 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7731 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7732 const SCEV *&InvariantRHS) {
7733
7734 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7735 if (!isLoopInvariant(RHS, L)) {
7736 if (!isLoopInvariant(LHS, L))
7737 return false;
7738
7739 std::swap(LHS, RHS);
7740 Pred = ICmpInst::getSwappedPredicate(Pred);
7741 }
7742
7743 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7744 if (!ArLHS || ArLHS->getLoop() != L)
7745 return false;
7746
7747 bool Increasing;
7748 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7749 return false;
7750
7751 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7752 // true as the loop iterates, and the backedge is control dependent on
7753 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7754 //
7755 // * if the predicate was false in the first iteration then the predicate
7756 // is never evaluated again, since the loop exits without taking the
7757 // backedge.
7758 // * if the predicate was true in the first iteration then it will
7759 // continue to be true for all future iterations since it is
7760 // monotonically increasing.
7761 //
7762 // For both the above possibilities, we can replace the loop varying
7763 // predicate with its value on the first iteration of the loop (which is
7764 // loop invariant).
7765 //
7766 // A similar reasoning applies for a monotonically decreasing predicate, by
7767 // replacing true with false and false with true in the above two bullets.
7768
7769 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7770
7771 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7772 return false;
7773
7774 InvariantPred = Pred;
7775 InvariantLHS = ArLHS->getStart();
7776 InvariantRHS = RHS;
7777 return true;
7778}
7779
Sanjoy Das401e6312016-02-01 20:48:10 +00007780bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7781 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007782 if (HasSameValue(LHS, RHS))
7783 return ICmpInst::isTrueWhenEqual(Pred);
7784
Dan Gohman07591692010-04-11 22:16:48 +00007785 // This code is split out from isKnownPredicate because it is called from
7786 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007787
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007788 auto CheckRanges =
7789 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7790 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7791 .contains(RangeLHS);
7792 };
7793
7794 // The check at the top of the function catches the case where the values are
7795 // known to be equal.
7796 if (Pred == CmpInst::ICMP_EQ)
7797 return false;
7798
7799 if (Pred == CmpInst::ICMP_NE)
7800 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7801 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7802 isKnownNonZero(getMinusSCEV(LHS, RHS));
7803
7804 if (CmpInst::isSigned(Pred))
7805 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7806
7807 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007808}
7809
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007810bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7811 const SCEV *LHS,
7812 const SCEV *RHS) {
7813
7814 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7815 // Return Y via OutY.
7816 auto MatchBinaryAddToConst =
7817 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7818 SCEV::NoWrapFlags ExpectedFlags) {
7819 const SCEV *NonConstOp, *ConstOp;
7820 SCEV::NoWrapFlags FlagsPresent;
7821
7822 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7823 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7824 return false;
7825
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007826 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007827 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7828 };
7829
7830 APInt C;
7831
7832 switch (Pred) {
7833 default:
7834 break;
7835
7836 case ICmpInst::ICMP_SGE:
7837 std::swap(LHS, RHS);
7838 case ICmpInst::ICMP_SLE:
7839 // X s<= (X + C)<nsw> if C >= 0
7840 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7841 return true;
7842
7843 // (X + C)<nsw> s<= X if C <= 0
7844 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7845 !C.isStrictlyPositive())
7846 return true;
7847 break;
7848
7849 case ICmpInst::ICMP_SGT:
7850 std::swap(LHS, RHS);
7851 case ICmpInst::ICMP_SLT:
7852 // X s< (X + C)<nsw> if C > 0
7853 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7854 C.isStrictlyPositive())
7855 return true;
7856
7857 // (X + C)<nsw> s< X if C < 0
7858 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7859 return true;
7860 break;
7861 }
7862
7863 return false;
7864}
7865
Sanjoy Das7d910f22015-10-02 18:50:30 +00007866bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7867 const SCEV *LHS,
7868 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007869 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007870 return false;
7871
7872 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7873 // the stack can result in exponential time complexity.
7874 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7875
7876 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7877 //
7878 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7879 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7880 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7881 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7882 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007883 return isKnownNonNegative(RHS) &&
7884 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7885 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007886}
7887
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007888bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7889 ICmpInst::Predicate Pred,
7890 const SCEV *LHS, const SCEV *RHS) {
7891 // No need to even try if we know the module has no guards.
7892 if (!HasGuards)
7893 return false;
7894
7895 return any_of(*BB, [&](Instruction &I) {
7896 using namespace llvm::PatternMatch;
7897
7898 Value *Condition;
7899 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7900 m_Value(Condition))) &&
7901 isImpliedCond(Pred, LHS, RHS, Condition, false);
7902 });
7903}
7904
Dan Gohmane65c9172009-07-13 21:35:55 +00007905/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7906/// protected by a conditional between LHS and RHS. This is used to
7907/// to eliminate casts.
7908bool
7909ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7910 ICmpInst::Predicate Pred,
7911 const SCEV *LHS, const SCEV *RHS) {
7912 // Interpret a null as meaning no loop, where there is obviously no guard
7913 // (interprocedural conditions notwithstanding).
7914 if (!L) return true;
7915
Sanjoy Das401e6312016-02-01 20:48:10 +00007916 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7917 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007918
Dan Gohmane65c9172009-07-13 21:35:55 +00007919 BasicBlock *Latch = L->getLoopLatch();
7920 if (!Latch)
7921 return false;
7922
7923 BranchInst *LoopContinuePredicate =
7924 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007925 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7926 isImpliedCond(Pred, LHS, RHS,
7927 LoopContinuePredicate->getCondition(),
7928 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7929 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007930
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007931 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007932 // -- that can lead to O(n!) time complexity.
7933 if (WalkingBEDominatingConds)
7934 return false;
7935
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007936 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007937
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007938 // See if we can exploit a trip count to prove the predicate.
7939 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7940 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7941 if (LatchBECount != getCouldNotCompute()) {
7942 // We know that Latch branches back to the loop header exactly
7943 // LatchBECount times. This means the backdege condition at Latch is
7944 // equivalent to "{0,+,1} u< LatchBECount".
7945 Type *Ty = LatchBECount->getType();
7946 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7947 const SCEV *LoopCounter =
7948 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7949 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7950 LatchBECount))
7951 return true;
7952 }
7953
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007954 // Check conditions due to any @llvm.assume intrinsics.
7955 for (auto &AssumeVH : AC.assumptions()) {
7956 if (!AssumeVH)
7957 continue;
7958 auto *CI = cast<CallInst>(AssumeVH);
7959 if (!DT.dominates(CI, Latch->getTerminator()))
7960 continue;
7961
7962 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7963 return true;
7964 }
7965
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007966 // If the loop is not reachable from the entry block, we risk running into an
7967 // infinite loop as we walk up into the dom tree. These loops do not matter
7968 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007969 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007970 return false;
7971
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007972 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7973 return true;
7974
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007975 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7976 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007977
7978 assert(DTN && "should reach the loop header before reaching the root!");
7979
7980 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007981 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7982 return true;
7983
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007984 BasicBlock *PBB = BB->getSinglePredecessor();
7985 if (!PBB)
7986 continue;
7987
7988 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7989 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7990 continue;
7991
7992 Value *Condition = ContinuePredicate->getCondition();
7993
7994 // If we have an edge `E` within the loop body that dominates the only
7995 // latch, the condition guarding `E` also guards the backedge. This
7996 // reasoning works only for loops with a single latch.
7997
7998 BasicBlockEdge DominatingEdge(PBB, BB);
7999 if (DominatingEdge.isSingleEdge()) {
8000 // We're constructively (and conservatively) enumerating edges within the
8001 // loop body that dominate the latch. The dominator tree better agree
8002 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008003 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008004
8005 if (isImpliedCond(Pred, LHS, RHS, Condition,
8006 BB != ContinuePredicate->getSuccessor(0)))
8007 return true;
8008 }
8009 }
8010
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008011 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008012}
8013
Dan Gohmane65c9172009-07-13 21:35:55 +00008014bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008015ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8016 ICmpInst::Predicate Pred,
8017 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008018 // Interpret a null as meaning no loop, where there is obviously no guard
8019 // (interprocedural conditions notwithstanding).
8020 if (!L) return false;
8021
Sanjoy Das401e6312016-02-01 20:48:10 +00008022 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8023 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008024
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008025 // Starting at the loop predecessor, climb up the predecessor chain, as long
8026 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008027 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008028 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008029 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008030 Pair.first;
8031 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008032
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008033 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8034 return true;
8035
Dan Gohman2a62fd92008-08-12 20:17:31 +00008036 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008037 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008038 if (!LoopEntryPredicate ||
8039 LoopEntryPredicate->isUnconditional())
8040 continue;
8041
Dan Gohmane18c2d62010-08-10 23:46:30 +00008042 if (isImpliedCond(Pred, LHS, RHS,
8043 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008044 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008045 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008046 }
8047
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008048 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008049 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00008050 if (!AssumeVH)
8051 continue;
8052 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008053 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008054 continue;
8055
8056 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8057 return true;
8058 }
8059
Dan Gohman2a62fd92008-08-12 20:17:31 +00008060 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008061}
8062
Benjamin Kramer039b1042015-10-28 13:54:36 +00008063namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008064/// RAII wrapper to prevent recursive application of isImpliedCond.
8065/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
8066/// currently evaluating isImpliedCond.
8067struct MarkPendingLoopPredicate {
8068 Value *Cond;
8069 DenseSet<Value*> &LoopPreds;
8070 bool Pending;
8071
8072 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
8073 : Cond(C), LoopPreds(LP) {
8074 Pending = !LoopPreds.insert(Cond).second;
8075 }
8076 ~MarkPendingLoopPredicate() {
8077 if (!Pending)
8078 LoopPreds.erase(Cond);
8079 }
8080};
Benjamin Kramer039b1042015-10-28 13:54:36 +00008081} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008082
Dan Gohmane18c2d62010-08-10 23:46:30 +00008083bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008084 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008085 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008086 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008087 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
8088 if (Mark.Pending)
8089 return false;
8090
Dan Gohman8b0a4192010-03-01 17:49:51 +00008091 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008093 if (BO->getOpcode() == Instruction::And) {
8094 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008095 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8096 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008097 } else if (BO->getOpcode() == Instruction::Or) {
8098 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008099 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8100 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008101 }
8102 }
8103
Dan Gohmane18c2d62010-08-10 23:46:30 +00008104 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008105 if (!ICI) return false;
8106
Andrew Trickfa594032012-11-29 18:35:13 +00008107 // Now that we found a conditional branch that dominates the loop or controls
8108 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008109 ICmpInst::Predicate FoundPred;
8110 if (Inverse)
8111 FoundPred = ICI->getInversePredicate();
8112 else
8113 FoundPred = ICI->getPredicate();
8114
8115 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8116 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008117
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008118 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8119}
8120
8121bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8122 const SCEV *RHS,
8123 ICmpInst::Predicate FoundPred,
8124 const SCEV *FoundLHS,
8125 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008126 // Balance the types.
8127 if (getTypeSizeInBits(LHS->getType()) <
8128 getTypeSizeInBits(FoundLHS->getType())) {
8129 if (CmpInst::isSigned(Pred)) {
8130 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8131 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8132 } else {
8133 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8134 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8135 }
8136 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008137 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008138 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008139 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8140 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8141 } else {
8142 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8143 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8144 }
8145 }
8146
Dan Gohman430f0cc2009-07-21 23:03:19 +00008147 // Canonicalize the query to match the way instcombine will have
8148 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008149 if (SimplifyICmpOperands(Pred, LHS, RHS))
8150 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008151 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008152 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8153 if (FoundLHS == FoundRHS)
8154 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008155
8156 // Check to see if we can make the LHS or RHS match.
8157 if (LHS == FoundRHS || RHS == FoundLHS) {
8158 if (isa<SCEVConstant>(RHS)) {
8159 std::swap(FoundLHS, FoundRHS);
8160 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8161 } else {
8162 std::swap(LHS, RHS);
8163 Pred = ICmpInst::getSwappedPredicate(Pred);
8164 }
8165 }
8166
8167 // Check whether the found predicate is the same as the desired predicate.
8168 if (FoundPred == Pred)
8169 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8170
8171 // Check whether swapping the found predicate makes it the same as the
8172 // desired predicate.
8173 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8174 if (isa<SCEVConstant>(RHS))
8175 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8176 else
8177 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8178 RHS, LHS, FoundLHS, FoundRHS);
8179 }
8180
Sanjoy Das6e78b172015-10-22 19:57:34 +00008181 // Unsigned comparison is the same as signed comparison when both the operands
8182 // are non-negative.
8183 if (CmpInst::isUnsigned(FoundPred) &&
8184 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8185 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8186 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8187
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008188 // Check if we can make progress by sharpening ranges.
8189 if (FoundPred == ICmpInst::ICMP_NE &&
8190 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8191
8192 const SCEVConstant *C = nullptr;
8193 const SCEV *V = nullptr;
8194
8195 if (isa<SCEVConstant>(FoundLHS)) {
8196 C = cast<SCEVConstant>(FoundLHS);
8197 V = FoundRHS;
8198 } else {
8199 C = cast<SCEVConstant>(FoundRHS);
8200 V = FoundLHS;
8201 }
8202
8203 // The guarding predicate tells us that C != V. If the known range
8204 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8205 // range we consider has to correspond to same signedness as the
8206 // predicate we're interested in folding.
8207
8208 APInt Min = ICmpInst::isSigned(Pred) ?
8209 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8210
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008211 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008212 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8213 // This is true even if (Min + 1) wraps around -- in case of
8214 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8215
8216 APInt SharperMin = Min + 1;
8217
8218 switch (Pred) {
8219 case ICmpInst::ICMP_SGE:
8220 case ICmpInst::ICMP_UGE:
8221 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8222 // RHS, we're done.
8223 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8224 getConstant(SharperMin)))
8225 return true;
8226
8227 case ICmpInst::ICMP_SGT:
8228 case ICmpInst::ICMP_UGT:
8229 // We know from the range information that (V `Pred` Min ||
8230 // V == Min). We know from the guarding condition that !(V
8231 // == Min). This gives us
8232 //
8233 // V `Pred` Min || V == Min && !(V == Min)
8234 // => V `Pred` Min
8235 //
8236 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8237
8238 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8239 return true;
8240
8241 default:
8242 // No change
8243 break;
8244 }
8245 }
8246 }
8247
Dan Gohman430f0cc2009-07-21 23:03:19 +00008248 // Check whether the actual condition is beyond sufficient.
8249 if (FoundPred == ICmpInst::ICMP_EQ)
8250 if (ICmpInst::isTrueWhenEqual(Pred))
8251 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8252 return true;
8253 if (Pred == ICmpInst::ICMP_NE)
8254 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8255 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8256 return true;
8257
8258 // Otherwise assume the worst.
8259 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008260}
8261
Sanjoy Das1ed69102015-10-13 02:53:27 +00008262bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8263 const SCEV *&L, const SCEV *&R,
8264 SCEV::NoWrapFlags &Flags) {
8265 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8266 if (!AE || AE->getNumOperands() != 2)
8267 return false;
8268
8269 L = AE->getOperand(0);
8270 R = AE->getOperand(1);
8271 Flags = AE->getNoWrapFlags();
8272 return true;
8273}
8274
Sanjoy Das0b1af852016-07-23 00:28:56 +00008275Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8276 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008277 // We avoid subtracting expressions here because this function is usually
8278 // fairly deep in the call stack (i.e. is called many times).
8279
Sanjoy Das96709c42015-09-25 23:53:45 +00008280 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8281 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8282 const auto *MAR = cast<SCEVAddRecExpr>(More);
8283
8284 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008285 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008286
8287 // We look at affine expressions only; not for correctness but to keep
8288 // getStepRecurrence cheap.
8289 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008290 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008291
Sanjoy Das1ed69102015-10-13 02:53:27 +00008292 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008293 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008294
8295 Less = LAR->getStart();
8296 More = MAR->getStart();
8297
8298 // fall through
8299 }
8300
8301 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008302 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8303 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008304 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008305 }
8306
8307 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008308 SCEV::NoWrapFlags Flags;
8309 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008310 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008311 if (R == More)
8312 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008313
Sanjoy Das1ed69102015-10-13 02:53:27 +00008314 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008315 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008316 if (R == Less)
8317 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008318
Sanjoy Das0b1af852016-07-23 00:28:56 +00008319 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008320}
8321
8322bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8323 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8324 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8325 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8326 return false;
8327
8328 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8329 if (!AddRecLHS)
8330 return false;
8331
8332 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8333 if (!AddRecFoundLHS)
8334 return false;
8335
8336 // We'd like to let SCEV reason about control dependencies, so we constrain
8337 // both the inequalities to be about add recurrences on the same loop. This
8338 // way we can use isLoopEntryGuardedByCond later.
8339
8340 const Loop *L = AddRecFoundLHS->getLoop();
8341 if (L != AddRecLHS->getLoop())
8342 return false;
8343
8344 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8345 //
8346 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8347 // ... (2)
8348 //
8349 // Informal proof for (2), assuming (1) [*]:
8350 //
8351 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8352 //
8353 // Then
8354 //
8355 // FoundLHS s< FoundRHS s< INT_MIN - C
8356 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8357 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8358 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8359 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8360 // <=> FoundLHS + C s< FoundRHS + C
8361 //
8362 // [*]: (1) can be proved by ruling out overflow.
8363 //
8364 // [**]: This can be proved by analyzing all the four possibilities:
8365 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8366 // (A s>= 0, B s>= 0).
8367 //
8368 // Note:
8369 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8370 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8371 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8372 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8373 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8374 // C)".
8375
Sanjoy Das0b1af852016-07-23 00:28:56 +00008376 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8377 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8378 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008379 return false;
8380
Sanjoy Das0b1af852016-07-23 00:28:56 +00008381 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008382 return true;
8383
Sanjoy Das96709c42015-09-25 23:53:45 +00008384 APInt FoundRHSLimit;
8385
8386 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008387 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008388 } else {
8389 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008390 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008391 }
8392
8393 // Try to prove (1) or (2), as needed.
8394 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8395 getConstant(FoundRHSLimit));
8396}
8397
Dan Gohman430f0cc2009-07-21 23:03:19 +00008398bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8399 const SCEV *LHS, const SCEV *RHS,
8400 const SCEV *FoundLHS,
8401 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008402 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8403 return true;
8404
Sanjoy Das96709c42015-09-25 23:53:45 +00008405 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8406 return true;
8407
Dan Gohman430f0cc2009-07-21 23:03:19 +00008408 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8409 FoundLHS, FoundRHS) ||
8410 // ~x < ~y --> x > y
8411 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8412 getNotSCEV(FoundRHS),
8413 getNotSCEV(FoundLHS));
8414}
8415
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008416
8417/// If Expr computes ~A, return A else return nullptr
8418static const SCEV *MatchNotExpr(const SCEV *Expr) {
8419 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008420 if (!Add || Add->getNumOperands() != 2 ||
8421 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008422 return nullptr;
8423
8424 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008425 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8426 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008427 return nullptr;
8428
8429 return AddRHS->getOperand(1);
8430}
8431
8432
8433/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8434template<typename MaxExprType>
8435static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8436 const SCEV *Candidate) {
8437 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8438 if (!MaxExpr) return false;
8439
Sanjoy Das347d2722015-12-01 07:49:27 +00008440 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008441}
8442
8443
8444/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8445template<typename MaxExprType>
8446static bool IsMinConsistingOf(ScalarEvolution &SE,
8447 const SCEV *MaybeMinExpr,
8448 const SCEV *Candidate) {
8449 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8450 if (!MaybeMaxExpr)
8451 return false;
8452
8453 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8454}
8455
Hal Finkela8d205f2015-08-19 01:51:51 +00008456static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8457 ICmpInst::Predicate Pred,
8458 const SCEV *LHS, const SCEV *RHS) {
8459
8460 // If both sides are affine addrecs for the same loop, with equal
8461 // steps, and we know the recurrences don't wrap, then we only
8462 // need to check the predicate on the starting values.
8463
8464 if (!ICmpInst::isRelational(Pred))
8465 return false;
8466
8467 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8468 if (!LAR)
8469 return false;
8470 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8471 if (!RAR)
8472 return false;
8473 if (LAR->getLoop() != RAR->getLoop())
8474 return false;
8475 if (!LAR->isAffine() || !RAR->isAffine())
8476 return false;
8477
8478 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8479 return false;
8480
Hal Finkelff08a2e2015-08-19 17:26:07 +00008481 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8482 SCEV::FlagNSW : SCEV::FlagNUW;
8483 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008484 return false;
8485
8486 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8487}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008488
8489/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8490/// expression?
8491static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8492 ICmpInst::Predicate Pred,
8493 const SCEV *LHS, const SCEV *RHS) {
8494 switch (Pred) {
8495 default:
8496 return false;
8497
8498 case ICmpInst::ICMP_SGE:
8499 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008500 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008501 case ICmpInst::ICMP_SLE:
8502 return
8503 // min(A, ...) <= A
8504 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8505 // A <= max(A, ...)
8506 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8507
8508 case ICmpInst::ICMP_UGE:
8509 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008510 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008511 case ICmpInst::ICMP_ULE:
8512 return
8513 // min(A, ...) <= A
8514 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8515 // A <= max(A, ...)
8516 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8517 }
8518
8519 llvm_unreachable("covered switch fell through?!");
8520}
8521
Dan Gohmane65c9172009-07-13 21:35:55 +00008522bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008523ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8524 const SCEV *LHS, const SCEV *RHS,
8525 const SCEV *FoundLHS,
8526 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008527 auto IsKnownPredicateFull =
8528 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008529 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008530 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008531 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8532 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008533 };
8534
Dan Gohmane65c9172009-07-13 21:35:55 +00008535 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008536 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8537 case ICmpInst::ICMP_EQ:
8538 case ICmpInst::ICMP_NE:
8539 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8540 return true;
8541 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008542 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008543 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008544 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8545 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008546 return true;
8547 break;
8548 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008549 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008550 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8551 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008552 return true;
8553 break;
8554 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008555 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008556 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8557 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008558 return true;
8559 break;
8560 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008561 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008562 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8563 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008564 return true;
8565 break;
8566 }
8567
8568 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008569}
8570
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008571bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8572 const SCEV *LHS,
8573 const SCEV *RHS,
8574 const SCEV *FoundLHS,
8575 const SCEV *FoundRHS) {
8576 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8577 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8578 // reduce the compile time impact of this optimization.
8579 return false;
8580
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008581 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008582 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008583 return false;
8584
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008585 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008586
8587 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8588 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8589 ConstantRange FoundLHSRange =
8590 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8591
Sanjoy Das095f5b22016-07-22 20:47:55 +00008592 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8593 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008594
8595 // We can also compute the range of values for `LHS` that satisfy the
8596 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008597 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008598 ConstantRange SatisfyingLHSRange =
8599 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8600
8601 // The antecedent implies the consequent if every value of `LHS` that
8602 // satisfies the antecedent also satisfies the consequent.
8603 return SatisfyingLHSRange.contains(LHSRange);
8604}
8605
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008606bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8607 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008608 assert(isKnownPositive(Stride) && "Positive stride expected!");
8609
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008610 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008611
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008612 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008613 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008614
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008615 if (IsSigned) {
8616 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8617 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8618 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8619 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008620
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008621 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8622 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008623 }
Dan Gohman01048422009-06-21 23:46:38 +00008624
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008625 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8626 APInt MaxValue = APInt::getMaxValue(BitWidth);
8627 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8628 .getUnsignedMax();
8629
8630 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8631 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8632}
8633
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008634bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8635 bool IsSigned, bool NoWrap) {
8636 if (NoWrap) return false;
8637
8638 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008639 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008640
8641 if (IsSigned) {
8642 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8643 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8644 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8645 .getSignedMax();
8646
8647 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8648 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8649 }
8650
8651 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8652 APInt MinValue = APInt::getMinValue(BitWidth);
8653 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8654 .getUnsignedMax();
8655
8656 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8657 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8658}
8659
Johannes Doerfert2683e562015-02-09 12:34:23 +00008660const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008661 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008662 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008663 Delta = Equality ? getAddExpr(Delta, Step)
8664 : getAddExpr(Delta, getMinusSCEV(Step, One));
8665 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008666}
8667
Andrew Trick3ca3f982011-07-26 17:19:55 +00008668ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008669ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008670 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008671 bool ControlsExit, bool AllowPredicates) {
8672 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008673 // We handle only IV < Invariant
8674 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008675 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008676
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008677 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008678 bool PredicatedIV = false;
8679
8680 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008681 // Try to make this an AddRec using runtime tests, in the first X
8682 // iterations of this loop, where X is the SCEV expression found by the
8683 // algorithm below.
8684 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008685 PredicatedIV = true;
8686 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008687
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008688 // Avoid weird loops
8689 if (!IV || IV->getLoop() != L || !IV->isAffine())
8690 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008691
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008692 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008693 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008694
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008695 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008696
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008697 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008698
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008699 // Avoid negative or zero stride values.
8700 if (!PositiveStride) {
8701 // We can compute the correct backedge taken count for loops with unknown
8702 // strides if we can prove that the loop is not an infinite loop with side
8703 // effects. Here's the loop structure we are trying to handle -
8704 //
8705 // i = start
8706 // do {
8707 // A[i] = i;
8708 // i += s;
8709 // } while (i < end);
8710 //
8711 // The backedge taken count for such loops is evaluated as -
8712 // (max(end, start + stride) - start - 1) /u stride
8713 //
8714 // The additional preconditions that we need to check to prove correctness
8715 // of the above formula is as follows -
8716 //
8717 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8718 // NoWrap flag).
8719 // b) loop is single exit with no side effects.
8720 //
8721 //
8722 // Precondition a) implies that if the stride is negative, this is a single
8723 // trip loop. The backedge taken count formula reduces to zero in this case.
8724 //
8725 // Precondition b) implies that the unknown stride cannot be zero otherwise
8726 // we have UB.
8727 //
8728 // The positive stride case is the same as isKnownPositive(Stride) returning
8729 // true (original behavior of the function).
8730 //
8731 // We want to make sure that the stride is truly unknown as there are edge
8732 // cases where ScalarEvolution propagates no wrap flags to the
8733 // post-increment/decrement IV even though the increment/decrement operation
8734 // itself is wrapping. The computed backedge taken count may be wrong in
8735 // such cases. This is prevented by checking that the stride is not known to
8736 // be either positive or non-positive. For example, no wrap flags are
8737 // propagated to the post-increment IV of this loop with a trip count of 2 -
8738 //
8739 // unsigned char i;
8740 // for(i=127; i<128; i+=129)
8741 // A[i] = i;
8742 //
8743 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8744 !loopHasNoSideEffects(L))
8745 return getCouldNotCompute();
8746
8747 } else if (!Stride->isOne() &&
8748 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8749 // Avoid proven overflow cases: this will ensure that the backedge taken
8750 // count will not generate any unsigned overflow. Relaxed no-overflow
8751 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8752 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008753 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008754
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008755 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8756 : ICmpInst::ICMP_ULT;
8757 const SCEV *Start = IV->getStart();
8758 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008759 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8760 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
Dan Gohman51aaf022010-01-26 04:40:18 +00008761
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008762 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008763
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008764 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8765 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008766
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008767 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008768
8769 APInt StrideForMaxBECount;
8770
8771 if (PositiveStride)
8772 StrideForMaxBECount = IsSigned ? getSignedRange(Stride).getSignedMin()
8773 : getUnsignedRange(Stride).getUnsignedMin();
8774 else
8775 // Using a stride of 1 is safe when computing max backedge taken count for
8776 // a loop with unknown stride.
8777 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8778
8779 APInt Limit =
8780 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8781 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008782
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008783 // Although End can be a MAX expression we estimate MaxEnd considering only
8784 // the case End = RHS. This is safe because in the other case (End - Start)
8785 // is zero, leading to a zero maximum backedge taken count.
8786 APInt MaxEnd =
8787 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8788 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8789
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008790 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008791 if (isa<SCEVConstant>(BECount))
8792 MaxBECount = BECount;
8793 else
8794 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008795 getConstant(StrideForMaxBECount), false);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008796
8797 if (isa<SCEVCouldNotCompute>(MaxBECount))
8798 MaxBECount = BECount;
8799
Silviu Baranga6f444df2016-04-08 14:29:09 +00008800 return ExitLimit(BECount, MaxBECount, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008801}
8802
8803ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008804ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008805 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008806 bool ControlsExit, bool AllowPredicates) {
8807 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008808 // We handle only IV > Invariant
8809 if (!isLoopInvariant(RHS, L))
8810 return getCouldNotCompute();
8811
8812 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008813 if (!IV && AllowPredicates)
8814 // Try to make this an AddRec using runtime tests, in the first X
8815 // iterations of this loop, where X is the SCEV expression found by the
8816 // algorithm below.
8817 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008818
8819 // Avoid weird loops
8820 if (!IV || IV->getLoop() != L || !IV->isAffine())
8821 return getCouldNotCompute();
8822
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008823 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008824 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8825
8826 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8827
8828 // Avoid negative or zero stride values
8829 if (!isKnownPositive(Stride))
8830 return getCouldNotCompute();
8831
8832 // Avoid proven overflow cases: this will ensure that the backedge taken count
8833 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008834 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008835 // behaviors like the case of C language.
8836 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8837 return getCouldNotCompute();
8838
8839 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8840 : ICmpInst::ICMP_UGT;
8841
8842 const SCEV *Start = IV->getStart();
8843 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008844 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8845 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008846
8847 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8848
8849 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8850 : getUnsignedRange(Start).getUnsignedMax();
8851
8852 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8853 : getUnsignedRange(Stride).getUnsignedMin();
8854
8855 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8856 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8857 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8858
8859 // Although End can be a MIN expression we estimate MinEnd considering only
8860 // the case End = RHS. This is safe because in the other case (Start - End)
8861 // is zero, leading to a zero maximum backedge taken count.
8862 APInt MinEnd =
8863 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8864 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8865
8866
8867 const SCEV *MaxBECount = getCouldNotCompute();
8868 if (isa<SCEVConstant>(BECount))
8869 MaxBECount = BECount;
8870 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008871 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008872 getConstant(MinStride), false);
8873
8874 if (isa<SCEVCouldNotCompute>(MaxBECount))
8875 MaxBECount = BECount;
8876
Silviu Baranga6f444df2016-04-08 14:29:09 +00008877 return ExitLimit(BECount, MaxBECount, P);
Chris Lattner587a75b2005-08-15 23:33:51 +00008878}
8879
Benjamin Kramerc321e532016-06-08 19:09:22 +00008880const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008881 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008882 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008883 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008884
8885 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008886 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008887 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008888 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008889 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008890 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008891 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008892 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008893 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008894 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008895 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008896 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008897 }
8898
8899 // The only time we can solve this is when we have all constant indices.
8900 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008901 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008902 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008903
8904 // Okay at this point we know that all elements of the chrec are constants and
8905 // that the start element is zero.
8906
8907 // First check to see if the range contains zero. If not, the first
8908 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008909 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008910 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008911 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008912
Chris Lattnerd934c702004-04-02 20:23:17 +00008913 if (isAffine()) {
8914 // If this is an affine expression then we have this situation:
8915 // Solve {0,+,A} in Range === Ax in Range
8916
Nick Lewycky52460262007-07-16 02:08:00 +00008917 // We know that zero is in the range. If A is positive then we know that
8918 // the upper value of the range must be the first possible exit value.
8919 // If A is negative then the lower of the range is the last possible loop
8920 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008921 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008922 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008923 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008924
Nick Lewycky52460262007-07-16 02:08:00 +00008925 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008926 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008927 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008928
8929 // Evaluate at the exit value. If we really did fall out of the valid
8930 // range, then we computed our trip count, otherwise wrap around or other
8931 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008932 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008933 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008934 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008935
8936 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008937 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008938 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008939 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008940 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008941 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008942 } else if (isQuadratic()) {
8943 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8944 // quadratic equation to solve it. To do this, we must frame our problem in
8945 // terms of figuring out when zero is crossed, instead of when
8946 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008947 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008948 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008949 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8950 // getNoWrapFlags(FlagNW)
8951 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008952
8953 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008954 if (auto Roots =
8955 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008956 const SCEVConstant *R1 = Roots->first;
8957 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008958 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008959 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8960 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008961 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008962 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008963
Chris Lattnerd934c702004-04-02 20:23:17 +00008964 // Make sure the root is not off by one. The returned iteration should
8965 // not be in the range, but the previous one should be. When solving
8966 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00008967 ConstantInt *R1Val =
8968 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008969 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008970 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008971 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008972 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008973
Dan Gohmana37eaf22007-10-22 18:31:58 +00008974 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008975 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008976 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00008977 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008978 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008979
Chris Lattnerd934c702004-04-02 20:23:17 +00008980 // If R1 was not in the range, then it is a good return value. Make
8981 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008982 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008983 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008984 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008985 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008986 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00008987 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008988 }
8989 }
8990 }
8991
Dan Gohman31efa302009-04-18 17:58:19 +00008992 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008993}
8994
Sebastian Pop448712b2014-05-07 18:01:20 +00008995namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008996struct FindUndefs {
8997 bool Found;
8998 FindUndefs() : Found(false) {}
8999
9000 bool follow(const SCEV *S) {
9001 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
9002 if (isa<UndefValue>(C->getValue()))
9003 Found = true;
9004 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
9005 if (isa<UndefValue>(C->getValue()))
9006 Found = true;
9007 }
9008
9009 // Keep looking if we haven't found it yet.
9010 return !Found;
9011 }
9012 bool isDone() const {
9013 // Stop recursion if we have found an undef.
9014 return Found;
9015 }
9016};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009017}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009018
9019// Return true when S contains at least an undef value.
9020static inline bool
9021containsUndefs(const SCEV *S) {
9022 FindUndefs F;
9023 SCEVTraversal<FindUndefs> ST(F);
9024 ST.visitAll(S);
9025
9026 return F.Found;
9027}
9028
9029namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009030// Collect all steps of SCEV expressions.
9031struct SCEVCollectStrides {
9032 ScalarEvolution &SE;
9033 SmallVectorImpl<const SCEV *> &Strides;
9034
9035 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9036 : SE(SE), Strides(S) {}
9037
9038 bool follow(const SCEV *S) {
9039 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9040 Strides.push_back(AR->getStepRecurrence(SE));
9041 return true;
9042 }
9043 bool isDone() const { return false; }
9044};
9045
9046// Collect all SCEVUnknown and SCEVMulExpr expressions.
9047struct SCEVCollectTerms {
9048 SmallVectorImpl<const SCEV *> &Terms;
9049
9050 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9051 : Terms(T) {}
9052
9053 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009054 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009055 if (!containsUndefs(S))
9056 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009057
9058 // Stop recursion: once we collected a term, do not walk its operands.
9059 return false;
9060 }
9061
9062 // Keep looking.
9063 return true;
9064 }
9065 bool isDone() const { return false; }
9066};
Tobias Grosser374bce02015-10-12 08:02:00 +00009067
9068// Check if a SCEV contains an AddRecExpr.
9069struct SCEVHasAddRec {
9070 bool &ContainsAddRec;
9071
9072 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9073 ContainsAddRec = false;
9074 }
9075
9076 bool follow(const SCEV *S) {
9077 if (isa<SCEVAddRecExpr>(S)) {
9078 ContainsAddRec = true;
9079
9080 // Stop recursion: once we collected a term, do not walk its operands.
9081 return false;
9082 }
9083
9084 // Keep looking.
9085 return true;
9086 }
9087 bool isDone() const { return false; }
9088};
9089
9090// Find factors that are multiplied with an expression that (possibly as a
9091// subexpression) contains an AddRecExpr. In the expression:
9092//
9093// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9094//
9095// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9096// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9097// parameters as they form a product with an induction variable.
9098//
9099// This collector expects all array size parameters to be in the same MulExpr.
9100// It might be necessary to later add support for collecting parameters that are
9101// spread over different nested MulExpr.
9102struct SCEVCollectAddRecMultiplies {
9103 SmallVectorImpl<const SCEV *> &Terms;
9104 ScalarEvolution &SE;
9105
9106 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9107 : Terms(T), SE(SE) {}
9108
9109 bool follow(const SCEV *S) {
9110 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9111 bool HasAddRec = false;
9112 SmallVector<const SCEV *, 0> Operands;
9113 for (auto Op : Mul->operands()) {
9114 if (isa<SCEVUnknown>(Op)) {
9115 Operands.push_back(Op);
9116 } else {
9117 bool ContainsAddRec;
9118 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9119 visitAll(Op, ContiansAddRec);
9120 HasAddRec |= ContainsAddRec;
9121 }
9122 }
9123 if (Operands.size() == 0)
9124 return true;
9125
9126 if (!HasAddRec)
9127 return false;
9128
9129 Terms.push_back(SE.getMulExpr(Operands));
9130 // Stop recursion: once we collected a term, do not walk its operands.
9131 return false;
9132 }
9133
9134 // Keep looking.
9135 return true;
9136 }
9137 bool isDone() const { return false; }
9138};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009139}
Sebastian Pop448712b2014-05-07 18:01:20 +00009140
Tobias Grosser374bce02015-10-12 08:02:00 +00009141/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9142/// two places:
9143/// 1) The strides of AddRec expressions.
9144/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009145void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9146 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009147 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009148 SCEVCollectStrides StrideCollector(*this, Strides);
9149 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009150
9151 DEBUG({
9152 dbgs() << "Strides:\n";
9153 for (const SCEV *S : Strides)
9154 dbgs() << *S << "\n";
9155 });
9156
9157 for (const SCEV *S : Strides) {
9158 SCEVCollectTerms TermCollector(Terms);
9159 visitAll(S, TermCollector);
9160 }
9161
9162 DEBUG({
9163 dbgs() << "Terms:\n";
9164 for (const SCEV *T : Terms)
9165 dbgs() << *T << "\n";
9166 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009167
9168 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9169 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009170}
9171
Sebastian Popb1a548f2014-05-12 19:01:53 +00009172static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009173 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009174 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009175 int Last = Terms.size() - 1;
9176 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009177
Sebastian Pop448712b2014-05-07 18:01:20 +00009178 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009179 if (Last == 0) {
9180 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009181 SmallVector<const SCEV *, 2> Qs;
9182 for (const SCEV *Op : M->operands())
9183 if (!isa<SCEVConstant>(Op))
9184 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009185
Sebastian Pope30bd352014-05-27 22:41:56 +00009186 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009187 }
9188
Sebastian Pope30bd352014-05-27 22:41:56 +00009189 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009190 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009191 }
9192
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009193 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009194 // Normalize the terms before the next call to findArrayDimensionsRec.
9195 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009196 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009197
9198 // Bail out when GCD does not evenly divide one of the terms.
9199 if (!R->isZero())
9200 return false;
9201
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009202 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009203 }
9204
Tobias Grosser3080cf12014-05-08 07:55:34 +00009205 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009206 Terms.erase(
9207 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9208 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009209
Sebastian Pop448712b2014-05-07 18:01:20 +00009210 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009211 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9212 return false;
9213
Sebastian Pope30bd352014-05-27 22:41:56 +00009214 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009215 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009216}
Sebastian Popc62c6792013-11-12 22:47:20 +00009217
Sebastian Pop448712b2014-05-07 18:01:20 +00009218// Returns true when S contains at least a SCEVUnknown parameter.
9219static inline bool
9220containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00009221 struct FindParameter {
9222 bool FoundParameter;
9223 FindParameter() : FoundParameter(false) {}
9224
9225 bool follow(const SCEV *S) {
9226 if (isa<SCEVUnknown>(S)) {
9227 FoundParameter = true;
9228 // Stop recursion: we found a parameter.
9229 return false;
9230 }
9231 // Keep looking.
9232 return true;
9233 }
9234 bool isDone() const {
9235 // Stop recursion if we have found a parameter.
9236 return FoundParameter;
9237 }
9238 };
9239
Sebastian Pop448712b2014-05-07 18:01:20 +00009240 FindParameter F;
9241 SCEVTraversal<FindParameter> ST(F);
9242 ST.visitAll(S);
9243
9244 return F.FoundParameter;
9245}
9246
9247// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9248static inline bool
9249containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9250 for (const SCEV *T : Terms)
9251 if (containsParameters(T))
9252 return true;
9253 return false;
9254}
9255
9256// Return the number of product terms in S.
9257static inline int numberOfTerms(const SCEV *S) {
9258 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9259 return Expr->getNumOperands();
9260 return 1;
9261}
9262
Sebastian Popa6e58602014-05-27 22:41:45 +00009263static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9264 if (isa<SCEVConstant>(T))
9265 return nullptr;
9266
9267 if (isa<SCEVUnknown>(T))
9268 return T;
9269
9270 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9271 SmallVector<const SCEV *, 2> Factors;
9272 for (const SCEV *Op : M->operands())
9273 if (!isa<SCEVConstant>(Op))
9274 Factors.push_back(Op);
9275
9276 return SE.getMulExpr(Factors);
9277 }
9278
9279 return T;
9280}
9281
9282/// Return the size of an element read or written by Inst.
9283const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9284 Type *Ty;
9285 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9286 Ty = Store->getValueOperand()->getType();
9287 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009288 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009289 else
9290 return nullptr;
9291
9292 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9293 return getSizeOfExpr(ETy, Ty);
9294}
9295
Sebastian Popa6e58602014-05-27 22:41:45 +00009296void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9297 SmallVectorImpl<const SCEV *> &Sizes,
9298 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009299 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009300 return;
9301
9302 // Early return when Terms do not contain parameters: we do not delinearize
9303 // non parametric SCEVs.
9304 if (!containsParameters(Terms))
9305 return;
9306
9307 DEBUG({
9308 dbgs() << "Terms:\n";
9309 for (const SCEV *T : Terms)
9310 dbgs() << *T << "\n";
9311 });
9312
9313 // Remove duplicates.
9314 std::sort(Terms.begin(), Terms.end());
9315 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9316
9317 // Put larger terms first.
9318 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9319 return numberOfTerms(LHS) > numberOfTerms(RHS);
9320 });
9321
Sebastian Popa6e58602014-05-27 22:41:45 +00009322 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9323
Tobias Grosser374bce02015-10-12 08:02:00 +00009324 // Try to divide all terms by the element size. If term is not divisible by
9325 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009326 for (const SCEV *&Term : Terms) {
9327 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009328 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009329 if (!Q->isZero())
9330 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009331 }
9332
9333 SmallVector<const SCEV *, 4> NewTerms;
9334
9335 // Remove constant factors.
9336 for (const SCEV *T : Terms)
9337 if (const SCEV *NewT = removeConstantFactors(SE, T))
9338 NewTerms.push_back(NewT);
9339
Sebastian Pop448712b2014-05-07 18:01:20 +00009340 DEBUG({
9341 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009342 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009343 dbgs() << *T << "\n";
9344 });
9345
Sebastian Popa6e58602014-05-27 22:41:45 +00009346 if (NewTerms.empty() ||
9347 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009348 Sizes.clear();
9349 return;
9350 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009351
Sebastian Popa6e58602014-05-27 22:41:45 +00009352 // The last element to be pushed into Sizes is the size of an element.
9353 Sizes.push_back(ElementSize);
9354
Sebastian Pop448712b2014-05-07 18:01:20 +00009355 DEBUG({
9356 dbgs() << "Sizes:\n";
9357 for (const SCEV *S : Sizes)
9358 dbgs() << *S << "\n";
9359 });
9360}
9361
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009362void ScalarEvolution::computeAccessFunctions(
9363 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9364 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009365
Sebastian Popb1a548f2014-05-12 19:01:53 +00009366 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009367 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009368 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009369
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009370 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009371 if (!AR->isAffine())
9372 return;
9373
9374 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009375 int Last = Sizes.size() - 1;
9376 for (int i = Last; i >= 0; i--) {
9377 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009378 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009379
9380 DEBUG({
9381 dbgs() << "Res: " << *Res << "\n";
9382 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9383 dbgs() << "Res divided by Sizes[i]:\n";
9384 dbgs() << "Quotient: " << *Q << "\n";
9385 dbgs() << "Remainder: " << *R << "\n";
9386 });
9387
9388 Res = Q;
9389
Sebastian Popa6e58602014-05-27 22:41:45 +00009390 // Do not record the last subscript corresponding to the size of elements in
9391 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009392 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009393
9394 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009395 if (isa<SCEVAddRecExpr>(R)) {
9396 Subscripts.clear();
9397 Sizes.clear();
9398 return;
9399 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009400
Sebastian Pop448712b2014-05-07 18:01:20 +00009401 continue;
9402 }
9403
9404 // Record the access function for the current subscript.
9405 Subscripts.push_back(R);
9406 }
9407
9408 // Also push in last position the remainder of the last division: it will be
9409 // the access function of the innermost dimension.
9410 Subscripts.push_back(Res);
9411
9412 std::reverse(Subscripts.begin(), Subscripts.end());
9413
9414 DEBUG({
9415 dbgs() << "Subscripts:\n";
9416 for (const SCEV *S : Subscripts)
9417 dbgs() << *S << "\n";
9418 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009419}
9420
Sebastian Popc62c6792013-11-12 22:47:20 +00009421/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9422/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009423/// is the offset start of the array. The SCEV->delinearize algorithm computes
9424/// the multiples of SCEV coefficients: that is a pattern matching of sub
9425/// expressions in the stride and base of a SCEV corresponding to the
9426/// computation of a GCD (greatest common divisor) of base and stride. When
9427/// SCEV->delinearize fails, it returns the SCEV unchanged.
9428///
9429/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9430///
9431/// void foo(long n, long m, long o, double A[n][m][o]) {
9432///
9433/// for (long i = 0; i < n; i++)
9434/// for (long j = 0; j < m; j++)
9435/// for (long k = 0; k < o; k++)
9436/// A[i][j][k] = 1.0;
9437/// }
9438///
9439/// the delinearization input is the following AddRec SCEV:
9440///
9441/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9442///
9443/// From this SCEV, we are able to say that the base offset of the access is %A
9444/// because it appears as an offset that does not divide any of the strides in
9445/// the loops:
9446///
9447/// CHECK: Base offset: %A
9448///
9449/// and then SCEV->delinearize determines the size of some of the dimensions of
9450/// the array as these are the multiples by which the strides are happening:
9451///
9452/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9453///
9454/// Note that the outermost dimension remains of UnknownSize because there are
9455/// no strides that would help identifying the size of the last dimension: when
9456/// the array has been statically allocated, one could compute the size of that
9457/// dimension by dividing the overall size of the array by the size of the known
9458/// dimensions: %m * %o * 8.
9459///
9460/// Finally delinearize provides the access functions for the array reference
9461/// that does correspond to A[i][j][k] of the above C testcase:
9462///
9463/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9464///
9465/// The testcases are checking the output of a function pass:
9466/// DelinearizationPass that walks through all loads and stores of a function
9467/// asking for the SCEV of the memory access with respect to all enclosing
9468/// loops, calling SCEV->delinearize on that and printing the results.
9469
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009470void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009471 SmallVectorImpl<const SCEV *> &Subscripts,
9472 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009473 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009474 // First step: collect parametric terms.
9475 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009476 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009477
Sebastian Popb1a548f2014-05-12 19:01:53 +00009478 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009479 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009480
Sebastian Pop448712b2014-05-07 18:01:20 +00009481 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009482 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009483
Sebastian Popb1a548f2014-05-12 19:01:53 +00009484 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009485 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009486
Sebastian Pop448712b2014-05-07 18:01:20 +00009487 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009488 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009489
Sebastian Pop28e6b972014-05-27 22:41:51 +00009490 if (Subscripts.empty())
9491 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009492
Sebastian Pop448712b2014-05-07 18:01:20 +00009493 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009494 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009495 dbgs() << "ArrayDecl[UnknownSize]";
9496 for (const SCEV *S : Sizes)
9497 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009498
Sebastian Pop444621a2014-05-09 22:45:02 +00009499 dbgs() << "\nArrayRef";
9500 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009501 dbgs() << "[" << *S << "]";
9502 dbgs() << "\n";
9503 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009504}
Chris Lattnerd934c702004-04-02 20:23:17 +00009505
9506//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009507// SCEVCallbackVH Class Implementation
9508//===----------------------------------------------------------------------===//
9509
Dan Gohmand33a0902009-05-19 19:22:47 +00009510void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009511 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009512 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9513 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009514 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009515 // this now dangles!
9516}
9517
Dan Gohman7a066722010-07-28 01:09:07 +00009518void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009519 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009520
Dan Gohman48f82222009-05-04 22:30:44 +00009521 // Forget all the expressions associated with users of the old value,
9522 // so that future queries will recompute the expressions using the new
9523 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009524 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009525 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009526 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009527 while (!Worklist.empty()) {
9528 User *U = Worklist.pop_back_val();
9529 // Deleting the Old value will cause this to dangle. Postpone
9530 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009531 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009532 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009533 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009534 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009535 if (PHINode *PN = dyn_cast<PHINode>(U))
9536 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009537 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009538 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009539 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009540 // Delete the Old value.
9541 if (PHINode *PN = dyn_cast<PHINode>(Old))
9542 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009543 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009544 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009545}
9546
Dan Gohmand33a0902009-05-19 19:22:47 +00009547ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009548 : CallbackVH(V), SE(se) {}
9549
9550//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009551// ScalarEvolution Class Implementation
9552//===----------------------------------------------------------------------===//
9553
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009554ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9555 AssumptionCache &AC, DominatorTree &DT,
9556 LoopInfo &LI)
9557 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9558 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009559 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9560 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009561 FirstUnknown(nullptr) {
9562
9563 // To use guards for proving predicates, we need to scan every instruction in
9564 // relevant basic blocks, and not just terminators. Doing this is a waste of
9565 // time if the IR does not actually contain any calls to
9566 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9567 //
9568 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9569 // to _add_ guards to the module when there weren't any before, and wants
9570 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9571 // efficient in lieu of being smart in that rather obscure case.
9572
9573 auto *GuardDecl = F.getParent()->getFunction(
9574 Intrinsic::getName(Intrinsic::experimental_guard));
9575 HasGuards = GuardDecl && !GuardDecl->use_empty();
9576}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009577
9578ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009579 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9580 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009581 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009582 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009583 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009584 PredicatedBackedgeTakenCounts(
9585 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009586 ConstantEvolutionLoopExitValue(
9587 std::move(Arg.ConstantEvolutionLoopExitValue)),
9588 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9589 LoopDispositions(std::move(Arg.LoopDispositions)),
9590 BlockDispositions(std::move(Arg.BlockDispositions)),
9591 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9592 SignedRanges(std::move(Arg.SignedRanges)),
9593 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009594 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009595 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9596 FirstUnknown(Arg.FirstUnknown) {
9597 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009598}
9599
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009600ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009601 // Iterate through all the SCEVUnknown instances and call their
9602 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009603 for (SCEVUnknown *U = FirstUnknown; U;) {
9604 SCEVUnknown *Tmp = U;
9605 U = U->Next;
9606 Tmp->~SCEVUnknown();
9607 }
Craig Topper9f008862014-04-15 04:59:12 +00009608 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009609
Wei Mia49559b2016-02-04 01:27:38 +00009610 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009611 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009612 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009613
9614 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9615 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009616 for (auto &BTCI : BackedgeTakenCounts)
9617 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009618 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9619 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009620
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009621 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009622 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009623 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009624}
9625
Dan Gohmanc8e23622009-04-21 23:15:49 +00009626bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009627 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009628}
9629
Dan Gohmanc8e23622009-04-21 23:15:49 +00009630static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009631 const Loop *L) {
9632 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009633 for (Loop *I : *L)
9634 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009635
Dan Gohmanbc694912010-01-09 18:17:45 +00009636 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009637 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009638 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009639
Dan Gohmancb0efec2009-12-18 01:14:11 +00009640 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009641 L->getExitBlocks(ExitBlocks);
9642 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009643 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009644
Dan Gohman0bddac12009-02-24 18:55:53 +00009645 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9646 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009647 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009648 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009649 }
9650
Dan Gohmanbc694912010-01-09 18:17:45 +00009651 OS << "\n"
9652 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009653 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009654 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009655
9656 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9657 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9658 } else {
9659 OS << "Unpredictable max backedge-taken count. ";
9660 }
9661
Silviu Baranga6f444df2016-04-08 14:29:09 +00009662 OS << "\n"
9663 "Loop ";
9664 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9665 OS << ": ";
9666
9667 SCEVUnionPredicate Pred;
9668 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9669 if (!isa<SCEVCouldNotCompute>(PBT)) {
9670 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9671 OS << " Predicates:\n";
9672 Pred.print(OS, 4);
9673 } else {
9674 OS << "Unpredictable predicated backedge-taken count. ";
9675 }
Dan Gohman69942932009-06-24 00:33:16 +00009676 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009677}
9678
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009679static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9680 switch (LD) {
9681 case ScalarEvolution::LoopVariant:
9682 return "Variant";
9683 case ScalarEvolution::LoopInvariant:
9684 return "Invariant";
9685 case ScalarEvolution::LoopComputable:
9686 return "Computable";
9687 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009688 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009689}
9690
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009691void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009692 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009693 // out SCEV values of all instructions that are interesting. Doing
9694 // this potentially causes it to create new SCEV objects though,
9695 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009696 // observable from outside the class though, so casting away the
9697 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009698 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009699
Dan Gohmanbc694912010-01-09 18:17:45 +00009700 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009701 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009702 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009703 for (Instruction &I : instructions(F))
9704 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9705 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009706 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009707 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009708 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009709 if (!isa<SCEVCouldNotCompute>(SV)) {
9710 OS << " U: ";
9711 SE.getUnsignedRange(SV).print(OS);
9712 OS << " S: ";
9713 SE.getSignedRange(SV).print(OS);
9714 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009715
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009716 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009717
Dan Gohmanaf752342009-07-07 17:06:11 +00009718 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009719 if (AtUse != SV) {
9720 OS << " --> ";
9721 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009722 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9723 OS << " U: ";
9724 SE.getUnsignedRange(AtUse).print(OS);
9725 OS << " S: ";
9726 SE.getSignedRange(AtUse).print(OS);
9727 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009728 }
9729
9730 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009731 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009732 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009733 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009734 OS << "<<Unknown>>";
9735 } else {
9736 OS << *ExitValue;
9737 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009738
9739 bool First = true;
9740 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9741 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009742 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009743 First = false;
9744 } else {
9745 OS << ", ";
9746 }
9747
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009748 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9749 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009750 }
9751
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009752 for (auto *InnerL : depth_first(L)) {
9753 if (InnerL == L)
9754 continue;
9755 if (First) {
9756 OS << "\t\t" "LoopDispositions: { ";
9757 First = false;
9758 } else {
9759 OS << ", ";
9760 }
9761
9762 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9763 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9764 }
9765
9766 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009767 }
9768
Chris Lattnerd934c702004-04-02 20:23:17 +00009769 OS << "\n";
9770 }
9771
Dan Gohmanbc694912010-01-09 18:17:45 +00009772 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009773 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009774 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009775 for (Loop *I : LI)
9776 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009777}
Dan Gohmane20f8242009-04-21 00:47:46 +00009778
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009779ScalarEvolution::LoopDisposition
9780ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009781 auto &Values = LoopDispositions[S];
9782 for (auto &V : Values) {
9783 if (V.getPointer() == L)
9784 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009785 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009786 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009787 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009788 auto &Values2 = LoopDispositions[S];
9789 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9790 if (V.getPointer() == L) {
9791 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009792 break;
9793 }
9794 }
9795 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009796}
9797
9798ScalarEvolution::LoopDisposition
9799ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009800 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009801 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009802 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009803 case scTruncate:
9804 case scZeroExtend:
9805 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009806 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009807 case scAddRecExpr: {
9808 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9809
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009810 // If L is the addrec's loop, it's computable.
9811 if (AR->getLoop() == L)
9812 return LoopComputable;
9813
Dan Gohmanafd6db92010-11-17 21:23:15 +00009814 // Add recurrences are never invariant in the function-body (null loop).
9815 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009816 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009817
9818 // This recurrence is variant w.r.t. L if L contains AR's loop.
9819 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009820 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009821
9822 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9823 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009824 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009825
9826 // This recurrence is variant w.r.t. L if any of its operands
9827 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009828 for (auto *Op : AR->operands())
9829 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009830 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009831
9832 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009833 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009834 }
9835 case scAddExpr:
9836 case scMulExpr:
9837 case scUMaxExpr:
9838 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009839 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009840 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9841 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009842 if (D == LoopVariant)
9843 return LoopVariant;
9844 if (D == LoopComputable)
9845 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009846 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009847 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009848 }
9849 case scUDivExpr: {
9850 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009851 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9852 if (LD == LoopVariant)
9853 return LoopVariant;
9854 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9855 if (RD == LoopVariant)
9856 return LoopVariant;
9857 return (LD == LoopInvariant && RD == LoopInvariant) ?
9858 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009859 }
9860 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009861 // All non-instruction values are loop invariant. All instructions are loop
9862 // invariant if they are not contained in the specified loop.
9863 // Instructions are never considered invariant in the function body
9864 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009865 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009866 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9867 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009868 case scCouldNotCompute:
9869 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009870 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009871 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009872}
9873
9874bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9875 return getLoopDisposition(S, L) == LoopInvariant;
9876}
9877
9878bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9879 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009880}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009881
Dan Gohman8ea83d82010-11-18 00:34:22 +00009882ScalarEvolution::BlockDisposition
9883ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009884 auto &Values = BlockDispositions[S];
9885 for (auto &V : Values) {
9886 if (V.getPointer() == BB)
9887 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009888 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009889 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009890 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009891 auto &Values2 = BlockDispositions[S];
9892 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9893 if (V.getPointer() == BB) {
9894 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009895 break;
9896 }
9897 }
9898 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009899}
9900
Dan Gohman8ea83d82010-11-18 00:34:22 +00009901ScalarEvolution::BlockDisposition
9902ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009903 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009904 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009905 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009906 case scTruncate:
9907 case scZeroExtend:
9908 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009909 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009910 case scAddRecExpr: {
9911 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009912 // to test for proper dominance too, because the instruction which
9913 // produces the addrec's value is a PHI, and a PHI effectively properly
9914 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009915 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009916 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009917 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009918
9919 // Fall through into SCEVNAryExpr handling.
9920 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009921 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009922 case scAddExpr:
9923 case scMulExpr:
9924 case scUMaxExpr:
9925 case scSMaxExpr: {
9926 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009927 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009928 for (const SCEV *NAryOp : NAry->operands()) {
9929 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009930 if (D == DoesNotDominateBlock)
9931 return DoesNotDominateBlock;
9932 if (D == DominatesBlock)
9933 Proper = false;
9934 }
9935 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009936 }
9937 case scUDivExpr: {
9938 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009939 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9940 BlockDisposition LD = getBlockDisposition(LHS, BB);
9941 if (LD == DoesNotDominateBlock)
9942 return DoesNotDominateBlock;
9943 BlockDisposition RD = getBlockDisposition(RHS, BB);
9944 if (RD == DoesNotDominateBlock)
9945 return DoesNotDominateBlock;
9946 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9947 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009948 }
9949 case scUnknown:
9950 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009951 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9952 if (I->getParent() == BB)
9953 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009954 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009955 return ProperlyDominatesBlock;
9956 return DoesNotDominateBlock;
9957 }
9958 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009959 case scCouldNotCompute:
9960 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009961 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009962 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009963}
9964
9965bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9966 return getBlockDisposition(S, BB) >= DominatesBlock;
9967}
9968
9969bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9970 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009971}
Dan Gohman534749b2010-11-17 22:27:42 +00009972
9973bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009974 // Search for a SCEV expression node within an expression tree.
9975 // Implements SCEVTraversal::Visitor.
9976 struct SCEVSearch {
9977 const SCEV *Node;
9978 bool IsFound;
9979
9980 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9981
9982 bool follow(const SCEV *S) {
9983 IsFound |= (S == Node);
9984 return !IsFound;
9985 }
9986 bool isDone() const { return IsFound; }
9987 };
9988
Andrew Trick365e31c2012-07-13 23:33:03 +00009989 SCEVSearch Search(Op);
9990 visitAll(S, Search);
9991 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009992}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009993
9994void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9995 ValuesAtScopes.erase(S);
9996 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009997 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009998 UnsignedRanges.erase(S);
9999 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +000010000 ExprValueMap.erase(S);
10001 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +000010002
Silviu Baranga6f444df2016-04-08 14:29:09 +000010003 auto RemoveSCEVFromBackedgeMap =
10004 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10005 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10006 BackedgeTakenInfo &BEInfo = I->second;
10007 if (BEInfo.hasOperand(S, this)) {
10008 BEInfo.clear();
10009 Map.erase(I++);
10010 } else
10011 ++I;
10012 }
10013 };
10014
10015 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10016 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +000010017}
Benjamin Kramer214935e2012-10-26 17:31:32 +000010018
10019typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010020
Alp Tokercb402912014-01-24 17:20:08 +000010021/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010022static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10023 size_t Pos = 0;
10024 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10025 Str.replace(Pos, From.size(), To.data(), To.size());
10026 Pos += To.size();
10027 }
10028}
10029
Benjamin Kramer214935e2012-10-26 17:31:32 +000010030/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10031static void
10032getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010033 std::string &S = Map[L];
10034 if (S.empty()) {
10035 raw_string_ostream OS(S);
10036 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010037
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010038 // false and 0 are semantically equivalent. This can happen in dead loops.
10039 replaceSubString(OS.str(), "false", "0");
10040 // Remove wrap flags, their use in SCEV is highly fragile.
10041 // FIXME: Remove this when SCEV gets smarter about them.
10042 replaceSubString(OS.str(), "<nw>", "");
10043 replaceSubString(OS.str(), "<nsw>", "");
10044 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010045 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010046
JF Bastien61ad8b32015-12-23 18:18:53 +000010047 for (auto *R : reverse(*L))
10048 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010049}
10050
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010051void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010052 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10053
10054 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10055 // FIXME: It would be much better to store actual values instead of strings,
10056 // but SCEV pointers will change if we drop the caches.
10057 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010058 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010059 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10060
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010061 // Gather stringified backedge taken counts for all loops using a fresh
10062 // ScalarEvolution object.
10063 ScalarEvolution SE2(F, TLI, AC, DT, LI);
10064 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10065 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010066
10067 // Now compare whether they're the same with and without caches. This allows
10068 // verifying that no pass changed the cache.
10069 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10070 "New loops suddenly appeared!");
10071
10072 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10073 OldE = BackedgeDumpsOld.end(),
10074 NewI = BackedgeDumpsNew.begin();
10075 OldI != OldE; ++OldI, ++NewI) {
10076 assert(OldI->first == NewI->first && "Loop order changed!");
10077
10078 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10079 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010080 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010081 // means that a pass is buggy or SCEV has to learn a new pattern but is
10082 // usually not harmful.
10083 if (OldI->second != NewI->second &&
10084 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010085 NewI->second.find("undef") == std::string::npos &&
10086 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010087 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010088 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010089 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010090 << "' changed from '" << OldI->second
10091 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010092 std::abort();
10093 }
10094 }
10095
10096 // TODO: Verify more things.
10097}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010098
Chandler Carruthb4faf132016-03-11 10:22:49 +000010099char ScalarEvolutionAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010100
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010101ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010102 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010103 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10104 AM.getResult<AssumptionAnalysis>(F),
10105 AM.getResult<DominatorTreeAnalysis>(F),
10106 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010107}
10108
10109PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010110ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010111 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010112 return PreservedAnalyses::all();
10113}
10114
10115INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10116 "Scalar Evolution Analysis", false, true)
10117INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10118INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10119INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10120INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10121INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10122 "Scalar Evolution Analysis", false, true)
10123char ScalarEvolutionWrapperPass::ID = 0;
10124
10125ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10126 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10127}
10128
10129bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10130 SE.reset(new ScalarEvolution(
10131 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10132 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10133 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10134 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10135 return false;
10136}
10137
10138void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10139
10140void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10141 SE->print(OS);
10142}
10143
10144void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10145 if (!VerifySCEV)
10146 return;
10147
10148 SE->verify();
10149}
10150
10151void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10152 AU.setPreservesAll();
10153 AU.addRequiredTransitive<AssumptionCacheTracker>();
10154 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10155 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10156 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10157}
Silviu Barangae3c05342015-11-02 14:41:02 +000010158
10159const SCEVPredicate *
10160ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10161 const SCEVConstant *RHS) {
10162 FoldingSetNodeID ID;
10163 // Unique this node based on the arguments
10164 ID.AddInteger(SCEVPredicate::P_Equal);
10165 ID.AddPointer(LHS);
10166 ID.AddPointer(RHS);
10167 void *IP = nullptr;
10168 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10169 return S;
10170 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10171 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10172 UniquePreds.InsertNode(Eq, IP);
10173 return Eq;
10174}
10175
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010176const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10177 const SCEVAddRecExpr *AR,
10178 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10179 FoldingSetNodeID ID;
10180 // Unique this node based on the arguments
10181 ID.AddInteger(SCEVPredicate::P_Wrap);
10182 ID.AddPointer(AR);
10183 ID.AddInteger(AddedFlags);
10184 void *IP = nullptr;
10185 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10186 return S;
10187 auto *OF = new (SCEVAllocator)
10188 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10189 UniquePreds.InsertNode(OF, IP);
10190 return OF;
10191}
10192
Benjamin Kramer83709b12015-11-16 09:01:28 +000010193namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010194
Silviu Barangae3c05342015-11-02 14:41:02 +000010195class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10196public:
Sanjoy Das807d33d2016-02-20 01:44:10 +000010197 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010198 // If Assume is true, rewrite is free to add further predicates to A
10199 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010200 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10201 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010202 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010203 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010204 }
10205
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010206 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10207 SCEVUnionPredicate &P, bool Assume)
10208 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010209
10210 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10211 auto ExprPreds = P.getPredicatesForExpr(Expr);
10212 for (auto *Pred : ExprPreds)
Sanjoy Dasb277a422016-06-15 06:53:55 +000010213 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
Silviu Barangae3c05342015-11-02 14:41:02 +000010214 if (IPred->getLHS() == Expr)
10215 return IPred->getRHS();
10216
10217 return Expr;
10218 }
10219
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010220 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10221 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010222 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010223 if (AR && AR->getLoop() == L && AR->isAffine()) {
10224 // This couldn't be folded because the operand didn't have the nuw
10225 // flag. Add the nusw flag as an assumption that we could make.
10226 const SCEV *Step = AR->getStepRecurrence(SE);
10227 Type *Ty = Expr->getType();
10228 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10229 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10230 SE.getSignExtendExpr(Step, Ty), L,
10231 AR->getNoWrapFlags());
10232 }
10233 return SE.getZeroExtendExpr(Operand, Expr->getType());
10234 }
10235
10236 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10237 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010238 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010239 if (AR && AR->getLoop() == L && AR->isAffine()) {
10240 // This couldn't be folded because the operand didn't have the nsw
10241 // flag. Add the nssw flag as an assumption that we could make.
10242 const SCEV *Step = AR->getStepRecurrence(SE);
10243 Type *Ty = Expr->getType();
10244 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10245 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10246 SE.getSignExtendExpr(Step, Ty), L,
10247 AR->getNoWrapFlags());
10248 }
10249 return SE.getSignExtendExpr(Operand, Expr->getType());
10250 }
10251
Silviu Barangae3c05342015-11-02 14:41:02 +000010252private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010253 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10254 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10255 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10256 if (!Assume) {
10257 // Check if we've already made this assumption.
10258 if (P.implies(A))
10259 return true;
10260 return false;
10261 }
10262 P.add(A);
10263 return true;
10264 }
10265
Silviu Barangae3c05342015-11-02 14:41:02 +000010266 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010267 const Loop *L;
10268 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +000010269};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010270} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010271
Sanjoy Das807d33d2016-02-20 01:44:10 +000010272const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010273 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +000010274 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010275}
10276
Silviu Barangad68ed852016-03-23 15:29:30 +000010277const SCEVAddRecExpr *
Sanjoy Das807d33d2016-02-20 01:44:10 +000010278ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
10279 SCEVUnionPredicate &Preds) {
Silviu Barangad68ed852016-03-23 15:29:30 +000010280 SCEVUnionPredicate TransformPreds;
10281 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true);
10282 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10283
10284 if (!AddRec)
10285 return nullptr;
10286
10287 // Since the transformation was successful, we can now transfer the SCEV
10288 // predicates.
10289 Preds.add(&TransformPreds);
10290 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010291}
10292
10293/// SCEV predicates
10294SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10295 SCEVPredicateKind Kind)
10296 : FastID(ID), Kind(Kind) {}
10297
10298SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10299 const SCEVUnknown *LHS,
10300 const SCEVConstant *RHS)
10301 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10302
10303bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010304 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010305
10306 if (!Op)
10307 return false;
10308
10309 return Op->LHS == LHS && Op->RHS == RHS;
10310}
10311
10312bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10313
10314const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10315
10316void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10317 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10318}
10319
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010320SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10321 const SCEVAddRecExpr *AR,
10322 IncrementWrapFlags Flags)
10323 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10324
10325const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10326
10327bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10328 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10329
10330 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10331}
10332
10333bool SCEVWrapPredicate::isAlwaysTrue() const {
10334 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10335 IncrementWrapFlags IFlags = Flags;
10336
10337 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10338 IFlags = clearFlags(IFlags, IncrementNSSW);
10339
10340 return IFlags == IncrementAnyWrap;
10341}
10342
10343void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10344 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10345 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10346 OS << "<nusw>";
10347 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10348 OS << "<nssw>";
10349 OS << "\n";
10350}
10351
10352SCEVWrapPredicate::IncrementWrapFlags
10353SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10354 ScalarEvolution &SE) {
10355 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10356 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10357
10358 // We can safely transfer the NSW flag as NSSW.
10359 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10360 ImpliedFlags = IncrementNSSW;
10361
10362 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10363 // If the increment is positive, the SCEV NUW flag will also imply the
10364 // WrapPredicate NUSW flag.
10365 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10366 if (Step->getValue()->getValue().isNonNegative())
10367 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10368 }
10369
10370 return ImpliedFlags;
10371}
10372
Silviu Barangae3c05342015-11-02 14:41:02 +000010373/// Union predicates don't get cached so create a dummy set ID for it.
10374SCEVUnionPredicate::SCEVUnionPredicate()
10375 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10376
10377bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010378 return all_of(Preds,
10379 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010380}
10381
10382ArrayRef<const SCEVPredicate *>
10383SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10384 auto I = SCEVToPreds.find(Expr);
10385 if (I == SCEVToPreds.end())
10386 return ArrayRef<const SCEVPredicate *>();
10387 return I->second;
10388}
10389
10390bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010391 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010392 return all_of(Set->Preds,
10393 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010394
10395 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10396 if (ScevPredsIt == SCEVToPreds.end())
10397 return false;
10398 auto &SCEVPreds = ScevPredsIt->second;
10399
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010400 return any_of(SCEVPreds,
10401 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010402}
10403
10404const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10405
10406void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10407 for (auto Pred : Preds)
10408 Pred->print(OS, Depth);
10409}
10410
10411void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010412 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010413 for (auto Pred : Set->Preds)
10414 add(Pred);
10415 return;
10416 }
10417
10418 if (implies(N))
10419 return;
10420
10421 const SCEV *Key = N->getExpr();
10422 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10423 " associated expression!");
10424
10425 SCEVToPreds[Key].push_back(N);
10426 Preds.push_back(N);
10427}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010428
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010429PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10430 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010431 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010432
10433const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10434 const SCEV *Expr = SE.getSCEV(V);
10435 RewriteEntry &Entry = RewriteMap[Expr];
10436
10437 // If we already have an entry and the version matches, return it.
10438 if (Entry.second && Generation == Entry.first)
10439 return Entry.second;
10440
10441 // We found an entry but it's stale. Rewrite the stale entry
10442 // acording to the current predicate.
10443 if (Entry.second)
10444 Expr = Entry.second;
10445
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010446 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010447 Entry = {Generation, NewSCEV};
10448
10449 return NewSCEV;
10450}
10451
Silviu Baranga6f444df2016-04-08 14:29:09 +000010452const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10453 if (!BackedgeCount) {
10454 SCEVUnionPredicate BackedgePred;
10455 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10456 addPredicate(BackedgePred);
10457 }
10458 return BackedgeCount;
10459}
10460
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010461void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10462 if (Preds.implies(&Pred))
10463 return;
10464 Preds.add(&Pred);
10465 updateGeneration();
10466}
10467
10468const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10469 return Preds;
10470}
10471
10472void PredicatedScalarEvolution::updateGeneration() {
10473 // If the generation number wrapped recompute everything.
10474 if (++Generation == 0) {
10475 for (auto &II : RewriteMap) {
10476 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010477 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010478 }
10479 }
10480}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010481
10482void PredicatedScalarEvolution::setNoOverflow(
10483 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10484 const SCEV *Expr = getSCEV(V);
10485 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10486
10487 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10488
10489 // Clear the statically implied flags.
10490 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10491 addPredicate(*SE.getWrapPredicate(AR, Flags));
10492
10493 auto II = FlagsMap.insert({V, Flags});
10494 if (!II.second)
10495 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10496}
10497
10498bool PredicatedScalarEvolution::hasNoOverflow(
10499 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10500 const SCEV *Expr = getSCEV(V);
10501 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10502
10503 Flags = SCEVWrapPredicate::clearFlags(
10504 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10505
10506 auto II = FlagsMap.find(V);
10507
10508 if (II != FlagsMap.end())
10509 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10510
10511 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10512}
10513
Silviu Barangad68ed852016-03-23 15:29:30 +000010514const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010515 const SCEV *Expr = this->getSCEV(V);
Silviu Barangad68ed852016-03-23 15:29:30 +000010516 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10517
10518 if (!New)
10519 return nullptr;
10520
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010521 updateGeneration();
10522 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10523 return New;
10524}
10525
Silviu Baranga6f444df2016-04-08 14:29:09 +000010526PredicatedScalarEvolution::PredicatedScalarEvolution(
10527 const PredicatedScalarEvolution &Init)
10528 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10529 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010530 for (const auto &I : Init.FlagsMap)
10531 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010532}
Silviu Barangab77365b2016-04-14 16:08:45 +000010533
10534void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10535 // For each block.
10536 for (auto *BB : L.getBlocks())
10537 for (auto &I : *BB) {
10538 if (!SE.isSCEVable(I.getType()))
10539 continue;
10540
10541 auto *Expr = SE.getSCEV(&I);
10542 auto II = RewriteMap.find(Expr);
10543
10544 if (II == RewriteMap.end())
10545 continue;
10546
10547 // Don't print things that are not interesting.
10548 if (II->second.second == Expr)
10549 continue;
10550
10551 OS.indent(Depth) << "[PSE]" << I << ":\n";
10552 OS.indent(Depth + 2) << *Expr << "\n";
10553 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10554 }
10555}