blob: 4e3e2b5442a75d03de14d60f233d04253f2651e9 [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
Sanjoy Dasf8570812016-05-29 00:38:22 +00003381/// Return the Value set from S.
Wei Mia49559b2016-02-04 01:27:38 +00003382SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3383 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3384 if (SI == ExprValueMap.end())
3385 return nullptr;
3386#ifndef NDEBUG
3387 if (VerifySCEVMap) {
3388 // Check there is no dangling Value in the set returned.
3389 for (const auto &VE : SI->second)
3390 assert(ValueExprMap.count(VE));
3391 }
3392#endif
3393 return &SI->second;
3394}
3395
Sanjoy Dasf8570812016-05-29 00:38:22 +00003396/// Erase Value from ValueExprMap and ExprValueMap. If ValueExprMap.erase(V) is
3397/// not used together with forgetMemoizedResults(S), eraseValueFromMap should be
3398/// used instead to ensure whenever V->S is removed from ValueExprMap, V is also
3399/// removed from the set of ExprValueMap[S].
Wei Mia49559b2016-02-04 01:27:38 +00003400void ScalarEvolution::eraseValueFromMap(Value *V) {
3401 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3402 if (I != ValueExprMap.end()) {
3403 const SCEV *S = I->second;
3404 SetVector<Value *> *SV = getSCEVValues(S);
3405 // Remove V from the set of ExprValueMap[S]
3406 if (SV)
3407 SV->remove(V);
3408 ValueExprMap.erase(V);
3409 }
3410}
3411
Sanjoy Dasf8570812016-05-29 00:38:22 +00003412/// Return an existing SCEV if it exists, otherwise analyze the expression and
3413/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003414const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003415 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003416
Jingyue Wu42f1d672015-07-28 18:22:40 +00003417 const SCEV *S = getExistingSCEV(V);
3418 if (S == nullptr) {
3419 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003420 // During PHI resolution, it is possible to create two SCEVs for the same
3421 // V, so it is needed to double check whether V->S is inserted into
3422 // ValueExprMap before insert S->V into ExprValueMap.
3423 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003424 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mia49559b2016-02-04 01:27:38 +00003425 if (Pair.second)
3426 ExprValueMap[S].insert(V);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003427 }
3428 return S;
3429}
3430
3431const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3432 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3433
Shuxin Yangefc4c012013-07-08 17:33:13 +00003434 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3435 if (I != ValueExprMap.end()) {
3436 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003437 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003438 return S;
Wei Mia49559b2016-02-04 01:27:38 +00003439 forgetMemoizedResults(S);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003440 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003441 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003442 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003443}
3444
Sanjoy Dasf8570812016-05-29 00:38:22 +00003445/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003446///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003447const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3448 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003449 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003450 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003451 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003452
Chris Lattner229907c2011-07-18 04:54:35 +00003453 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003454 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003455 return getMulExpr(
3456 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003457}
3458
Sanjoy Dasf8570812016-05-29 00:38:22 +00003459/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003460const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003461 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003462 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003463 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003464
Chris Lattner229907c2011-07-18 04:54:35 +00003465 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003466 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003467 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003468 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003469 return getMinusSCEV(AllOnes, V);
3470}
3471
Chris Lattnerfc877522011-01-09 22:26:35 +00003472const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003473 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003474 // Fast path: X - X --> 0.
3475 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003476 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003477
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003478 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3479 // makes it so that we cannot make much use of NUW.
3480 auto AddFlags = SCEV::FlagAnyWrap;
3481 const bool RHSIsNotMinSigned =
3482 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3483 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3484 // Let M be the minimum representable signed value. Then (-1)*RHS
3485 // signed-wraps if and only if RHS is M. That can happen even for
3486 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3487 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3488 // (-1)*RHS, we need to prove that RHS != M.
3489 //
3490 // If LHS is non-negative and we know that LHS - RHS does not
3491 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3492 // either by proving that RHS > M or that LHS >= 0.
3493 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3494 AddFlags = SCEV::FlagNSW;
3495 }
3496 }
3497
3498 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3499 // RHS is NSW and LHS >= 0.
3500 //
3501 // The difficulty here is that the NSW flag may have been proven
3502 // relative to a loop that is to be found in a recurrence in LHS and
3503 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3504 // larger scope than intended.
3505 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3506
3507 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003508}
3509
Dan Gohmanaf752342009-07-07 17:06:11 +00003510const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003511ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3512 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003513 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3514 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003515 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003516 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003517 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003518 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003519 return getTruncateExpr(V, Ty);
3520 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003521}
3522
Dan Gohmanaf752342009-07-07 17:06:11 +00003523const SCEV *
3524ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003525 Type *Ty) {
3526 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003527 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3528 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003529 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003530 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003531 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003532 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003533 return getTruncateExpr(V, Ty);
3534 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003535}
3536
Dan Gohmanaf752342009-07-07 17:06:11 +00003537const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003538ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3539 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003540 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3541 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003542 "Cannot noop or zero extend with non-integer arguments!");
3543 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3544 "getNoopOrZeroExtend cannot truncate!");
3545 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3546 return V; // No conversion
3547 return getZeroExtendExpr(V, Ty);
3548}
3549
Dan Gohmanaf752342009-07-07 17:06:11 +00003550const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003551ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3552 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003553 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3554 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003555 "Cannot noop or sign extend with non-integer arguments!");
3556 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3557 "getNoopOrSignExtend cannot truncate!");
3558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3559 return V; // No conversion
3560 return getSignExtendExpr(V, Ty);
3561}
3562
Dan Gohmanaf752342009-07-07 17:06:11 +00003563const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003564ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3565 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003566 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3567 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003568 "Cannot noop or any extend with non-integer arguments!");
3569 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3570 "getNoopOrAnyExtend cannot truncate!");
3571 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3572 return V; // No conversion
3573 return getAnyExtendExpr(V, Ty);
3574}
3575
Dan Gohmanaf752342009-07-07 17:06:11 +00003576const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003577ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3578 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003579 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3580 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003581 "Cannot truncate or noop with non-integer arguments!");
3582 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3583 "getTruncateOrNoop cannot extend!");
3584 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3585 return V; // No conversion
3586 return getTruncateExpr(V, Ty);
3587}
3588
Dan Gohmanabd17092009-06-24 14:49:00 +00003589const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3590 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003591 const SCEV *PromotedLHS = LHS;
3592 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003593
3594 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3595 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3596 else
3597 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3598
3599 return getUMaxExpr(PromotedLHS, PromotedRHS);
3600}
3601
Dan Gohmanabd17092009-06-24 14:49:00 +00003602const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3603 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003604 const SCEV *PromotedLHS = LHS;
3605 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003606
3607 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3608 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3609 else
3610 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3611
3612 return getUMinExpr(PromotedLHS, PromotedRHS);
3613}
3614
Andrew Trick87716c92011-03-17 23:51:11 +00003615const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3616 // A pointer operand may evaluate to a nonpointer expression, such as null.
3617 if (!V->getType()->isPointerTy())
3618 return V;
3619
3620 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3621 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003622 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003623 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003624 for (const SCEV *NAryOp : NAry->operands()) {
3625 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003626 // Cannot find the base of an expression with multiple pointer operands.
3627 if (PtrOp)
3628 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003629 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003630 }
3631 }
3632 if (!PtrOp)
3633 return V;
3634 return getPointerBase(PtrOp);
3635 }
3636 return V;
3637}
3638
Sanjoy Dasf8570812016-05-29 00:38:22 +00003639/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003640static void
3641PushDefUseChildren(Instruction *I,
3642 SmallVectorImpl<Instruction *> &Worklist) {
3643 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003644 for (User *U : I->users())
3645 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003646}
3647
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003648void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003649 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003650 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003651
Dan Gohman0b89dff2009-07-25 01:13:03 +00003652 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003653 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003654 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003655 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003656 if (!Visited.insert(I).second)
3657 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003658
Sanjoy Das63914592015-10-18 00:29:20 +00003659 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003660 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003661 const SCEV *Old = It->second;
3662
Dan Gohman0b89dff2009-07-25 01:13:03 +00003663 // Short-circuit the def-use traversal if the symbolic name
3664 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003665 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003666 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003667
Dan Gohman0b89dff2009-07-25 01:13:03 +00003668 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003669 // structure, it's a PHI that's in the progress of being computed
3670 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3671 // additional loop trip count information isn't going to change anything.
3672 // In the second case, createNodeForPHI will perform the necessary
3673 // updates on its own when it gets to that point. In the third, we do
3674 // want to forget the SCEVUnknown.
3675 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003676 !isa<SCEVUnknown>(Old) ||
3677 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003678 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003679 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003680 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003681 }
3682
3683 PushDefUseChildren(I, Worklist);
3684 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003685}
Chris Lattnerd934c702004-04-02 20:23:17 +00003686
Benjamin Kramer83709b12015-11-16 09:01:28 +00003687namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003688class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3689public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003690 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003691 ScalarEvolution &SE) {
3692 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003693 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003694 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3695 }
3696
3697 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3698 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3699
3700 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3701 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3702 Valid = false;
3703 return Expr;
3704 }
3705
3706 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3707 // Only allow AddRecExprs for this loop.
3708 if (Expr->getLoop() == L)
3709 return Expr->getStart();
3710 Valid = false;
3711 return Expr;
3712 }
3713
3714 bool isValid() { return Valid; }
3715
3716private:
3717 const Loop *L;
3718 bool Valid;
3719};
3720
3721class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3722public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003723 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003724 ScalarEvolution &SE) {
3725 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003726 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003727 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3728 }
3729
3730 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3731 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3732
3733 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3734 // Only allow AddRecExprs for this loop.
3735 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3736 Valid = false;
3737 return Expr;
3738 }
3739
3740 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3741 if (Expr->getLoop() == L && Expr->isAffine())
3742 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3743 Valid = false;
3744 return Expr;
3745 }
3746 bool isValid() { return Valid; }
3747
3748private:
3749 const Loop *L;
3750 bool Valid;
3751};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003752} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003753
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003754SCEV::NoWrapFlags
3755ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3756 if (!AR->isAffine())
3757 return SCEV::FlagAnyWrap;
3758
3759 typedef OverflowingBinaryOperator OBO;
3760 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3761
3762 if (!AR->hasNoSignedWrap()) {
3763 ConstantRange AddRecRange = getSignedRange(AR);
3764 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3765
3766 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3767 Instruction::Add, IncRange, OBO::NoSignedWrap);
3768 if (NSWRegion.contains(AddRecRange))
3769 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3770 }
3771
3772 if (!AR->hasNoUnsignedWrap()) {
3773 ConstantRange AddRecRange = getUnsignedRange(AR);
3774 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3775
3776 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3777 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3778 if (NUWRegion.contains(AddRecRange))
3779 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3780 }
3781
3782 return Result;
3783}
3784
Sanjoy Das118d9192016-03-31 05:14:22 +00003785namespace {
3786/// Represents an abstract binary operation. This may exist as a
3787/// normal instruction or constant expression, or may have been
3788/// derived from an expression tree.
3789struct BinaryOp {
3790 unsigned Opcode;
3791 Value *LHS;
3792 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003793 bool IsNSW;
3794 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003795
3796 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3797 /// constant expression.
3798 Operator *Op;
3799
3800 explicit BinaryOp(Operator *Op)
3801 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003802 IsNSW(false), IsNUW(false), Op(Op) {
3803 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3804 IsNSW = OBO->hasNoSignedWrap();
3805 IsNUW = OBO->hasNoUnsignedWrap();
3806 }
3807 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003808
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003809 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3810 bool IsNUW = false)
3811 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3812 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003813};
3814}
3815
3816
3817/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003818static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003819 auto *Op = dyn_cast<Operator>(V);
3820 if (!Op)
3821 return None;
3822
3823 // Implementation detail: all the cleverness here should happen without
3824 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3825 // SCEV expressions when possible, and we should not break that.
3826
3827 switch (Op->getOpcode()) {
3828 case Instruction::Add:
3829 case Instruction::Sub:
3830 case Instruction::Mul:
3831 case Instruction::UDiv:
3832 case Instruction::And:
3833 case Instruction::Or:
3834 case Instruction::AShr:
3835 case Instruction::Shl:
3836 return BinaryOp(Op);
3837
3838 case Instruction::Xor:
3839 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3840 // If the RHS of the xor is a signbit, then this is just an add.
3841 // Instcombine turns add of signbit into xor as a strength reduction step.
3842 if (RHSC->getValue().isSignBit())
3843 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3844 return BinaryOp(Op);
3845
3846 case Instruction::LShr:
3847 // Turn logical shift right of a constant into a unsigned divide.
3848 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3849 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3850
3851 // If the shift count is not less than the bitwidth, the result of
3852 // the shift is undefined. Don't try to analyze it, because the
3853 // resolution chosen here may differ from the resolution chosen in
3854 // other parts of the compiler.
3855 if (SA->getValue().ult(BitWidth)) {
3856 Constant *X =
3857 ConstantInt::get(SA->getContext(),
3858 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3859 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3860 }
3861 }
3862 return BinaryOp(Op);
3863
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003864 case Instruction::ExtractValue: {
3865 auto *EVI = cast<ExtractValueInst>(Op);
3866 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3867 break;
3868
3869 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3870 if (!CI)
3871 break;
3872
3873 if (auto *F = CI->getCalledFunction())
3874 switch (F->getIntrinsicID()) {
3875 case Intrinsic::sadd_with_overflow:
3876 case Intrinsic::uadd_with_overflow: {
3877 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3878 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3879 CI->getArgOperand(1));
3880
3881 // Now that we know that all uses of the arithmetic-result component of
3882 // CI are guarded by the overflow check, we can go ahead and pretend
3883 // that the arithmetic is non-overflowing.
3884 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3885 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3886 CI->getArgOperand(1), /* IsNSW = */ true,
3887 /* IsNUW = */ false);
3888 else
3889 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3890 CI->getArgOperand(1), /* IsNSW = */ false,
3891 /* IsNUW*/ true);
3892 }
3893
3894 case Intrinsic::ssub_with_overflow:
3895 case Intrinsic::usub_with_overflow:
3896 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3897 CI->getArgOperand(1));
3898
3899 case Intrinsic::smul_with_overflow:
3900 case Intrinsic::umul_with_overflow:
3901 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3902 CI->getArgOperand(1));
3903 default:
3904 break;
3905 }
3906 }
3907
Sanjoy Das118d9192016-03-31 05:14:22 +00003908 default:
3909 break;
3910 }
3911
3912 return None;
3913}
3914
Sanjoy Das55015d22015-10-02 23:09:44 +00003915const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3916 const Loop *L = LI.getLoopFor(PN->getParent());
3917 if (!L || L->getHeader() != PN->getParent())
3918 return nullptr;
3919
3920 // The loop may have multiple entrances or multiple exits; we can analyze
3921 // this phi as an addrec if it has a unique entry value and a unique
3922 // backedge value.
3923 Value *BEValueV = nullptr, *StartValueV = nullptr;
3924 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3925 Value *V = PN->getIncomingValue(i);
3926 if (L->contains(PN->getIncomingBlock(i))) {
3927 if (!BEValueV) {
3928 BEValueV = V;
3929 } else if (BEValueV != V) {
3930 BEValueV = nullptr;
3931 break;
3932 }
3933 } else if (!StartValueV) {
3934 StartValueV = V;
3935 } else if (StartValueV != V) {
3936 StartValueV = nullptr;
3937 break;
3938 }
3939 }
3940 if (BEValueV && StartValueV) {
3941 // While we are analyzing this PHI node, handle its value symbolically.
3942 const SCEV *SymbolicName = getUnknown(PN);
3943 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3944 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003945 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003946
3947 // Using this symbolic name for the PHI, analyze the value coming around
3948 // the back-edge.
3949 const SCEV *BEValue = getSCEV(BEValueV);
3950
3951 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3952 // has a special value for the first iteration of the loop.
3953
3954 // If the value coming around the backedge is an add with the symbolic
3955 // value we just inserted, then we found a simple induction variable!
3956 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3957 // If there is a single occurrence of the symbolic value, replace it
3958 // with a recurrence.
3959 unsigned FoundIndex = Add->getNumOperands();
3960 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3961 if (Add->getOperand(i) == SymbolicName)
3962 if (FoundIndex == e) {
3963 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00003964 break;
3965 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003966
3967 if (FoundIndex != Add->getNumOperands()) {
3968 // Create an add with everything but the specified operand.
3969 SmallVector<const SCEV *, 8> Ops;
3970 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3971 if (i != FoundIndex)
3972 Ops.push_back(Add->getOperand(i));
3973 const SCEV *Accum = getAddExpr(Ops);
3974
3975 // This is not a valid addrec if the step amount is varying each
3976 // loop iteration, but is not itself an addrec in this loop.
3977 if (isLoopInvariant(Accum, L) ||
3978 (isa<SCEVAddRecExpr>(Accum) &&
3979 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3980 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3981
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003982 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003983 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
3984 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00003985 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003986 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00003987 Flags = setFlags(Flags, SCEV::FlagNSW);
3988 }
3989 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3990 // If the increment is an inbounds GEP, then we know the address
3991 // space cannot be wrapped around. We cannot make any guarantee
3992 // about signed or unsigned overflow because pointers are
3993 // unsigned but we may have a negative index from the base
3994 // pointer. We can guarantee that no unsigned wrap occurs if the
3995 // indices form a positive value.
3996 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3997 Flags = setFlags(Flags, SCEV::FlagNW);
3998
3999 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4000 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4001 Flags = setFlags(Flags, SCEV::FlagNUW);
4002 }
4003
4004 // We cannot transfer nuw and nsw flags from subtraction
4005 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4006 // for instance.
4007 }
4008
4009 const SCEV *StartVal = getSCEV(StartValueV);
4010 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4011
Sanjoy Das55015d22015-10-02 23:09:44 +00004012 // Okay, for the entire analysis of this edge we assumed the PHI
4013 // to be symbolic. We now need to go back and purge all of the
4014 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004015 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004016 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004017
4018 // We can add Flags to the post-inc expression only if we
4019 // know that it us *undefined behavior* for BEValueV to
4020 // overflow.
4021 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4022 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4023 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4024
Sanjoy Das55015d22015-10-02 23:09:44 +00004025 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004026 }
4027 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004028 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004029 // Otherwise, this could be a loop like this:
4030 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4031 // In this case, j = {1,+,1} and BEValue is j.
4032 // Because the other in-value of i (0) fits the evolution of BEValue
4033 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004034 //
4035 // We can generalize this saying that i is the shifted value of BEValue
4036 // by one iteration:
4037 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4038 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4039 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4040 if (Shifted != getCouldNotCompute() &&
4041 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004042 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004043 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004044 // Okay, for the entire analysis of this edge we assumed the PHI
4045 // to be symbolic. We now need to go back and purge all of the
4046 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004047 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004048 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4049 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004050 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004051 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004052 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004053
4054 // Remove the temporary PHI node SCEV that has been inserted while intending
4055 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4056 // as it will prevent later (possibly simpler) SCEV expressions to be added
4057 // to the ValueExprMap.
4058 ValueExprMap.erase(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004059 }
4060
4061 return nullptr;
4062}
4063
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004064// Checks if the SCEV S is available at BB. S is considered available at BB
4065// if S can be materialized at BB without introducing a fault.
4066static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4067 BasicBlock *BB) {
4068 struct CheckAvailable {
4069 bool TraversalDone = false;
4070 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004071
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004072 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4073 BasicBlock *BB = nullptr;
4074 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004075
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004076 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4077 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004078
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004079 bool setUnavailable() {
4080 TraversalDone = true;
4081 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004082 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004083 }
4084
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004085 bool follow(const SCEV *S) {
4086 switch (S->getSCEVType()) {
4087 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4088 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004089 // These expressions are available if their operand(s) is/are.
4090 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004091
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004092 case scAddRecExpr: {
4093 // We allow add recurrences that are on the loop BB is in, or some
4094 // outer loop. This guarantees availability because the value of the
4095 // add recurrence at BB is simply the "current" value of the induction
4096 // variable. We can relax this in the future; for instance an add
4097 // recurrence on a sibling dominating loop is also available at BB.
4098 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4099 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004100 return true;
4101
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004102 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004103 }
4104
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004105 case scUnknown: {
4106 // For SCEVUnknown, we check for simple dominance.
4107 const auto *SU = cast<SCEVUnknown>(S);
4108 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004109
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004110 if (isa<Argument>(V))
4111 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004112
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004113 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4114 return false;
4115
4116 return setUnavailable();
4117 }
4118
4119 case scUDivExpr:
4120 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004121 // We do not try to smart about these at all.
4122 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004123 }
4124 llvm_unreachable("switch should be fully covered!");
4125 }
4126
4127 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004128 };
4129
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004130 CheckAvailable CA(L, BB, DT);
4131 SCEVTraversal<CheckAvailable> ST(CA);
4132
4133 ST.visitAll(S);
4134 return CA.Available;
4135}
4136
4137// Try to match a control flow sequence that branches out at BI and merges back
4138// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4139// match.
4140static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4141 Value *&C, Value *&LHS, Value *&RHS) {
4142 C = BI->getCondition();
4143
4144 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4145 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4146
4147 if (!LeftEdge.isSingleEdge())
4148 return false;
4149
4150 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4151
4152 Use &LeftUse = Merge->getOperandUse(0);
4153 Use &RightUse = Merge->getOperandUse(1);
4154
4155 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4156 LHS = LeftUse;
4157 RHS = RightUse;
4158 return true;
4159 }
4160
4161 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4162 LHS = RightUse;
4163 RHS = LeftUse;
4164 return true;
4165 }
4166
4167 return false;
4168}
4169
4170const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004171 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004172 const Loop *L = LI.getLoopFor(PN->getParent());
4173
Sanjoy Das337d4782015-10-31 23:21:40 +00004174 // We don't want to break LCSSA, even in a SCEV expression tree.
4175 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4176 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4177 return nullptr;
4178
Sanjoy Das55015d22015-10-02 23:09:44 +00004179 // Try to match
4180 //
4181 // br %cond, label %left, label %right
4182 // left:
4183 // br label %merge
4184 // right:
4185 // br label %merge
4186 // merge:
4187 // V = phi [ %x, %left ], [ %y, %right ]
4188 //
4189 // as "select %cond, %x, %y"
4190
4191 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4192 assert(IDom && "At least the entry block should dominate PN");
4193
4194 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4195 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4196
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004197 if (BI && BI->isConditional() &&
4198 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4199 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4200 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004201 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4202 }
4203
4204 return nullptr;
4205}
4206
4207const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4208 if (const SCEV *S = createAddRecFromPHI(PN))
4209 return S;
4210
4211 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4212 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004213
Dan Gohmana9c205c2010-02-25 06:57:05 +00004214 // If the PHI has a single incoming value, follow that value, unless the
4215 // PHI's incoming blocks are in a different loop, in which case doing so
4216 // risks breaking LCSSA form. Instcombine would normally zap these, but
4217 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004218 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004219 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004220 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004221
Chris Lattnerd934c702004-04-02 20:23:17 +00004222 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004223 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004224}
4225
Sanjoy Das55015d22015-10-02 23:09:44 +00004226const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4227 Value *Cond,
4228 Value *TrueVal,
4229 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004230 // Handle "constant" branch or select. This can occur for instance when a
4231 // loop pass transforms an inner loop and moves on to process the outer loop.
4232 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4233 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4234
Sanjoy Dasd0671342015-10-02 19:39:59 +00004235 // Try to match some simple smax or umax patterns.
4236 auto *ICI = dyn_cast<ICmpInst>(Cond);
4237 if (!ICI)
4238 return getUnknown(I);
4239
4240 Value *LHS = ICI->getOperand(0);
4241 Value *RHS = ICI->getOperand(1);
4242
4243 switch (ICI->getPredicate()) {
4244 case ICmpInst::ICMP_SLT:
4245 case ICmpInst::ICMP_SLE:
4246 std::swap(LHS, RHS);
4247 // fall through
4248 case ICmpInst::ICMP_SGT:
4249 case ICmpInst::ICMP_SGE:
4250 // a >s b ? a+x : b+x -> smax(a, b)+x
4251 // a >s b ? b+x : a+x -> smin(a, b)+x
4252 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4253 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4254 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4255 const SCEV *LA = getSCEV(TrueVal);
4256 const SCEV *RA = getSCEV(FalseVal);
4257 const SCEV *LDiff = getMinusSCEV(LA, LS);
4258 const SCEV *RDiff = getMinusSCEV(RA, RS);
4259 if (LDiff == RDiff)
4260 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4261 LDiff = getMinusSCEV(LA, RS);
4262 RDiff = getMinusSCEV(RA, LS);
4263 if (LDiff == RDiff)
4264 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4265 }
4266 break;
4267 case ICmpInst::ICMP_ULT:
4268 case ICmpInst::ICMP_ULE:
4269 std::swap(LHS, RHS);
4270 // fall through
4271 case ICmpInst::ICMP_UGT:
4272 case ICmpInst::ICMP_UGE:
4273 // a >u b ? a+x : b+x -> umax(a, b)+x
4274 // a >u b ? b+x : a+x -> umin(a, b)+x
4275 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4276 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4277 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4278 const SCEV *LA = getSCEV(TrueVal);
4279 const SCEV *RA = getSCEV(FalseVal);
4280 const SCEV *LDiff = getMinusSCEV(LA, LS);
4281 const SCEV *RDiff = getMinusSCEV(RA, RS);
4282 if (LDiff == RDiff)
4283 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4284 LDiff = getMinusSCEV(LA, RS);
4285 RDiff = getMinusSCEV(RA, LS);
4286 if (LDiff == RDiff)
4287 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4288 }
4289 break;
4290 case ICmpInst::ICMP_NE:
4291 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4292 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4293 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4294 const SCEV *One = getOne(I->getType());
4295 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4296 const SCEV *LA = getSCEV(TrueVal);
4297 const SCEV *RA = getSCEV(FalseVal);
4298 const SCEV *LDiff = getMinusSCEV(LA, LS);
4299 const SCEV *RDiff = getMinusSCEV(RA, One);
4300 if (LDiff == RDiff)
4301 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4302 }
4303 break;
4304 case ICmpInst::ICMP_EQ:
4305 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4306 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4307 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4308 const SCEV *One = getOne(I->getType());
4309 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4310 const SCEV *LA = getSCEV(TrueVal);
4311 const SCEV *RA = getSCEV(FalseVal);
4312 const SCEV *LDiff = getMinusSCEV(LA, One);
4313 const SCEV *RDiff = getMinusSCEV(RA, LS);
4314 if (LDiff == RDiff)
4315 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4316 }
4317 break;
4318 default:
4319 break;
4320 }
4321
4322 return getUnknown(I);
4323}
4324
Sanjoy Dasf8570812016-05-29 00:38:22 +00004325/// Expand GEP instructions into add and multiply operations. This allows them
4326/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004327const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004328 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004329 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004330 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004331
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004332 SmallVector<const SCEV *, 4> IndexExprs;
4333 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4334 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004335 return getGEPExpr(GEP->getSourceElementType(),
4336 getSCEV(GEP->getPointerOperand()),
4337 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004338}
4339
Dan Gohmanc702fc02009-06-19 23:29:04 +00004340uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004341ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004342 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004343 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004344
Dan Gohmana30370b2009-05-04 22:02:23 +00004345 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004346 return std::min(GetMinTrailingZeros(T->getOperand()),
4347 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004348
Dan Gohmana30370b2009-05-04 22:02:23 +00004349 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004350 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4351 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4352 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004353 }
4354
Dan Gohmana30370b2009-05-04 22:02:23 +00004355 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004356 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4357 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4358 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004359 }
4360
Dan Gohmana30370b2009-05-04 22:02:23 +00004361 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004362 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004363 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004364 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004365 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004366 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004367 }
4368
Dan Gohmana30370b2009-05-04 22:02:23 +00004369 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004370 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004371 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4372 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004373 for (unsigned i = 1, e = M->getNumOperands();
4374 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004375 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004376 BitWidth);
4377 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004378 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004379
Dan Gohmana30370b2009-05-04 22:02:23 +00004380 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004381 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004382 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004383 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004384 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004385 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004386 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004387
Dan Gohmana30370b2009-05-04 22:02:23 +00004388 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004389 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004390 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004391 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004392 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004393 return MinOpRes;
4394 }
4395
Dan Gohmana30370b2009-05-04 22:02:23 +00004396 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004397 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004398 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004399 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004400 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004401 return MinOpRes;
4402 }
4403
Dan Gohmanc702fc02009-06-19 23:29:04 +00004404 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4405 // For a SCEVUnknown, ask ValueTracking.
4406 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004407 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004408 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4409 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004410 return Zeros.countTrailingOnes();
4411 }
4412
4413 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004414 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004415}
Chris Lattnerd934c702004-04-02 20:23:17 +00004416
Sanjoy Dasf8570812016-05-29 00:38:22 +00004417/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004418static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004419 if (Instruction *I = dyn_cast<Instruction>(V))
4420 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4421 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004422
4423 return None;
4424}
4425
Sanjoy Dasf8570812016-05-29 00:38:22 +00004426/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004427/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4428/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004429ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004430ScalarEvolution::getRange(const SCEV *S,
4431 ScalarEvolution::RangeSignHint SignHint) {
4432 DenseMap<const SCEV *, ConstantRange> &Cache =
4433 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4434 : SignedRanges;
4435
Dan Gohman761065e2010-11-17 02:44:44 +00004436 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004437 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4438 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004439 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004440
4441 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004442 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004443
Dan Gohman85be4332010-01-26 19:19:05 +00004444 unsigned BitWidth = getTypeSizeInBits(S->getType());
4445 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4446
Sanjoy Das91b54772015-03-09 21:43:43 +00004447 // If the value has known zeros, the maximum value will have those known zeros
4448 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004449 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004450 if (TZ != 0) {
4451 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4452 ConservativeResult =
4453 ConstantRange(APInt::getMinValue(BitWidth),
4454 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4455 else
4456 ConservativeResult = ConstantRange(
4457 APInt::getSignedMinValue(BitWidth),
4458 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4459 }
Dan Gohman85be4332010-01-26 19:19:05 +00004460
Dan Gohmane65c9172009-07-13 21:35:55 +00004461 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004462 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004463 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004464 X = X.add(getRange(Add->getOperand(i), SignHint));
4465 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004466 }
4467
4468 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004469 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004470 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004471 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4472 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004473 }
4474
4475 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004476 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004477 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004478 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4479 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004480 }
4481
4482 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004483 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004484 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004485 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4486 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004487 }
4488
4489 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004490 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4491 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4492 return setRange(UDiv, SignHint,
4493 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004494 }
4495
4496 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004497 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4498 return setRange(ZExt, SignHint,
4499 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004500 }
4501
4502 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004503 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4504 return setRange(SExt, SignHint,
4505 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004506 }
4507
4508 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004509 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4510 return setRange(Trunc, SignHint,
4511 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004512 }
4513
Dan Gohmane65c9172009-07-13 21:35:55 +00004514 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004515 // If there's no unsigned wrap, the value will never be less than its
4516 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004517 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004518 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004519 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004520 ConservativeResult = ConservativeResult.intersectWith(
4521 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004522
Dan Gohman51ad99d2010-01-21 02:09:26 +00004523 // If there's no signed wrap, and all the operands have the same sign or
4524 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004525 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004526 bool AllNonNeg = true;
4527 bool AllNonPos = true;
4528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4529 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4530 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4531 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004532 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004533 ConservativeResult = ConservativeResult.intersectWith(
4534 ConstantRange(APInt(BitWidth, 0),
4535 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004536 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004537 ConservativeResult = ConservativeResult.intersectWith(
4538 ConstantRange(APInt::getSignedMinValue(BitWidth),
4539 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004540 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004541
4542 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004543 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004544 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004545 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4546 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004547 auto RangeFromAffine = getRangeForAffineAR(
4548 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4549 BitWidth);
4550 if (!RangeFromAffine.isFullSet())
4551 ConservativeResult =
4552 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004553
4554 auto RangeFromFactoring = getRangeViaFactoring(
4555 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4556 BitWidth);
4557 if (!RangeFromFactoring.isFullSet())
4558 ConservativeResult =
4559 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004560 }
Dan Gohmand261d272009-06-24 01:05:09 +00004561 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004562
Sanjoy Das91b54772015-03-09 21:43:43 +00004563 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004564 }
4565
Dan Gohmanc702fc02009-06-19 23:29:04 +00004566 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004567 // Check if the IR explicitly contains !range metadata.
4568 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4569 if (MDRange.hasValue())
4570 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4571
Sanjoy Das91b54772015-03-09 21:43:43 +00004572 // Split here to avoid paying the compile-time cost of calling both
4573 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4574 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004575 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004576 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4577 // For a SCEVUnknown, ask ValueTracking.
4578 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004579 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004580 if (Ones != ~Zeros + 1)
4581 ConservativeResult =
4582 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4583 } else {
4584 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4585 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004586 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004587 if (NS > 1)
4588 ConservativeResult = ConservativeResult.intersectWith(
4589 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4590 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004591 }
4592
4593 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004594 }
4595
Sanjoy Das91b54772015-03-09 21:43:43 +00004596 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004597}
4598
Sanjoy Dasb765b632016-03-02 00:57:39 +00004599ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4600 const SCEV *Step,
4601 const SCEV *MaxBECount,
4602 unsigned BitWidth) {
4603 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4604 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4605 "Precondition!");
4606
4607 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4608
4609 // Check for overflow. This must be done with ConstantRange arithmetic
4610 // because we could be called from within the ScalarEvolution overflow
4611 // checking code.
4612
4613 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4614 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4615 ConstantRange ZExtMaxBECountRange =
4616 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4617
4618 ConstantRange StepSRange = getSignedRange(Step);
4619 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4620
4621 ConstantRange StartURange = getUnsignedRange(Start);
4622 ConstantRange EndURange =
4623 StartURange.add(MaxBECountRange.multiply(StepSRange));
4624
4625 // Check for unsigned overflow.
4626 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4627 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4628 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4629 ZExtEndURange) {
4630 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4631 EndURange.getUnsignedMin());
4632 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4633 EndURange.getUnsignedMax());
4634 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4635 if (!IsFullRange)
4636 Result =
4637 Result.intersectWith(ConstantRange(Min, Max + 1));
4638 }
4639
4640 ConstantRange StartSRange = getSignedRange(Start);
4641 ConstantRange EndSRange =
4642 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4643
4644 // Check for signed overflow. This must be done with ConstantRange
4645 // arithmetic because we could be called from within the ScalarEvolution
4646 // overflow checking code.
4647 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4648 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4649 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4650 SExtEndSRange) {
4651 APInt Min =
4652 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4653 APInt Max =
4654 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4655 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4656 if (!IsFullRange)
4657 Result =
4658 Result.intersectWith(ConstantRange(Min, Max + 1));
4659 }
4660
4661 return Result;
4662}
4663
Sanjoy Dasbf730982016-03-02 00:57:54 +00004664ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4665 const SCEV *Step,
4666 const SCEV *MaxBECount,
4667 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004668 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4669 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4670
4671 struct SelectPattern {
4672 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004673 APInt TrueValue;
4674 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004675
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004676 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4677 const SCEV *S) {
4678 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004679 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004680
4681 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4682 "Should be!");
4683
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004684 // Peel off a constant offset:
4685 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4686 // In the future we could consider being smarter here and handle
4687 // {Start+Step,+,Step} too.
4688 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4689 return;
4690
4691 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4692 S = SA->getOperand(1);
4693 }
4694
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004695 // Peel off a cast operation
4696 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4697 CastOp = SCast->getSCEVType();
4698 S = SCast->getOperand();
4699 }
4700
Sanjoy Dasbf730982016-03-02 00:57:54 +00004701 using namespace llvm::PatternMatch;
4702
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004703 auto *SU = dyn_cast<SCEVUnknown>(S);
4704 const APInt *TrueVal, *FalseVal;
4705 if (!SU ||
4706 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4707 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004708 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004709 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004710 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004711
4712 TrueValue = *TrueVal;
4713 FalseValue = *FalseVal;
4714
4715 // Re-apply the cast we peeled off earlier
4716 if (CastOp.hasValue())
4717 switch (*CastOp) {
4718 default:
4719 llvm_unreachable("Unknown SCEV cast type!");
4720
4721 case scTruncate:
4722 TrueValue = TrueValue.trunc(BitWidth);
4723 FalseValue = FalseValue.trunc(BitWidth);
4724 break;
4725 case scZeroExtend:
4726 TrueValue = TrueValue.zext(BitWidth);
4727 FalseValue = FalseValue.zext(BitWidth);
4728 break;
4729 case scSignExtend:
4730 TrueValue = TrueValue.sext(BitWidth);
4731 FalseValue = FalseValue.sext(BitWidth);
4732 break;
4733 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004734
4735 // Re-apply the constant offset we peeled off earlier
4736 TrueValue += Offset;
4737 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004738 }
4739
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004740 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004741 };
4742
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004743 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004744 if (!StartPattern.isRecognized())
4745 return ConstantRange(BitWidth, /* isFullSet = */ true);
4746
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004747 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004748 if (!StepPattern.isRecognized())
4749 return ConstantRange(BitWidth, /* isFullSet = */ true);
4750
4751 if (StartPattern.Condition != StepPattern.Condition) {
4752 // We don't handle this case today; but we could, by considering four
4753 // possibilities below instead of two. I'm not sure if there are cases where
4754 // that will help over what getRange already does, though.
4755 return ConstantRange(BitWidth, /* isFullSet = */ true);
4756 }
4757
4758 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4759 // construct arbitrary general SCEV expressions here. This function is called
4760 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4761 // say) can end up caching a suboptimal value.
4762
Sanjoy Das6b017a12016-03-02 02:56:29 +00004763 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4764 // C2352 and C2512 (otherwise it isn't needed).
4765
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004766 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004767 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004768 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004769 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004770
Sanjoy Das1168f932016-03-02 02:34:20 +00004771 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004772 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004773 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004774 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004775
4776 return TrueRange.unionWith(FalseRange);
4777}
4778
Jingyue Wu42f1d672015-07-28 18:22:40 +00004779SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004780 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004781 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4782
4783 // Return early if there are no flags to propagate to the SCEV.
4784 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4785 if (BinOp->hasNoUnsignedWrap())
4786 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4787 if (BinOp->hasNoSignedWrap())
4788 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004789 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004790 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004791
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004792 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4793}
4794
4795bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4796 // Here we check that I is in the header of the innermost loop containing I,
4797 // since we only deal with instructions in the loop header. The actual loop we
4798 // need to check later will come from an add recurrence, but getting that
4799 // requires computing the SCEV of the operands, which can be expensive. This
4800 // check we can do cheaply to rule out some cases early.
4801 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004802 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004803 InnermostContainingLoop->getHeader() != I->getParent())
4804 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004805
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004806 // Only proceed if we can prove that I does not yield poison.
4807 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004808
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004809 // At this point we know that if I is executed, then it does not wrap
4810 // according to at least one of NSW or NUW. If I is not executed, then we do
4811 // not know if the calculation that I represents would wrap. Multiple
4812 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004813 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4814 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004815 // that guarantee for cases where I is not executed. So we need to find the
4816 // loop that I is considered in relation to and prove that I is executed for
4817 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004818 // calculates does not wrap anywhere in the loop, so then we can apply the
4819 // flags to the SCEV.
4820 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004821 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4822 // from different loops, so that we know which loop to prove that I is
4823 // executed in.
4824 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4825 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004826 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004827 bool AllOtherOpsLoopInvariant = true;
4828 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4829 ++OtherOpIndex) {
4830 if (OtherOpIndex != OpIndex) {
4831 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4832 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4833 AllOtherOpsLoopInvariant = false;
4834 break;
4835 }
4836 }
4837 }
4838 if (AllOtherOpsLoopInvariant &&
4839 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4840 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004841 }
4842 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004843 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004844}
4845
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004846bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4847 // If we know that \c I can never be poison period, then that's enough.
4848 if (isSCEVExprNeverPoison(I))
4849 return true;
4850
4851 // For an add recurrence specifically, we assume that infinite loops without
4852 // side effects are undefined behavior, and then reason as follows:
4853 //
4854 // If the add recurrence is poison in any iteration, it is poison on all
4855 // future iterations (since incrementing poison yields poison). If the result
4856 // of the add recurrence is fed into the loop latch condition and the loop
4857 // does not contain any throws or exiting blocks other than the latch, we now
4858 // have the ability to "choose" whether the backedge is taken or not (by
4859 // choosing a sufficiently evil value for the poison feeding into the branch)
4860 // for every iteration including and after the one in which \p I first became
4861 // poison. There are two possibilities (let's call the iteration in which \p
4862 // I first became poison as K):
4863 //
4864 // 1. In the set of iterations including and after K, the loop body executes
4865 // no side effects. In this case executing the backege an infinte number
4866 // of times will yield undefined behavior.
4867 //
4868 // 2. In the set of iterations including and after K, the loop body executes
4869 // at least one side effect. In this case, that specific instance of side
4870 // effect is control dependent on poison, which also yields undefined
4871 // behavior.
4872
4873 auto *ExitingBB = L->getExitingBlock();
4874 auto *LatchBB = L->getLoopLatch();
4875 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4876 return false;
4877
4878 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004879 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004880
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004881 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4882 // things that are known to be fully poison under that assumption go on the
4883 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004884 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004885 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004886
4887 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004888 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004889 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004890
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004891 for (auto *PoisonUser : Poison->users()) {
4892 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4893 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4894 PoisonStack.push_back(cast<Instruction>(PoisonUser));
4895 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004896 assert(BI->isConditional() && "Only possibility!");
4897 if (BI->getParent() == LatchBB) {
4898 LatchControlDependentOnPoison = true;
4899 break;
4900 }
4901 }
4902 }
4903 }
4904
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004905 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4906}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004907
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004908bool ScalarEvolution::loopHasNoAbnormalExits(const Loop *L) {
4909 auto Itr = LoopHasNoAbnormalExits.find(L);
4910 if (Itr == LoopHasNoAbnormalExits.end()) {
Sanjoy Das1eade912016-06-09 01:14:03 +00004911 auto NoAbnormalExitInBB = [&](BasicBlock *BB) {
4912 return all_of(*BB, [](Instruction &I) {
4913 return isGuaranteedToTransferExecutionToSuccessor(&I);
Sanjoy Das85984122016-06-08 17:48:42 +00004914 });
Sanjoy Das1eade912016-06-09 01:14:03 +00004915 };
4916
4917 auto InsertPair = LoopHasNoAbnormalExits.insert(
4918 {L, all_of(L->getBlocks(), NoAbnormalExitInBB)});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004919 assert(InsertPair.second && "We just checked!");
4920 Itr = InsertPair.first;
4921 }
4922
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004923 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004924}
4925
Dan Gohmanaf752342009-07-07 17:06:11 +00004926const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004927 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004928 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004929
Dan Gohman69451a02010-03-09 23:46:50 +00004930 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00004931 // Don't attempt to analyze instructions in blocks that aren't
4932 // reachable. Such instructions don't matter, and they aren't required
4933 // to obey basic rules for definitions dominating uses which this
4934 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004935 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004936 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004937 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00004938 return getConstant(CI);
4939 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004940 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004941 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00004942 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004943 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004944 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004945
Dan Gohman80ca01c2009-07-17 20:47:02 +00004946 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004947 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004948 switch (BO->Opcode) {
4949 case Instruction::Add: {
4950 // The simple thing to do would be to just call getSCEV on both operands
4951 // and call getAddExpr with the result. However if we're looking at a
4952 // bunch of things all added together, this can be quite inefficient,
4953 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4954 // Instead, gather up all the operands and make a single getAddExpr call.
4955 // LLVM IR canonical form means we need only traverse the left operands.
4956 SmallVector<const SCEV *, 4> AddOps;
4957 do {
4958 if (BO->Op) {
4959 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
4960 AddOps.push_back(OpSCEV);
4961 break;
4962 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004963
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004964 // If a NUW or NSW flag can be applied to the SCEV for this
4965 // addition, then compute the SCEV for this addition by itself
4966 // with a separate call to getAddExpr. We need to do that
4967 // instead of pushing the operands of the addition onto AddOps,
4968 // since the flags are only known to apply to this particular
4969 // addition - they may not apply to other additions that can be
4970 // formed with operands from AddOps.
4971 const SCEV *RHS = getSCEV(BO->RHS);
4972 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
4973 if (Flags != SCEV::FlagAnyWrap) {
4974 const SCEV *LHS = getSCEV(BO->LHS);
4975 if (BO->Opcode == Instruction::Sub)
4976 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4977 else
4978 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4979 break;
4980 }
Dan Gohman36bad002009-09-17 18:05:20 +00004981 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004982
4983 if (BO->Opcode == Instruction::Sub)
4984 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
4985 else
4986 AddOps.push_back(getSCEV(BO->RHS));
4987
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004988 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004989 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
4990 NewBO->Opcode != Instruction::Sub)) {
4991 AddOps.push_back(getSCEV(BO->LHS));
4992 break;
4993 }
4994 BO = NewBO;
4995 } while (true);
4996
4997 return getAddExpr(AddOps);
4998 }
4999
5000 case Instruction::Mul: {
5001 SmallVector<const SCEV *, 4> MulOps;
5002 do {
5003 if (BO->Op) {
5004 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5005 MulOps.push_back(OpSCEV);
5006 break;
5007 }
5008
5009 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5010 if (Flags != SCEV::FlagAnyWrap) {
5011 MulOps.push_back(
5012 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5013 break;
5014 }
5015 }
5016
5017 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005018 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005019 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5020 MulOps.push_back(getSCEV(BO->LHS));
5021 break;
5022 }
5023 BO = NewBO;
5024 } while (true);
5025
5026 return getMulExpr(MulOps);
5027 }
5028 case Instruction::UDiv:
5029 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5030 case Instruction::Sub: {
5031 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5032 if (BO->Op)
5033 Flags = getNoWrapFlagsFromUB(BO->Op);
5034 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5035 }
5036 case Instruction::And:
5037 // For an expression like x&255 that merely masks off the high bits,
5038 // use zext(trunc(x)) as the SCEV expression.
5039 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5040 if (CI->isNullValue())
5041 return getSCEV(BO->RHS);
5042 if (CI->isAllOnesValue())
5043 return getSCEV(BO->LHS);
5044 const APInt &A = CI->getValue();
5045
5046 // Instcombine's ShrinkDemandedConstant may strip bits out of
5047 // constants, obscuring what would otherwise be a low-bits mask.
5048 // Use computeKnownBits to compute what ShrinkDemandedConstant
5049 // knew about to reconstruct a low-bits mask value.
5050 unsigned LZ = A.countLeadingZeros();
5051 unsigned TZ = A.countTrailingZeros();
5052 unsigned BitWidth = A.getBitWidth();
5053 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5054 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5055 0, &AC, nullptr, &DT);
5056
5057 APInt EffectiveMask =
5058 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5059 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5060 const SCEV *MulCount = getConstant(ConstantInt::get(
5061 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5062 return getMulExpr(
5063 getZeroExtendExpr(
5064 getTruncateExpr(
5065 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5066 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5067 BO->LHS->getType()),
5068 MulCount);
5069 }
Dan Gohman36bad002009-09-17 18:05:20 +00005070 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005071 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005072
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005073 case Instruction::Or:
5074 // If the RHS of the Or is a constant, we may have something like:
5075 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5076 // optimizations will transparently handle this case.
5077 //
5078 // In order for this transformation to be safe, the LHS must be of the
5079 // form X*(2^n) and the Or constant must be less than 2^n.
5080 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5081 const SCEV *LHS = getSCEV(BO->LHS);
5082 const APInt &CIVal = CI->getValue();
5083 if (GetMinTrailingZeros(LHS) >=
5084 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5085 // Build a plain add SCEV.
5086 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5087 // If the LHS of the add was an addrec and it has no-wrap flags,
5088 // transfer the no-wrap flags, since an or won't introduce a wrap.
5089 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5090 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5091 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5092 OldAR->getNoWrapFlags());
5093 }
5094 return S;
5095 }
5096 }
5097 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005098
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005099 case Instruction::Xor:
5100 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5101 // If the RHS of xor is -1, then this is a not operation.
5102 if (CI->isAllOnesValue())
5103 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005104
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005105 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5106 // This is a variant of the check for xor with -1, and it handles
5107 // the case where instcombine has trimmed non-demanded bits out
5108 // of an xor with -1.
5109 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5110 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5111 if (LBO->getOpcode() == Instruction::And &&
5112 LCI->getValue() == CI->getValue())
5113 if (const SCEVZeroExtendExpr *Z =
5114 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5115 Type *UTy = BO->LHS->getType();
5116 const SCEV *Z0 = Z->getOperand();
5117 Type *Z0Ty = Z0->getType();
5118 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005119
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005120 // If C is a low-bits mask, the zero extend is serving to
5121 // mask off the high bits. Complement the operand and
5122 // re-apply the zext.
5123 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5124 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5125
5126 // If C is a single bit, it may be in the sign-bit position
5127 // before the zero-extend. In this case, represent the xor
5128 // using an add, which is equivalent, and re-apply the zext.
5129 APInt Trunc = CI->getValue().trunc(Z0TySize);
5130 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5131 Trunc.isSignBit())
5132 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5133 UTy);
5134 }
5135 }
5136 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005137
5138 case Instruction::Shl:
5139 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005140 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5141 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005142
5143 // If the shift count is not less than the bitwidth, the result of
5144 // the shift is undefined. Don't try to analyze it, because the
5145 // resolution chosen here may differ from the resolution chosen in
5146 // other parts of the compiler.
5147 if (SA->getValue().uge(BitWidth))
5148 break;
5149
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005150 // It is currently not resolved how to interpret NSW for left
5151 // shift by BitWidth - 1, so we avoid applying flags in that
5152 // case. Remove this check (or this comment) once the situation
5153 // is resolved. See
5154 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5155 // and http://reviews.llvm.org/D8890 .
5156 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005157 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5158 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005159
Owen Andersonedb4a702009-07-24 23:12:02 +00005160 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005161 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005162 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005163 }
5164 break;
5165
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005166 case Instruction::AShr:
5167 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5168 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5169 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5170 if (L->getOpcode() == Instruction::Shl &&
5171 L->getOperand(1) == BO->RHS) {
5172 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005173
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005174 // If the shift count is not less than the bitwidth, the result of
5175 // the shift is undefined. Don't try to analyze it, because the
5176 // resolution chosen here may differ from the resolution chosen in
5177 // other parts of the compiler.
5178 if (CI->getValue().uge(BitWidth))
5179 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005180
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005181 uint64_t Amt = BitWidth - CI->getZExtValue();
5182 if (Amt == BitWidth)
5183 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5184 return getSignExtendExpr(
5185 getTruncateExpr(getSCEV(L->getOperand(0)),
5186 IntegerType::get(getContext(), Amt)),
5187 BO->LHS->getType());
5188 }
5189 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005190 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005191 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005192
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005193 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005194 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005195 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005196
5197 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005198 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005199
5200 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005201 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005202
5203 case Instruction::BitCast:
5204 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005205 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005206 return getSCEV(U->getOperand(0));
5207 break;
5208
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005209 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5210 // lead to pointer expressions which cannot safely be expanded to GEPs,
5211 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5212 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005213
Dan Gohmanee750d12009-05-08 20:26:55 +00005214 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005215 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005216
Dan Gohman05e89732008-06-22 19:56:46 +00005217 case Instruction::PHI:
5218 return createNodeForPHI(cast<PHINode>(U));
5219
5220 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005221 // U can also be a select constant expr, which let fall through. Since
5222 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5223 // constant expressions cannot have instructions as operands, we'd have
5224 // returned getUnknown for a select constant expressions anyway.
5225 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005226 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5227 U->getOperand(1), U->getOperand(2));
Chris Lattnerd934c702004-04-02 20:23:17 +00005228 }
5229
Dan Gohmanc8e23622009-04-21 23:15:49 +00005230 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005231}
5232
5233
5234
5235//===----------------------------------------------------------------------===//
5236// Iteration Count Computation Code
5237//
5238
Chandler Carruth6666c272014-10-11 00:12:11 +00005239unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5240 if (BasicBlock *ExitingBB = L->getExitingBlock())
5241 return getSmallConstantTripCount(L, ExitingBB);
5242
5243 // No trip count information for multiple exits.
5244 return 0;
5245}
5246
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005247unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5248 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005249 assert(ExitingBlock && "Must pass a non-null exiting block!");
5250 assert(L->isLoopExiting(ExitingBlock) &&
5251 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005252 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005253 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005254 if (!ExitCount)
5255 return 0;
5256
5257 ConstantInt *ExitConst = ExitCount->getValue();
5258
5259 // Guard against huge trip counts.
5260 if (ExitConst->getValue().getActiveBits() > 32)
5261 return 0;
5262
5263 // In case of integer overflow, this returns 0, which is correct.
5264 return ((unsigned)ExitConst->getZExtValue()) + 1;
5265}
5266
Chandler Carruth6666c272014-10-11 00:12:11 +00005267unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5268 if (BasicBlock *ExitingBB = L->getExitingBlock())
5269 return getSmallConstantTripMultiple(L, ExitingBB);
5270
5271 // No trip multiple information for multiple exits.
5272 return 0;
5273}
5274
Sanjoy Dasf8570812016-05-29 00:38:22 +00005275/// Returns the largest constant divisor of the trip count of this loop as a
5276/// normal unsigned value, if possible. This means that the actual trip count is
5277/// always a multiple of the returned value (don't forget the trip count could
5278/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005279///
5280/// Returns 1 if the trip count is unknown or not guaranteed to be the
5281/// multiple of a constant (which is also the case if the trip count is simply
5282/// constant, use getSmallConstantTripCount for that case), Will also return 1
5283/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005284///
5285/// As explained in the comments for getSmallConstantTripCount, this assumes
5286/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005287unsigned
5288ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5289 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005290 assert(ExitingBlock && "Must pass a non-null exiting block!");
5291 assert(L->isLoopExiting(ExitingBlock) &&
5292 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005293 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005294 if (ExitCount == getCouldNotCompute())
5295 return 1;
5296
5297 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005298 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005299 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5300 // to factor simple cases.
5301 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5302 TCMul = Mul->getOperand(0);
5303
5304 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5305 if (!MulC)
5306 return 1;
5307
5308 ConstantInt *Result = MulC->getValue();
5309
Hal Finkel30bd9342012-10-24 19:46:44 +00005310 // Guard against huge trip counts (this requires checking
5311 // for zero to handle the case where the trip count == -1 and the
5312 // addition wraps).
5313 if (!Result || Result->getValue().getActiveBits() > 32 ||
5314 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005315 return 1;
5316
5317 return (unsigned)Result->getZExtValue();
5318}
5319
Sanjoy Dasf8570812016-05-29 00:38:22 +00005320/// Get the expression for the number of loop iterations for which this loop is
5321/// guaranteed not to exit via ExitingBlock. Otherwise return
5322/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005323const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5324 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005325}
5326
Silviu Baranga6f444df2016-04-08 14:29:09 +00005327const SCEV *
5328ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5329 SCEVUnionPredicate &Preds) {
5330 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5331}
5332
Dan Gohmanaf752342009-07-07 17:06:11 +00005333const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005334 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005335}
5336
Sanjoy Dasf8570812016-05-29 00:38:22 +00005337/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5338/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005339const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005340 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005341}
5342
Sanjoy Dasf8570812016-05-29 00:38:22 +00005343/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005344static void
5345PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5346 BasicBlock *Header = L->getHeader();
5347
5348 // Push all Loop-header PHIs onto the Worklist stack.
5349 for (BasicBlock::iterator I = Header->begin();
5350 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5351 Worklist.push_back(PN);
5352}
5353
Dan Gohman2b8da352009-04-30 20:47:05 +00005354const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005355ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5356 auto &BTI = getBackedgeTakenInfo(L);
5357 if (BTI.hasFullInfo())
5358 return BTI;
5359
5360 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5361
5362 if (!Pair.second)
5363 return Pair.first->second;
5364
5365 BackedgeTakenInfo Result =
5366 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5367
5368 return PredicatedBackedgeTakenCounts.find(L)->second = Result;
5369}
5370
5371const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005372ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005373 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005374 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005375 // update the value. The temporary CouldNotCompute value tells SCEV
5376 // code elsewhere that it shouldn't attempt to request a new
5377 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005378 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005379 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005380 if (!Pair.second)
5381 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005382
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005383 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005384 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5385 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005386 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005387
5388 if (Result.getExact(this) != getCouldNotCompute()) {
5389 assert(isLoopInvariant(Result.getExact(this), L) &&
5390 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005391 "Computed backedge-taken count isn't loop invariant for loop!");
5392 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005393 }
5394 else if (Result.getMax(this) == getCouldNotCompute() &&
5395 isa<PHINode>(L->getHeader()->begin())) {
5396 // Only count loops that have phi nodes as not being computable.
5397 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005398 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005399
Chris Lattnera337f5e2011-01-09 02:16:18 +00005400 // Now that we know more about the trip count for this loop, forget any
5401 // existing SCEV values for PHI nodes in this loop since they are only
5402 // conservative estimates made without the benefit of trip count
5403 // information. This is similar to the code in forgetLoop, except that
5404 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005405 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005406 SmallVector<Instruction *, 16> Worklist;
5407 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005408
Chris Lattnera337f5e2011-01-09 02:16:18 +00005409 SmallPtrSet<Instruction *, 8> Visited;
5410 while (!Worklist.empty()) {
5411 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005412 if (!Visited.insert(I).second)
5413 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005414
Chris Lattnera337f5e2011-01-09 02:16:18 +00005415 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005416 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005417 if (It != ValueExprMap.end()) {
5418 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005419
Chris Lattnera337f5e2011-01-09 02:16:18 +00005420 // SCEVUnknown for a PHI either means that it has an unrecognized
5421 // structure, or it's a PHI that's in the progress of being computed
5422 // by createNodeForPHI. In the former case, additional loop trip
5423 // count information isn't going to change anything. In the later
5424 // case, createNodeForPHI will perform the necessary updates on its
5425 // own when it gets to that point.
5426 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5427 forgetMemoizedResults(Old);
5428 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005429 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005430 if (PHINode *PN = dyn_cast<PHINode>(I))
5431 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005432 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005433
5434 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005435 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005436 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005437
5438 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005439 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005440 // recusive call to getBackedgeTakenInfo (on a different
5441 // loop), which would invalidate the iterator computed
5442 // earlier.
5443 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00005444}
5445
Dan Gohman880c92a2009-10-31 15:04:55 +00005446void ScalarEvolution::forgetLoop(const Loop *L) {
5447 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005448 auto RemoveLoopFromBackedgeMap =
5449 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5450 auto BTCPos = Map.find(L);
5451 if (BTCPos != Map.end()) {
5452 BTCPos->second.clear();
5453 Map.erase(BTCPos);
5454 }
5455 };
5456
5457 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5458 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005459
Dan Gohman880c92a2009-10-31 15:04:55 +00005460 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005461 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005462 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005463
Dan Gohmandc191042009-07-08 19:23:34 +00005464 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005465 while (!Worklist.empty()) {
5466 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005467 if (!Visited.insert(I).second)
5468 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005469
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005470 ValueExprMapType::iterator It =
5471 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005472 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005473 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005474 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005475 if (PHINode *PN = dyn_cast<PHINode>(I))
5476 ConstantEvolutionLoopExitValue.erase(PN);
5477 }
5478
5479 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005480 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005481
5482 // Forget all contained loops too, to avoid dangling entries in the
5483 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005484 for (Loop *I : *L)
5485 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005486
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005487 LoopHasNoAbnormalExits.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005488}
5489
Eric Christopheref6d5932010-07-29 01:25:38 +00005490void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005491 Instruction *I = dyn_cast<Instruction>(V);
5492 if (!I) return;
5493
5494 // Drop information about expressions based on loop-header PHIs.
5495 SmallVector<Instruction *, 16> Worklist;
5496 Worklist.push_back(I);
5497
5498 SmallPtrSet<Instruction *, 8> Visited;
5499 while (!Worklist.empty()) {
5500 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005501 if (!Visited.insert(I).second)
5502 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005503
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005504 ValueExprMapType::iterator It =
5505 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005506 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005507 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005508 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005509 if (PHINode *PN = dyn_cast<PHINode>(I))
5510 ConstantEvolutionLoopExitValue.erase(PN);
5511 }
5512
5513 PushDefUseChildren(I, Worklist);
5514 }
5515}
5516
Sanjoy Dasf8570812016-05-29 00:38:22 +00005517/// Get the exact loop backedge taken count considering all loop exits. A
5518/// computable result can only be returned for loops with a single exit.
5519/// Returning the minimum taken count among all exits is incorrect because one
5520/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5521/// the limit of each loop test is never skipped. This is a valid assumption as
5522/// long as the loop exits via that test. For precise results, it is the
5523/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005524/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005525const SCEV *
Silviu Baranga6f444df2016-04-08 14:29:09 +00005526ScalarEvolution::BackedgeTakenInfo::getExact(
5527 ScalarEvolution *SE, SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005528 // If any exits were not computable, the loop is not computable.
5529 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5530
Andrew Trick90c7a102011-11-16 00:52:40 +00005531 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005532 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005533 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5534
Craig Topper9f008862014-04-15 04:59:12 +00005535 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005536 for (auto &ENT : ExitNotTaken) {
5537 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005538
5539 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005540 BECount = ENT.ExactNotTaken;
5541 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005542 return SE->getCouldNotCompute();
Silviu Baranga6f444df2016-04-08 14:29:09 +00005543 if (Preds && ENT.getPred())
5544 Preds->add(ENT.getPred());
5545
5546 assert((Preds || ENT.hasAlwaysTruePred()) &&
5547 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005548 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005549
Andrew Trickbbb226a2011-09-02 21:20:46 +00005550 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005551 return BECount;
5552}
5553
Sanjoy Dasf8570812016-05-29 00:38:22 +00005554/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005555const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005556ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005557 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005558 for (auto &ENT : ExitNotTaken)
5559 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePred())
5560 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005561
Andrew Trick3ca3f982011-07-26 17:19:55 +00005562 return SE->getCouldNotCompute();
5563}
5564
5565/// getMax - Get the max backedge taken count for the loop.
5566const SCEV *
5567ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005568 for (auto &ENT : ExitNotTaken)
5569 if (!ENT.hasAlwaysTruePred())
5570 return SE->getCouldNotCompute();
5571
Andrew Trick3ca3f982011-07-26 17:19:55 +00005572 return Max ? Max : SE->getCouldNotCompute();
5573}
5574
Andrew Trick9093e152013-03-26 03:14:53 +00005575bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5576 ScalarEvolution *SE) const {
5577 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5578 return true;
5579
5580 if (!ExitNotTaken.ExitingBlock)
5581 return false;
5582
Silviu Baranga6f444df2016-04-08 14:29:09 +00005583 for (auto &ENT : ExitNotTaken)
5584 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5585 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005586 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005587
Andrew Trick9093e152013-03-26 03:14:53 +00005588 return false;
5589}
5590
Andrew Trick3ca3f982011-07-26 17:19:55 +00005591/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5592/// computable exit into a persistent ExitNotTakenInfo array.
5593ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Silviu Baranga6f444df2016-04-08 14:29:09 +00005594 SmallVectorImpl<EdgeInfo> &ExitCounts, bool Complete, const SCEV *MaxCount)
5595 : Max(MaxCount) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005596
5597 if (!Complete)
5598 ExitNotTaken.setIncomplete();
5599
5600 unsigned NumExits = ExitCounts.size();
5601 if (NumExits == 0) return;
5602
Silviu Baranga6f444df2016-04-08 14:29:09 +00005603 ExitNotTaken.ExitingBlock = ExitCounts[0].ExitBlock;
5604 ExitNotTaken.ExactNotTaken = ExitCounts[0].Taken;
5605
5606 // Determine the number of ExitNotTakenExtras structures that we need.
5607 unsigned ExtraInfoSize = 0;
5608 if (NumExits > 1)
5609 ExtraInfoSize = 1 + std::count_if(std::next(ExitCounts.begin()),
5610 ExitCounts.end(), [](EdgeInfo &Entry) {
5611 return !Entry.Pred.isAlwaysTrue();
5612 });
5613 else if (!ExitCounts[0].Pred.isAlwaysTrue())
5614 ExtraInfoSize = 1;
5615
5616 ExitNotTakenExtras *ENT = nullptr;
5617
5618 // Allocate the ExitNotTakenExtras structures and initialize the first
5619 // element (ExitNotTaken).
5620 if (ExtraInfoSize > 0) {
5621 ENT = new ExitNotTakenExtras[ExtraInfoSize];
5622 ExitNotTaken.ExtraInfo = &ENT[0];
5623 *ExitNotTaken.getPred() = std::move(ExitCounts[0].Pred);
5624 }
5625
5626 if (NumExits == 1)
5627 return;
5628
Silviu Baranga24dbd2e2016-05-13 14:54:50 +00005629 assert(ENT && "ExitNotTakenExtras is NULL while having more than one exit");
5630
Silviu Baranga6f444df2016-04-08 14:29:09 +00005631 auto &Exits = ExitNotTaken.ExtraInfo->Exits;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005632
5633 // Handle the rare case of multiple computable exits.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005634 for (unsigned i = 1, PredPos = 1; i < NumExits; ++i) {
5635 ExitNotTakenExtras *Ptr = nullptr;
5636 if (!ExitCounts[i].Pred.isAlwaysTrue()) {
5637 Ptr = &ENT[PredPos++];
5638 Ptr->Pred = std::move(ExitCounts[i].Pred);
5639 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005640
Silviu Baranga6f444df2016-04-08 14:29:09 +00005641 Exits.emplace_back(ExitCounts[i].ExitBlock, ExitCounts[i].Taken, Ptr);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005642 }
5643}
5644
Sanjoy Dasf8570812016-05-29 00:38:22 +00005645/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005646void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005647 ExitNotTaken.ExitingBlock = nullptr;
5648 ExitNotTaken.ExactNotTaken = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005649 delete[] ExitNotTaken.ExtraInfo;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005650}
5651
Sanjoy Dasf8570812016-05-29 00:38:22 +00005652/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005653ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005654ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5655 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005656 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005657 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005658
Silviu Baranga6f444df2016-04-08 14:29:09 +00005659 SmallVector<EdgeInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005660 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005661 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005662 const SCEV *MustExitMaxBECount = nullptr;
5663 const SCEV *MayExitMaxBECount = nullptr;
5664
5665 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5666 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005667 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005668 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005669 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005670 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5671
5672 assert((AllowPredicates || EL.Pred.isAlwaysTrue()) &&
5673 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005674
5675 // 1. For each exit that can be computed, add an entry to ExitCounts.
5676 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005677 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005678 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005679 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005680 CouldComputeBECount = false;
5681 else
Silviu Baranga6f444df2016-04-08 14:29:09 +00005682 ExitCounts.emplace_back(EdgeInfo(ExitBB, EL.Exact, EL.Pred));
Andrew Trick3ca3f982011-07-26 17:19:55 +00005683
Andrew Trick839e30b2014-05-23 19:47:13 +00005684 // 2. Derive the loop's MaxBECount from each exit's max number of
5685 // non-exiting iterations. Partition the loop exits into two kinds:
5686 // LoopMustExits and LoopMayExits.
5687 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005688 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5689 // is a LoopMayExit. If any computable LoopMustExit is found, then
5690 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5691 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5692 // considered greater than any computable EL.Max.
5693 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005694 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005695 if (!MustExitMaxBECount)
5696 MustExitMaxBECount = EL.Max;
5697 else {
5698 MustExitMaxBECount =
5699 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005700 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005701 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5702 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5703 MayExitMaxBECount = EL.Max;
5704 else {
5705 MayExitMaxBECount =
5706 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5707 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005708 }
Dan Gohman96212b62009-06-22 00:31:57 +00005709 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005710 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5711 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005712 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005713}
5714
Andrew Trick3ca3f982011-07-26 17:19:55 +00005715ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005716ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5717 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005718
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005719 // Okay, we've chosen an exiting block. See what condition causes us to exit
5720 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005721 // lead to the loop header.
5722 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005723 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005724 for (auto *SBB : successors(ExitingBlock))
5725 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005726 if (Exit) // Multiple exit successors.
5727 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005728 Exit = SBB;
5729 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005730 MustExecuteLoopHeader = false;
5731 }
Dan Gohmance973df2009-06-24 04:48:43 +00005732
Chris Lattner18954852007-01-07 02:24:26 +00005733 // At this point, we know we have a conditional branch that determines whether
5734 // the loop is exited. However, we don't know if the branch is executed each
5735 // time through the loop. If not, then the execution count of the branch will
5736 // not be equal to the trip count of the loop.
5737 //
5738 // Currently we check for this by checking to see if the Exit branch goes to
5739 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005740 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005741 // loop header. This is common for un-rotated loops.
5742 //
5743 // If both of those tests fail, walk up the unique predecessor chain to the
5744 // header, stopping if there is an edge that doesn't exit the loop. If the
5745 // header is reached, the execution count of the branch will be equal to the
5746 // trip count of the loop.
5747 //
5748 // More extensive analysis could be done to handle more cases here.
5749 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005750 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005751 // The simple checks failed, try climbing the unique predecessor chain
5752 // up to the header.
5753 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005754 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005755 BasicBlock *Pred = BB->getUniquePredecessor();
5756 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005757 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005758 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005759 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005760 if (PredSucc == BB)
5761 continue;
5762 // If the predecessor has a successor that isn't BB and isn't
5763 // outside the loop, assume the worst.
5764 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005765 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005766 }
5767 if (Pred == L->getHeader()) {
5768 Ok = true;
5769 break;
5770 }
5771 BB = Pred;
5772 }
5773 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005774 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005775 }
5776
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005777 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005778 TerminatorInst *Term = ExitingBlock->getTerminator();
5779 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5780 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5781 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005782 return computeExitLimitFromCond(
5783 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5784 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005785 }
5786
5787 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005788 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005789 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005790
5791 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005792}
5793
Andrew Trick3ca3f982011-07-26 17:19:55 +00005794ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005795ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005796 Value *ExitCond,
5797 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005798 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005799 bool ControlsExit,
5800 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005801 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005802 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5803 if (BO->getOpcode() == Instruction::And) {
5804 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005805 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005806 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005807 ControlsExit && !EitherMayExit,
5808 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005809 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005810 ControlsExit && !EitherMayExit,
5811 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005812 const SCEV *BECount = getCouldNotCompute();
5813 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005814 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005815 // Both conditions must be true for the loop to continue executing.
5816 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005817 if (EL0.Exact == getCouldNotCompute() ||
5818 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005819 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005820 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005821 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5822 if (EL0.Max == getCouldNotCompute())
5823 MaxBECount = EL1.Max;
5824 else if (EL1.Max == getCouldNotCompute())
5825 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005826 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005827 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005828 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005829 // Both conditions must be true at the same time for the loop to exit.
5830 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005831 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005832 if (EL0.Max == EL1.Max)
5833 MaxBECount = EL0.Max;
5834 if (EL0.Exact == EL1.Exact)
5835 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005836 }
5837
Silviu Baranga6f444df2016-04-08 14:29:09 +00005838 SCEVUnionPredicate NP;
5839 NP.add(&EL0.Pred);
5840 NP.add(&EL1.Pred);
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005841 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5842 // to be more aggressive when computing BECount than when computing
5843 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact
5844 // to match, but for EL0.Max and EL1.Max to not.
5845 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5846 !isa<SCEVCouldNotCompute>(BECount))
5847 MaxBECount = BECount;
5848
Silviu Baranga6f444df2016-04-08 14:29:09 +00005849 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005850 }
5851 if (BO->getOpcode() == Instruction::Or) {
5852 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005853 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005854 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005855 ControlsExit && !EitherMayExit,
5856 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005857 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005858 ControlsExit && !EitherMayExit,
5859 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005860 const SCEV *BECount = getCouldNotCompute();
5861 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005862 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005863 // Both conditions must be false for the loop to continue executing.
5864 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005865 if (EL0.Exact == getCouldNotCompute() ||
5866 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005867 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005868 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005869 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5870 if (EL0.Max == getCouldNotCompute())
5871 MaxBECount = EL1.Max;
5872 else if (EL1.Max == getCouldNotCompute())
5873 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005874 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005875 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005876 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005877 // Both conditions must be false at the same time for the loop to exit.
5878 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005879 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005880 if (EL0.Max == EL1.Max)
5881 MaxBECount = EL0.Max;
5882 if (EL0.Exact == EL1.Exact)
5883 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005884 }
5885
Silviu Baranga6f444df2016-04-08 14:29:09 +00005886 SCEVUnionPredicate NP;
5887 NP.add(&EL0.Pred);
5888 NP.add(&EL1.Pred);
5889 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005890 }
5891 }
5892
5893 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005894 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005895 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5896 ExitLimit EL =
5897 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5898 if (EL.hasFullInfo() || !AllowPredicates)
5899 return EL;
5900
5901 // Try again, but use SCEV predicates this time.
5902 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5903 /*AllowPredicates=*/true);
5904 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005905
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005906 // Check for a constant condition. These are normally stripped out by
5907 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5908 // preserve the CFG and is temporarily leaving constant conditions
5909 // in place.
5910 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5911 if (L->contains(FBB) == !CI->getZExtValue())
5912 // The backedge is always taken.
5913 return getCouldNotCompute();
5914 else
5915 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005916 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005917 }
5918
Eli Friedmanebf98b02009-05-09 12:32:42 +00005919 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005920 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005921}
5922
Andrew Trick3ca3f982011-07-26 17:19:55 +00005923ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005924ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005925 ICmpInst *ExitCond,
5926 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005927 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005928 bool ControlsExit,
5929 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005930
Reid Spencer266e42b2006-12-23 06:05:41 +00005931 // If the condition was exit on true, convert the condition to exit on false
5932 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005933 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005934 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005935 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005936 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005937
5938 // Handle common loops like: for (X = "string"; *X; ++X)
5939 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5940 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005941 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005942 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005943 if (ItCnt.hasAnyInfo())
5944 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005945 }
5946
Dan Gohmanaf752342009-07-07 17:06:11 +00005947 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5948 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005949
5950 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005951 LHS = getSCEVAtScope(LHS, L);
5952 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005953
Dan Gohmance973df2009-06-24 04:48:43 +00005954 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005955 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005956 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005957 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005958 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005959 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005960 }
5961
Dan Gohman81585c12010-05-03 16:35:17 +00005962 // Simplify the operands before analyzing them.
5963 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5964
Chris Lattnerd934c702004-04-02 20:23:17 +00005965 // If we have a comparison of a chrec against a constant, try to use value
5966 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005967 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5968 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005969 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005970 // Form the constant range.
5971 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00005972 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005973
Dan Gohmanaf752342009-07-07 17:06:11 +00005974 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005975 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005976 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005977
Chris Lattnerd934c702004-04-02 20:23:17 +00005978 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005979 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005980 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00005981 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005982 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005983 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005984 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005985 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005986 case ICmpInst::ICMP_EQ: { // while (X == Y)
5987 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00005988 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005989 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005990 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005991 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005992 case ICmpInst::ICMP_SLT:
5993 case ICmpInst::ICMP_ULT: { // while (X < Y)
5994 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00005995 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005996 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005997 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005998 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005999 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006000 case ICmpInst::ICMP_SGT:
6001 case ICmpInst::ICMP_UGT: { // while (X > Y)
6002 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006003 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006004 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006005 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006006 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006007 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006008 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006009 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006010 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006011 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006012
6013 auto *ExhaustiveCount =
6014 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6015
6016 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6017 return ExhaustiveCount;
6018
6019 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6020 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006021}
6022
Benjamin Kramer5a188542014-02-11 15:44:32 +00006023ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006024ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006025 SwitchInst *Switch,
6026 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006027 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006028 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6029
6030 // Give up if the exit is the default dest of a switch.
6031 if (Switch->getDefaultDest() == ExitingBlock)
6032 return getCouldNotCompute();
6033
6034 assert(L->contains(Switch->getDefaultDest()) &&
6035 "Default case must not exit the loop!");
6036 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6037 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6038
6039 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006040 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006041 if (EL.hasAnyInfo())
6042 return EL;
6043
6044 return getCouldNotCompute();
6045}
6046
Chris Lattnerec901cc2004-10-12 01:49:27 +00006047static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006048EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6049 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006050 const SCEV *InVal = SE.getConstant(C);
6051 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006052 assert(isa<SCEVConstant>(Val) &&
6053 "Evaluation of SCEV at constant didn't fold correctly?");
6054 return cast<SCEVConstant>(Val)->getValue();
6055}
6056
Sanjoy Dasf8570812016-05-29 00:38:22 +00006057/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6058/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006059ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006060ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006061 LoadInst *LI,
6062 Constant *RHS,
6063 const Loop *L,
6064 ICmpInst::Predicate predicate) {
6065
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006066 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006067
6068 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006069 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006070 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006071 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006072
6073 // Make sure that it is really a constant global we are gepping, with an
6074 // initializer, and make sure the first IDX is really 0.
6075 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006076 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006077 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6078 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006079 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006080
6081 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006082 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006083 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006084 unsigned VarIdxNum = 0;
6085 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6086 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6087 Indexes.push_back(CI);
6088 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006089 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006090 VarIdx = GEP->getOperand(i);
6091 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006092 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006093 }
6094
Andrew Trick7004e4b2012-03-26 22:33:59 +00006095 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6096 if (!VarIdx)
6097 return getCouldNotCompute();
6098
Chris Lattnerec901cc2004-10-12 01:49:27 +00006099 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6100 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006101 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006102 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006103
6104 // We can only recognize very limited forms of loop index expressions, in
6105 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006106 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006107 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006108 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6109 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006110 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006111
6112 unsigned MaxSteps = MaxBruteForceIterations;
6113 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006114 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006115 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006116 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006117
6118 // Form the GEP offset.
6119 Indexes[VarIdxNum] = Val;
6120
Chris Lattnere166a852012-01-24 05:49:24 +00006121 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6122 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006123 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006124
6125 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006126 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006127 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006128 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006129 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006130 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006131 }
6132 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006133 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006134}
6135
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006136ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6137 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6138 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6139 if (!RHS)
6140 return getCouldNotCompute();
6141
6142 const BasicBlock *Latch = L->getLoopLatch();
6143 if (!Latch)
6144 return getCouldNotCompute();
6145
6146 const BasicBlock *Predecessor = L->getLoopPredecessor();
6147 if (!Predecessor)
6148 return getCouldNotCompute();
6149
6150 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6151 // Return LHS in OutLHS and shift_opt in OutOpCode.
6152 auto MatchPositiveShift =
6153 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6154
6155 using namespace PatternMatch;
6156
6157 ConstantInt *ShiftAmt;
6158 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6159 OutOpCode = Instruction::LShr;
6160 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6161 OutOpCode = Instruction::AShr;
6162 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6163 OutOpCode = Instruction::Shl;
6164 else
6165 return false;
6166
6167 return ShiftAmt->getValue().isStrictlyPositive();
6168 };
6169
6170 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6171 //
6172 // loop:
6173 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6174 // %iv.shifted = lshr i32 %iv, <positive constant>
6175 //
6176 // Return true on a succesful match. Return the corresponding PHI node (%iv
6177 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6178 auto MatchShiftRecurrence =
6179 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6180 Optional<Instruction::BinaryOps> PostShiftOpCode;
6181
6182 {
6183 Instruction::BinaryOps OpC;
6184 Value *V;
6185
6186 // If we encounter a shift instruction, "peel off" the shift operation,
6187 // and remember that we did so. Later when we inspect %iv's backedge
6188 // value, we will make sure that the backedge value uses the same
6189 // operation.
6190 //
6191 // Note: the peeled shift operation does not have to be the same
6192 // instruction as the one feeding into the PHI's backedge value. We only
6193 // really care about it being the same *kind* of shift instruction --
6194 // that's all that is required for our later inferences to hold.
6195 if (MatchPositiveShift(LHS, V, OpC)) {
6196 PostShiftOpCode = OpC;
6197 LHS = V;
6198 }
6199 }
6200
6201 PNOut = dyn_cast<PHINode>(LHS);
6202 if (!PNOut || PNOut->getParent() != L->getHeader())
6203 return false;
6204
6205 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6206 Value *OpLHS;
6207
6208 return
6209 // The backedge value for the PHI node must be a shift by a positive
6210 // amount
6211 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6212
6213 // of the PHI node itself
6214 OpLHS == PNOut &&
6215
6216 // and the kind of shift should be match the kind of shift we peeled
6217 // off, if any.
6218 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6219 };
6220
6221 PHINode *PN;
6222 Instruction::BinaryOps OpCode;
6223 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6224 return getCouldNotCompute();
6225
6226 const DataLayout &DL = getDataLayout();
6227
6228 // The key rationale for this optimization is that for some kinds of shift
6229 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6230 // within a finite number of iterations. If the condition guarding the
6231 // backedge (in the sense that the backedge is taken if the condition is true)
6232 // is false for the value the shift recurrence stabilizes to, then we know
6233 // that the backedge is taken only a finite number of times.
6234
6235 ConstantInt *StableValue = nullptr;
6236 switch (OpCode) {
6237 default:
6238 llvm_unreachable("Impossible case!");
6239
6240 case Instruction::AShr: {
6241 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6242 // bitwidth(K) iterations.
6243 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6244 bool KnownZero, KnownOne;
6245 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6246 Predecessor->getTerminator(), &DT);
6247 auto *Ty = cast<IntegerType>(RHS->getType());
6248 if (KnownZero)
6249 StableValue = ConstantInt::get(Ty, 0);
6250 else if (KnownOne)
6251 StableValue = ConstantInt::get(Ty, -1, true);
6252 else
6253 return getCouldNotCompute();
6254
6255 break;
6256 }
6257 case Instruction::LShr:
6258 case Instruction::Shl:
6259 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6260 // stabilize to 0 in at most bitwidth(K) iterations.
6261 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6262 break;
6263 }
6264
6265 auto *Result =
6266 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6267 assert(Result->getType()->isIntegerTy(1) &&
6268 "Otherwise cannot be an operand to a branch instruction");
6269
6270 if (Result->isZeroValue()) {
6271 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6272 const SCEV *UpperBound =
6273 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
Silviu Baranga6f444df2016-04-08 14:29:09 +00006274 SCEVUnionPredicate P;
6275 return ExitLimit(getCouldNotCompute(), UpperBound, P);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006276 }
6277
6278 return getCouldNotCompute();
6279}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006280
Sanjoy Dasf8570812016-05-29 00:38:22 +00006281/// Return true if we can constant fold an instruction of the specified type,
6282/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006283static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006284 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006285 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6286 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006287 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006288
Chris Lattnerdd730472004-04-17 22:58:41 +00006289 if (const CallInst *CI = dyn_cast<CallInst>(I))
6290 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006291 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006292 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006293}
6294
Andrew Trick3a86ba72011-10-05 03:25:31 +00006295/// Determine whether this instruction can constant evolve within this loop
6296/// assuming its operands can all constant evolve.
6297static bool canConstantEvolve(Instruction *I, const Loop *L) {
6298 // An instruction outside of the loop can't be derived from a loop PHI.
6299 if (!L->contains(I)) return false;
6300
6301 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006302 // We don't currently keep track of the control flow needed to evaluate
6303 // PHIs, so we cannot handle PHIs inside of loops.
6304 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006305 }
6306
6307 // If we won't be able to constant fold this expression even if the operands
6308 // are constants, bail early.
6309 return CanConstantFold(I);
6310}
6311
6312/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6313/// recursing through each instruction operand until reaching a loop header phi.
6314static PHINode *
6315getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006316 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006317
6318 // Otherwise, we can evaluate this instruction if all of its operands are
6319 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006320 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006321 for (Value *Op : UseInst->operands()) {
6322 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006323
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006324 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006325 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006326
6327 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006328 if (!P)
6329 // If this operand is already visited, reuse the prior result.
6330 // We may have P != PHI if this is the deepest point at which the
6331 // inconsistent paths meet.
6332 P = PHIMap.lookup(OpInst);
6333 if (!P) {
6334 // Recurse and memoize the results, whether a phi is found or not.
6335 // This recursive call invalidates pointers into PHIMap.
6336 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6337 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006338 }
Craig Topper9f008862014-04-15 04:59:12 +00006339 if (!P)
6340 return nullptr; // Not evolving from PHI
6341 if (PHI && PHI != P)
6342 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006343 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006344 }
6345 // This is a expression evolving from a constant PHI!
6346 return PHI;
6347}
6348
Chris Lattnerdd730472004-04-17 22:58:41 +00006349/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6350/// in the loop that V is derived from. We allow arbitrary operations along the
6351/// way, but the operands of an operation must either be constants or a value
6352/// derived from a constant PHI. If this expression does not fit with these
6353/// constraints, return null.
6354static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006355 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006356 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006357
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006358 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006359 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006360
Andrew Trick3a86ba72011-10-05 03:25:31 +00006361 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006362 DenseMap<Instruction *, PHINode *> PHIMap;
6363 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006364}
6365
6366/// EvaluateExpression - Given an expression that passes the
6367/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6368/// in the loop has the value PHIVal. If we can't fold this expression for some
6369/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006370static Constant *EvaluateExpression(Value *V, const Loop *L,
6371 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006372 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006373 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006374 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006375 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006376 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006377 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006378
Andrew Trick3a86ba72011-10-05 03:25:31 +00006379 if (Constant *C = Vals.lookup(I)) return C;
6380
Nick Lewyckya6674c72011-10-22 19:58:20 +00006381 // An instruction inside the loop depends on a value outside the loop that we
6382 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006383 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006384
6385 // An unmapped PHI can be due to a branch or another loop inside this loop,
6386 // or due to this not being the initial iteration through a loop where we
6387 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006388 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006389
Dan Gohmanf820bd32010-06-22 13:15:46 +00006390 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006391
6392 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006393 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6394 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006395 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006396 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006397 continue;
6398 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006399 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006400 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006401 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006402 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006403 }
6404
Nick Lewyckya6674c72011-10-22 19:58:20 +00006405 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006406 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006407 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006408 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6409 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006410 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006411 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006412 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006413}
6414
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006415
6416// If every incoming value to PN except the one for BB is a specific Constant,
6417// return that, else return nullptr.
6418static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6419 Constant *IncomingVal = nullptr;
6420
6421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6422 if (PN->getIncomingBlock(i) == BB)
6423 continue;
6424
6425 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6426 if (!CurrentVal)
6427 return nullptr;
6428
6429 if (IncomingVal != CurrentVal) {
6430 if (IncomingVal)
6431 return nullptr;
6432 IncomingVal = CurrentVal;
6433 }
6434 }
6435
6436 return IncomingVal;
6437}
6438
Chris Lattnerdd730472004-04-17 22:58:41 +00006439/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6440/// in the header of its containing loop, we know the loop executes a
6441/// constant number of times, and the PHI node is just a recurrence
6442/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006443Constant *
6444ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006445 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006446 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006447 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006448 if (I != ConstantEvolutionLoopExitValue.end())
6449 return I->second;
6450
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006451 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006452 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006453
6454 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6455
Andrew Trick3a86ba72011-10-05 03:25:31 +00006456 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006457 BasicBlock *Header = L->getHeader();
6458 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006459
Sanjoy Dasdd709962015-10-08 18:28:36 +00006460 BasicBlock *Latch = L->getLoopLatch();
6461 if (!Latch)
6462 return nullptr;
6463
Sanjoy Das4493b402015-10-07 17:38:25 +00006464 for (auto &I : *Header) {
6465 PHINode *PHI = dyn_cast<PHINode>(&I);
6466 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006467 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006468 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006469 CurrentIterVals[PHI] = StartCST;
6470 }
6471 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006472 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006473
Sanjoy Dasdd709962015-10-08 18:28:36 +00006474 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006475
6476 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006477 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006478 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006479
Dan Gohman0bddac12009-02-24 18:55:53 +00006480 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006481 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006482 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006483 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006484 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006485 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006486
Nick Lewyckya6674c72011-10-22 19:58:20 +00006487 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006488 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006489 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006490 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006491 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006492 if (!NextPHI)
6493 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006494 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006495
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006496 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6497
Nick Lewyckya6674c72011-10-22 19:58:20 +00006498 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6499 // cease to be able to evaluate one of them or if they stop evolving,
6500 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006501 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006502 for (const auto &I : CurrentIterVals) {
6503 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006504 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006505 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006506 }
6507 // We use two distinct loops because EvaluateExpression may invalidate any
6508 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006509 for (const auto &I : PHIsToCompute) {
6510 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006511 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006512 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006513 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006514 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006515 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006516 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006517 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006518 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006519
6520 // If all entries in CurrentIterVals == NextIterVals then we can stop
6521 // iterating, the loop can't continue to change.
6522 if (StoppedEvolving)
6523 return RetVal = CurrentIterVals[PN];
6524
Andrew Trick3a86ba72011-10-05 03:25:31 +00006525 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006526 }
6527}
6528
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006529const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006530 Value *Cond,
6531 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006532 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006533 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006534
Dan Gohman866971e2010-06-19 14:17:24 +00006535 // If the loop is canonicalized, the PHI will have exactly two entries.
6536 // That's the only form we support here.
6537 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6538
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006539 DenseMap<Instruction *, Constant *> CurrentIterVals;
6540 BasicBlock *Header = L->getHeader();
6541 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6542
Sanjoy Dasdd709962015-10-08 18:28:36 +00006543 BasicBlock *Latch = L->getLoopLatch();
6544 assert(Latch && "Should follow from NumIncomingValues == 2!");
6545
Sanjoy Das4493b402015-10-07 17:38:25 +00006546 for (auto &I : *Header) {
6547 PHINode *PHI = dyn_cast<PHINode>(&I);
6548 if (!PHI)
6549 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006550 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006551 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006552 CurrentIterVals[PHI] = StartCST;
6553 }
6554 if (!CurrentIterVals.count(PN))
6555 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006556
6557 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6558 // the loop symbolically to determine when the condition gets a value of
6559 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006560 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006561 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006562 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006563 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006564 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006565
Zhou Sheng75b871f2007-01-11 12:24:14 +00006566 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006567 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006568
Reid Spencer983e3b32007-03-01 07:25:48 +00006569 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006570 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006571 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006572 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006573
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006574 // Update all the PHI nodes for the next iteration.
6575 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006576
6577 // Create a list of which PHIs we need to compute. We want to do this before
6578 // calling EvaluateExpression on them because that may invalidate iterators
6579 // into CurrentIterVals.
6580 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006581 for (const auto &I : CurrentIterVals) {
6582 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006583 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006584 PHIsToCompute.push_back(PHI);
6585 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006586 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006587 Constant *&NextPHI = NextIterVals[PHI];
6588 if (NextPHI) continue; // Already computed!
6589
Sanjoy Dasdd709962015-10-08 18:28:36 +00006590 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006591 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006592 }
6593 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006594 }
6595
6596 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006597 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006598}
6599
Dan Gohmanaf752342009-07-07 17:06:11 +00006600const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006601 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6602 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006603 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006604 for (auto &LS : Values)
6605 if (LS.first == L)
6606 return LS.second ? LS.second : V;
6607
6608 Values.emplace_back(L, nullptr);
6609
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006610 // Otherwise compute it.
6611 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006612 for (auto &LS : reverse(ValuesAtScopes[V]))
6613 if (LS.first == L) {
6614 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006615 break;
6616 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006617 return C;
6618}
6619
Nick Lewyckya6674c72011-10-22 19:58:20 +00006620/// This builds up a Constant using the ConstantExpr interface. That way, we
6621/// will return Constants for objects which aren't represented by a
6622/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6623/// Returns NULL if the SCEV isn't representable as a Constant.
6624static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006625 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006626 case scCouldNotCompute:
6627 case scAddRecExpr:
6628 break;
6629 case scConstant:
6630 return cast<SCEVConstant>(V)->getValue();
6631 case scUnknown:
6632 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6633 case scSignExtend: {
6634 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6635 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6636 return ConstantExpr::getSExt(CastOp, SS->getType());
6637 break;
6638 }
6639 case scZeroExtend: {
6640 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6641 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6642 return ConstantExpr::getZExt(CastOp, SZ->getType());
6643 break;
6644 }
6645 case scTruncate: {
6646 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6647 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6648 return ConstantExpr::getTrunc(CastOp, ST->getType());
6649 break;
6650 }
6651 case scAddExpr: {
6652 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6653 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006654 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6655 unsigned AS = PTy->getAddressSpace();
6656 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6657 C = ConstantExpr::getBitCast(C, DestPtrTy);
6658 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006659 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6660 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006661 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006662
6663 // First pointer!
6664 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006665 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006666 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006667 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006668 // The offsets have been converted to bytes. We can add bytes to an
6669 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006670 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006671 }
6672
6673 // Don't bother trying to sum two pointers. We probably can't
6674 // statically compute a load that results from it anyway.
6675 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006676 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006677
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006678 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6679 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006680 C2 = ConstantExpr::getIntegerCast(
6681 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006682 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006683 } else
6684 C = ConstantExpr::getAdd(C, C2);
6685 }
6686 return C;
6687 }
6688 break;
6689 }
6690 case scMulExpr: {
6691 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6692 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6693 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006694 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006695 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6696 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006697 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006698 C = ConstantExpr::getMul(C, C2);
6699 }
6700 return C;
6701 }
6702 break;
6703 }
6704 case scUDivExpr: {
6705 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6706 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6707 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6708 if (LHS->getType() == RHS->getType())
6709 return ConstantExpr::getUDiv(LHS, RHS);
6710 break;
6711 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006712 case scSMaxExpr:
6713 case scUMaxExpr:
6714 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006715 }
Craig Topper9f008862014-04-15 04:59:12 +00006716 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006717}
6718
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006719const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006720 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006721
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006722 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006723 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006724 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006725 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006726 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006727 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6728 if (PHINode *PN = dyn_cast<PHINode>(I))
6729 if (PN->getParent() == LI->getHeader()) {
6730 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006731 // to see if the loop that contains it has a known backedge-taken
6732 // count. If so, we may be able to force computation of the exit
6733 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006734 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006735 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006736 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006737 // Okay, we know how many times the containing loop executes. If
6738 // this is a constant evolving PHI node, get the final value at
6739 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006740 Constant *RV =
6741 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006742 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006743 }
6744 }
6745
Reid Spencere6328ca2006-12-04 21:33:23 +00006746 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006747 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006748 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006749 // result. This is particularly useful for computing loop exit values.
6750 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006751 SmallVector<Constant *, 4> Operands;
6752 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006753 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006754 if (Constant *C = dyn_cast<Constant>(Op)) {
6755 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006756 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006757 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006758
6759 // If any of the operands is non-constant and if they are
6760 // non-integer and non-pointer, don't even try to analyze them
6761 // with scev techniques.
6762 if (!isSCEVable(Op->getType()))
6763 return V;
6764
6765 const SCEV *OrigV = getSCEV(Op);
6766 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6767 MadeImprovement |= OrigV != OpV;
6768
Nick Lewyckya6674c72011-10-22 19:58:20 +00006769 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006770 if (!C) return V;
6771 if (C->getType() != Op->getType())
6772 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6773 Op->getType(),
6774 false),
6775 C, Op->getType());
6776 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006777 }
Dan Gohmance973df2009-06-24 04:48:43 +00006778
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006779 // Check to see if getSCEVAtScope actually made an improvement.
6780 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006781 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006782 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006783 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006784 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006785 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006786 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6787 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006788 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006789 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006790 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006791 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006792 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006793 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006794 }
6795 }
6796
6797 // This is some other type of SCEVUnknown, just return it.
6798 return V;
6799 }
6800
Dan Gohmana30370b2009-05-04 22:02:23 +00006801 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006802 // Avoid performing the look-up in the common case where the specified
6803 // expression has no loop-variant portions.
6804 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006805 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006806 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006807 // Okay, at least one of these operands is loop variant but might be
6808 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006809 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6810 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006811 NewOps.push_back(OpAtScope);
6812
6813 for (++i; i != e; ++i) {
6814 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006815 NewOps.push_back(OpAtScope);
6816 }
6817 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006818 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006819 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006820 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006821 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006822 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006823 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006824 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006825 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006826 }
6827 }
6828 // If we got here, all operands are loop invariant.
6829 return Comm;
6830 }
6831
Dan Gohmana30370b2009-05-04 22:02:23 +00006832 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006833 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6834 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006835 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6836 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006837 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006838 }
6839
6840 // If this is a loop recurrence for a loop that does not contain L, then we
6841 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006842 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006843 // First, attempt to evaluate each operand.
6844 // Avoid performing the look-up in the common case where the specified
6845 // expression has no loop-variant portions.
6846 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6847 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6848 if (OpAtScope == AddRec->getOperand(i))
6849 continue;
6850
6851 // Okay, at least one of these operands is loop variant but might be
6852 // foldable. Build a new instance of the folded commutative expression.
6853 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6854 AddRec->op_begin()+i);
6855 NewOps.push_back(OpAtScope);
6856 for (++i; i != e; ++i)
6857 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6858
Andrew Trick759ba082011-04-27 01:21:25 +00006859 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006860 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006861 AddRec->getNoWrapFlags(SCEV::FlagNW));
6862 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006863 // The addrec may be folded to a nonrecurrence, for example, if the
6864 // induction variable is multiplied by zero after constant folding. Go
6865 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006866 if (!AddRec)
6867 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006868 break;
6869 }
6870
6871 // If the scope is outside the addrec's loop, evaluate it by using the
6872 // loop exit value of the addrec.
6873 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006874 // To evaluate this recurrence, we need to know how many times the AddRec
6875 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006876 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006877 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006878
Eli Friedman61f67622008-08-04 23:49:06 +00006879 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006880 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006881 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006882
Dan Gohman8ca08852009-05-24 23:25:42 +00006883 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006884 }
6885
Dan Gohmana30370b2009-05-04 22:02:23 +00006886 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006887 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006888 if (Op == Cast->getOperand())
6889 return Cast; // must be loop invariant
6890 return getZeroExtendExpr(Op, Cast->getType());
6891 }
6892
Dan Gohmana30370b2009-05-04 22:02:23 +00006893 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006894 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006895 if (Op == Cast->getOperand())
6896 return Cast; // must be loop invariant
6897 return getSignExtendExpr(Op, Cast->getType());
6898 }
6899
Dan Gohmana30370b2009-05-04 22:02:23 +00006900 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006901 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006902 if (Op == Cast->getOperand())
6903 return Cast; // must be loop invariant
6904 return getTruncateExpr(Op, Cast->getType());
6905 }
6906
Torok Edwinfbcc6632009-07-14 16:55:14 +00006907 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006908}
6909
Dan Gohmanaf752342009-07-07 17:06:11 +00006910const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006911 return getSCEVAtScope(getSCEV(V), L);
6912}
6913
Sanjoy Dasf8570812016-05-29 00:38:22 +00006914/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006915///
6916/// A * X = B (mod N)
6917///
6918/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6919/// A and B isn't important.
6920///
6921/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006922static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006923 ScalarEvolution &SE) {
6924 uint32_t BW = A.getBitWidth();
6925 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6926 assert(A != 0 && "A must be non-zero.");
6927
6928 // 1. D = gcd(A, N)
6929 //
6930 // The gcd of A and N may have only one prime factor: 2. The number of
6931 // trailing zeros in A is its multiplicity
6932 uint32_t Mult2 = A.countTrailingZeros();
6933 // D = 2^Mult2
6934
6935 // 2. Check if B is divisible by D.
6936 //
6937 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6938 // is not less than multiplicity of this prime factor for D.
6939 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006940 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006941
6942 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6943 // modulo (N / D).
6944 //
6945 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6946 // bit width during computations.
6947 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6948 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006949 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006950 APInt I = AD.multiplicativeInverse(Mod);
6951
6952 // 4. Compute the minimum unsigned root of the equation:
6953 // I * (B / D) mod (N / D)
6954 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6955
6956 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6957 // bits.
6958 return SE.getConstant(Result.trunc(BW));
6959}
Chris Lattnerd934c702004-04-02 20:23:17 +00006960
Sanjoy Dasf8570812016-05-29 00:38:22 +00006961/// Find the roots of the quadratic equation for the given quadratic chrec
6962/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
6963/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00006964///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00006965static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006966SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006967 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006968 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6969 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6970 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006971
Chris Lattnerd934c702004-04-02 20:23:17 +00006972 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00006973 if (!LC || !MC || !NC)
6974 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00006975
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006976 uint32_t BitWidth = LC->getAPInt().getBitWidth();
6977 const APInt &L = LC->getAPInt();
6978 const APInt &M = MC->getAPInt();
6979 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00006980 APInt Two(BitWidth, 2);
6981 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006982
Dan Gohmance973df2009-06-24 04:48:43 +00006983 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006984 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006985 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006986 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6987 // The B coefficient is M-N/2
6988 APInt B(M);
6989 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006990
Reid Spencer983e3b32007-03-01 07:25:48 +00006991 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006992 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006993
Reid Spencer983e3b32007-03-01 07:25:48 +00006994 // Compute the B^2-4ac term.
6995 APInt SqrtTerm(B);
6996 SqrtTerm *= B;
6997 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006998
Nick Lewyckyfb780832012-08-01 09:14:36 +00006999 if (SqrtTerm.isNegative()) {
7000 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007001 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007002 }
7003
Reid Spencer983e3b32007-03-01 07:25:48 +00007004 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7005 // integer value or else APInt::sqrt() will assert.
7006 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007007
Dan Gohmance973df2009-06-24 04:48:43 +00007008 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007009 // The divisions must be performed as signed divisions.
7010 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007011 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007012 if (TwoA.isMinValue())
7013 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007014
Owen Anderson47db9412009-07-22 00:24:57 +00007015 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007016
7017 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007018 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007019 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007020 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007021
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007022 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7023 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007024 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007025}
7026
Andrew Trick3ca3f982011-07-26 17:19:55 +00007027ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007028ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007029 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007030
7031 // This is only used for loops with a "x != y" exit test. The exit condition
7032 // is now expressed as a single expression, V = x-y. So the exit test is
7033 // effectively V != 0. We know and take advantage of the fact that this
7034 // expression only being used in a comparison by zero context.
7035
Silviu Baranga6f444df2016-04-08 14:29:09 +00007036 SCEVUnionPredicate P;
Chris Lattnerd934c702004-04-02 20:23:17 +00007037 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007038 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007039 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007040 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007041 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007042 }
7043
Dan Gohman48f82222009-05-04 22:30:44 +00007044 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007045 if (!AddRec && AllowPredicates)
7046 // Try to make this an AddRec using runtime tests, in the first X
7047 // iterations of this loop, where X is the SCEV expression found by the
7048 // algorithm below.
7049 AddRec = convertSCEVToAddRecWithPredicates(V, L, P);
7050
Chris Lattnerd934c702004-04-02 20:23:17 +00007051 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007052 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007053
Chris Lattnerdff679f2011-01-09 22:39:48 +00007054 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7055 // the quadratic equation to solve it.
7056 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007057 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7058 const SCEVConstant *R1 = Roots->first;
7059 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007060 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007061 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7062 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007063 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007064 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007065
Chris Lattnerd934c702004-04-02 20:23:17 +00007066 // We can only use this value if the chrec ends up with an exact zero
7067 // value at this index. When solving for "X*X != 5", for example, we
7068 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007069 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007070 if (Val->isZero())
Silviu Baranga6f444df2016-04-08 14:29:09 +00007071 return ExitLimit(R1, R1, P); // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00007072 }
7073 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007074 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007075 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007076
Chris Lattnerdff679f2011-01-09 22:39:48 +00007077 // Otherwise we can only handle this if it is affine.
7078 if (!AddRec->isAffine())
7079 return getCouldNotCompute();
7080
7081 // If this is an affine expression, the execution count of this branch is
7082 // the minimum unsigned root of the following equation:
7083 //
7084 // Start + Step*N = 0 (mod 2^BW)
7085 //
7086 // equivalent to:
7087 //
7088 // Step*N = -Start (mod 2^BW)
7089 //
7090 // where BW is the common bit width of Start and Step.
7091
7092 // Get the initial value for the loop.
7093 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7094 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7095
7096 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007097 //
7098 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7099 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7100 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7101 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007102 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007103 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007104 return getCouldNotCompute();
7105
Andrew Trick8b55b732011-03-14 16:50:06 +00007106 // For positive steps (counting up until unsigned overflow):
7107 // N = -Start/Step (as unsigned)
7108 // For negative steps (counting down to zero):
7109 // N = Start/-Step
7110 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007111 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007112 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007113
7114 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007115 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7116 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007117 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7118 ConstantRange CR = getUnsignedRange(Start);
7119 const SCEV *MaxBECount;
7120 if (!CountDown && CR.getUnsignedMin().isMinValue())
7121 // When counting up, the worst starting value is 1, not 0.
7122 MaxBECount = CR.getUnsignedMax().isMinValue()
7123 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7124 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7125 else
7126 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7127 : -CR.getUnsignedMin());
Silviu Baranga6f444df2016-04-08 14:29:09 +00007128 return ExitLimit(Distance, MaxBECount, P);
Nick Lewycky31555522011-10-03 07:10:45 +00007129 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007130
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007131 // As a special case, handle the instance where Step is a positive power of
7132 // two. In this case, determining whether Step divides Distance evenly can be
7133 // done by counting and comparing the number of trailing zeros of Step and
7134 // Distance.
7135 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007136 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007137 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7138 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7139 // case is not handled as this code is guarded by !CountDown.
7140 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007141 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7142 // Here we've constrained the equation to be of the form
7143 //
7144 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7145 //
7146 // where we're operating on a W bit wide integer domain and k is
7147 // non-negative. The smallest unsigned solution for X is the trip count.
7148 //
7149 // (0) is equivalent to:
7150 //
7151 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7152 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7153 // <=> 2^k * Distance' - X = L * 2^(W - N)
7154 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7155 //
7156 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7157 // by 2^(W - N).
7158 //
7159 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7160 //
7161 // E.g. say we're solving
7162 //
7163 // 2 * Val = 2 * X (in i8) ... (3)
7164 //
7165 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7166 //
7167 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7168 // necessarily the smallest unsigned value of X that satisfies (3).
7169 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7170 // is i8 1, not i8 -127
7171
7172 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7173
7174 // Since SCEV does not have a URem node, we construct one using a truncate
7175 // and a zero extend.
7176
7177 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7178 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7179 auto *WideTy = Distance->getType();
7180
Silviu Baranga6f444df2016-04-08 14:29:09 +00007181 const SCEV *Limit =
7182 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7183 return ExitLimit(Limit, Limit, P);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007184 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007185 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007186
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007187 // If the condition controls loop exit (the loop exits only if the expression
7188 // is true) and the addition is no-wrap we can use unsigned divide to
7189 // compute the backedge count. In this case, the step may not divide the
7190 // distance, but we don't care because if the condition is "missed" the loop
7191 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007192 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7193 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007194 const SCEV *Exact =
7195 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007196 return ExitLimit(Exact, Exact, P);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007197 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007198
Chris Lattnerdff679f2011-01-09 22:39:48 +00007199 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007200 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7201 const SCEV *E = SolveLinEquationWithOverflow(
7202 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7203 return ExitLimit(E, E, P);
7204 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007205 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007206}
7207
Andrew Trick3ca3f982011-07-26 17:19:55 +00007208ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007209ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007210 // Loops that look like: while (X == 0) are very strange indeed. We don't
7211 // handle them yet except for the trivial case. This could be expanded in the
7212 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007213
Chris Lattnerd934c702004-04-02 20:23:17 +00007214 // If the value is a constant, check to see if it is known to be non-zero
7215 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007216 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007217 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007218 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007219 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007220 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007221
Chris Lattnerd934c702004-04-02 20:23:17 +00007222 // We could implement others, but I really doubt anyone writes loops like
7223 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007224 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007225}
7226
Dan Gohman4e3c1132010-04-15 16:19:08 +00007227std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007228ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007229 // If the block has a unique predecessor, then there is no path from the
7230 // predecessor to the block that does not go through the direct edge
7231 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007232 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007233 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007234
7235 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007236 // If the header has a unique predecessor outside the loop, it must be
7237 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007238 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007239 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007240
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007241 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007242}
7243
Sanjoy Dasf8570812016-05-29 00:38:22 +00007244/// SCEV structural equivalence is usually sufficient for testing whether two
7245/// expressions are equal, however for the purposes of looking for a condition
7246/// guarding a loop, it can be useful to be a little more general, since a
7247/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007248///
Dan Gohmanaf752342009-07-07 17:06:11 +00007249static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007250 // Quick check to see if they are the same SCEV.
7251 if (A == B) return true;
7252
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007253 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7254 // Not all instructions that are "identical" compute the same value. For
7255 // instance, two distinct alloca instructions allocating the same type are
7256 // identical and do not read memory; but compute distinct values.
7257 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7258 };
7259
Dan Gohman450f4e02009-06-20 00:35:32 +00007260 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7261 // two different instructions with the same value. Check for this case.
7262 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7263 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7264 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7265 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007266 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007267 return true;
7268
7269 // Otherwise assume they may have a different value.
7270 return false;
7271}
7272
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007273bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007274 const SCEV *&LHS, const SCEV *&RHS,
7275 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007276 bool Changed = false;
7277
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007278 // If we hit the max recursion limit bail out.
7279 if (Depth >= 3)
7280 return false;
7281
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007282 // Canonicalize a constant to the right side.
7283 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7284 // Check for both operands constant.
7285 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7286 if (ConstantExpr::getICmp(Pred,
7287 LHSC->getValue(),
7288 RHSC->getValue())->isNullValue())
7289 goto trivially_false;
7290 else
7291 goto trivially_true;
7292 }
7293 // Otherwise swap the operands to put the constant on the right.
7294 std::swap(LHS, RHS);
7295 Pred = ICmpInst::getSwappedPredicate(Pred);
7296 Changed = true;
7297 }
7298
7299 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007300 // addrec's loop, put the addrec on the left. Also make a dominance check,
7301 // as both operands could be addrecs loop-invariant in each other's loop.
7302 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7303 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007304 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007305 std::swap(LHS, RHS);
7306 Pred = ICmpInst::getSwappedPredicate(Pred);
7307 Changed = true;
7308 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007309 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007310
7311 // If there's a constant operand, canonicalize comparisons with boundary
7312 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7313 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007314 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007315 switch (Pred) {
7316 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7317 case ICmpInst::ICMP_EQ:
7318 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007319 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7320 if (!RA)
7321 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7322 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00007323 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7324 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007325 RHS = AE->getOperand(1);
7326 LHS = ME->getOperand(1);
7327 Changed = true;
7328 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007329 break;
7330 case ICmpInst::ICMP_UGE:
7331 if ((RA - 1).isMinValue()) {
7332 Pred = ICmpInst::ICMP_NE;
7333 RHS = getConstant(RA - 1);
7334 Changed = true;
7335 break;
7336 }
7337 if (RA.isMaxValue()) {
7338 Pred = ICmpInst::ICMP_EQ;
7339 Changed = true;
7340 break;
7341 }
7342 if (RA.isMinValue()) goto trivially_true;
7343
7344 Pred = ICmpInst::ICMP_UGT;
7345 RHS = getConstant(RA - 1);
7346 Changed = true;
7347 break;
7348 case ICmpInst::ICMP_ULE:
7349 if ((RA + 1).isMaxValue()) {
7350 Pred = ICmpInst::ICMP_NE;
7351 RHS = getConstant(RA + 1);
7352 Changed = true;
7353 break;
7354 }
7355 if (RA.isMinValue()) {
7356 Pred = ICmpInst::ICMP_EQ;
7357 Changed = true;
7358 break;
7359 }
7360 if (RA.isMaxValue()) goto trivially_true;
7361
7362 Pred = ICmpInst::ICMP_ULT;
7363 RHS = getConstant(RA + 1);
7364 Changed = true;
7365 break;
7366 case ICmpInst::ICMP_SGE:
7367 if ((RA - 1).isMinSignedValue()) {
7368 Pred = ICmpInst::ICMP_NE;
7369 RHS = getConstant(RA - 1);
7370 Changed = true;
7371 break;
7372 }
7373 if (RA.isMaxSignedValue()) {
7374 Pred = ICmpInst::ICMP_EQ;
7375 Changed = true;
7376 break;
7377 }
7378 if (RA.isMinSignedValue()) goto trivially_true;
7379
7380 Pred = ICmpInst::ICMP_SGT;
7381 RHS = getConstant(RA - 1);
7382 Changed = true;
7383 break;
7384 case ICmpInst::ICMP_SLE:
7385 if ((RA + 1).isMaxSignedValue()) {
7386 Pred = ICmpInst::ICMP_NE;
7387 RHS = getConstant(RA + 1);
7388 Changed = true;
7389 break;
7390 }
7391 if (RA.isMinSignedValue()) {
7392 Pred = ICmpInst::ICMP_EQ;
7393 Changed = true;
7394 break;
7395 }
7396 if (RA.isMaxSignedValue()) goto trivially_true;
7397
7398 Pred = ICmpInst::ICMP_SLT;
7399 RHS = getConstant(RA + 1);
7400 Changed = true;
7401 break;
7402 case ICmpInst::ICMP_UGT:
7403 if (RA.isMinValue()) {
7404 Pred = ICmpInst::ICMP_NE;
7405 Changed = true;
7406 break;
7407 }
7408 if ((RA + 1).isMaxValue()) {
7409 Pred = ICmpInst::ICMP_EQ;
7410 RHS = getConstant(RA + 1);
7411 Changed = true;
7412 break;
7413 }
7414 if (RA.isMaxValue()) goto trivially_false;
7415 break;
7416 case ICmpInst::ICMP_ULT:
7417 if (RA.isMaxValue()) {
7418 Pred = ICmpInst::ICMP_NE;
7419 Changed = true;
7420 break;
7421 }
7422 if ((RA - 1).isMinValue()) {
7423 Pred = ICmpInst::ICMP_EQ;
7424 RHS = getConstant(RA - 1);
7425 Changed = true;
7426 break;
7427 }
7428 if (RA.isMinValue()) goto trivially_false;
7429 break;
7430 case ICmpInst::ICMP_SGT:
7431 if (RA.isMinSignedValue()) {
7432 Pred = ICmpInst::ICMP_NE;
7433 Changed = true;
7434 break;
7435 }
7436 if ((RA + 1).isMaxSignedValue()) {
7437 Pred = ICmpInst::ICMP_EQ;
7438 RHS = getConstant(RA + 1);
7439 Changed = true;
7440 break;
7441 }
7442 if (RA.isMaxSignedValue()) goto trivially_false;
7443 break;
7444 case ICmpInst::ICMP_SLT:
7445 if (RA.isMaxSignedValue()) {
7446 Pred = ICmpInst::ICMP_NE;
7447 Changed = true;
7448 break;
7449 }
7450 if ((RA - 1).isMinSignedValue()) {
7451 Pred = ICmpInst::ICMP_EQ;
7452 RHS = getConstant(RA - 1);
7453 Changed = true;
7454 break;
7455 }
7456 if (RA.isMinSignedValue()) goto trivially_false;
7457 break;
7458 }
7459 }
7460
7461 // Check for obvious equality.
7462 if (HasSameValue(LHS, RHS)) {
7463 if (ICmpInst::isTrueWhenEqual(Pred))
7464 goto trivially_true;
7465 if (ICmpInst::isFalseWhenEqual(Pred))
7466 goto trivially_false;
7467 }
7468
Dan Gohman81585c12010-05-03 16:35:17 +00007469 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7470 // adding or subtracting 1 from one of the operands.
7471 switch (Pred) {
7472 case ICmpInst::ICMP_SLE:
7473 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7474 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007475 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007476 Pred = ICmpInst::ICMP_SLT;
7477 Changed = true;
7478 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007479 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007480 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007481 Pred = ICmpInst::ICMP_SLT;
7482 Changed = true;
7483 }
7484 break;
7485 case ICmpInst::ICMP_SGE:
7486 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007487 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007488 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007489 Pred = ICmpInst::ICMP_SGT;
7490 Changed = true;
7491 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7492 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007493 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007494 Pred = ICmpInst::ICMP_SGT;
7495 Changed = true;
7496 }
7497 break;
7498 case ICmpInst::ICMP_ULE:
7499 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007500 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007501 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007502 Pred = ICmpInst::ICMP_ULT;
7503 Changed = true;
7504 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007505 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007506 Pred = ICmpInst::ICMP_ULT;
7507 Changed = true;
7508 }
7509 break;
7510 case ICmpInst::ICMP_UGE:
7511 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007512 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007513 Pred = ICmpInst::ICMP_UGT;
7514 Changed = true;
7515 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007516 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007517 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007518 Pred = ICmpInst::ICMP_UGT;
7519 Changed = true;
7520 }
7521 break;
7522 default:
7523 break;
7524 }
7525
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007526 // TODO: More simplifications are possible here.
7527
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007528 // Recursively simplify until we either hit a recursion limit or nothing
7529 // changes.
7530 if (Changed)
7531 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7532
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007533 return Changed;
7534
7535trivially_true:
7536 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007537 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007538 Pred = ICmpInst::ICMP_EQ;
7539 return true;
7540
7541trivially_false:
7542 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007543 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007544 Pred = ICmpInst::ICMP_NE;
7545 return true;
7546}
7547
Dan Gohmane65c9172009-07-13 21:35:55 +00007548bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7549 return getSignedRange(S).getSignedMax().isNegative();
7550}
7551
7552bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7553 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7554}
7555
7556bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7557 return !getSignedRange(S).getSignedMin().isNegative();
7558}
7559
7560bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7561 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7562}
7563
7564bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7565 return isKnownNegative(S) || isKnownPositive(S);
7566}
7567
7568bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7569 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007570 // Canonicalize the inputs first.
7571 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7572
Dan Gohman07591692010-04-11 22:16:48 +00007573 // If LHS or RHS is an addrec, check to see if the condition is true in
7574 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007575 // If LHS and RHS are both addrec, both conditions must be true in
7576 // every iteration of the loop.
7577 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7578 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7579 bool LeftGuarded = false;
7580 bool RightGuarded = false;
7581 if (LAR) {
7582 const Loop *L = LAR->getLoop();
7583 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7584 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7585 if (!RAR) return true;
7586 LeftGuarded = true;
7587 }
7588 }
7589 if (RAR) {
7590 const Loop *L = RAR->getLoop();
7591 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7592 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7593 if (!LAR) return true;
7594 RightGuarded = true;
7595 }
7596 }
7597 if (LeftGuarded && RightGuarded)
7598 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007599
Sanjoy Das7d910f22015-10-02 18:50:30 +00007600 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7601 return true;
7602
Dan Gohman07591692010-04-11 22:16:48 +00007603 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007604 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007605}
7606
Sanjoy Das5dab2052015-07-27 21:42:49 +00007607bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7608 ICmpInst::Predicate Pred,
7609 bool &Increasing) {
7610 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7611
7612#ifndef NDEBUG
7613 // Verify an invariant: inverting the predicate should turn a monotonically
7614 // increasing change to a monotonically decreasing one, and vice versa.
7615 bool IncreasingSwapped;
7616 bool ResultSwapped = isMonotonicPredicateImpl(
7617 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7618
7619 assert(Result == ResultSwapped && "should be able to analyze both!");
7620 if (ResultSwapped)
7621 assert(Increasing == !IncreasingSwapped &&
7622 "monotonicity should flip as we flip the predicate");
7623#endif
7624
7625 return Result;
7626}
7627
7628bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7629 ICmpInst::Predicate Pred,
7630 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007631
7632 // A zero step value for LHS means the induction variable is essentially a
7633 // loop invariant value. We don't really depend on the predicate actually
7634 // flipping from false to true (for increasing predicates, and the other way
7635 // around for decreasing predicates), all we care about is that *if* the
7636 // predicate changes then it only changes from false to true.
7637 //
7638 // A zero step value in itself is not very useful, but there may be places
7639 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7640 // as general as possible.
7641
Sanjoy Das366acc12015-08-06 20:43:41 +00007642 switch (Pred) {
7643 default:
7644 return false; // Conservative answer
7645
7646 case ICmpInst::ICMP_UGT:
7647 case ICmpInst::ICMP_UGE:
7648 case ICmpInst::ICMP_ULT:
7649 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007650 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007651 return false;
7652
7653 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007654 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007655
7656 case ICmpInst::ICMP_SGT:
7657 case ICmpInst::ICMP_SGE:
7658 case ICmpInst::ICMP_SLT:
7659 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007660 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007661 return false;
7662
7663 const SCEV *Step = LHS->getStepRecurrence(*this);
7664
7665 if (isKnownNonNegative(Step)) {
7666 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7667 return true;
7668 }
7669
7670 if (isKnownNonPositive(Step)) {
7671 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7672 return true;
7673 }
7674
7675 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007676 }
7677
Sanjoy Das5dab2052015-07-27 21:42:49 +00007678 }
7679
Sanjoy Das366acc12015-08-06 20:43:41 +00007680 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007681}
7682
7683bool ScalarEvolution::isLoopInvariantPredicate(
7684 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7685 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7686 const SCEV *&InvariantRHS) {
7687
7688 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7689 if (!isLoopInvariant(RHS, L)) {
7690 if (!isLoopInvariant(LHS, L))
7691 return false;
7692
7693 std::swap(LHS, RHS);
7694 Pred = ICmpInst::getSwappedPredicate(Pred);
7695 }
7696
7697 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7698 if (!ArLHS || ArLHS->getLoop() != L)
7699 return false;
7700
7701 bool Increasing;
7702 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7703 return false;
7704
7705 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7706 // true as the loop iterates, and the backedge is control dependent on
7707 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7708 //
7709 // * if the predicate was false in the first iteration then the predicate
7710 // is never evaluated again, since the loop exits without taking the
7711 // backedge.
7712 // * if the predicate was true in the first iteration then it will
7713 // continue to be true for all future iterations since it is
7714 // monotonically increasing.
7715 //
7716 // For both the above possibilities, we can replace the loop varying
7717 // predicate with its value on the first iteration of the loop (which is
7718 // loop invariant).
7719 //
7720 // A similar reasoning applies for a monotonically decreasing predicate, by
7721 // replacing true with false and false with true in the above two bullets.
7722
7723 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7724
7725 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7726 return false;
7727
7728 InvariantPred = Pred;
7729 InvariantLHS = ArLHS->getStart();
7730 InvariantRHS = RHS;
7731 return true;
7732}
7733
Sanjoy Das401e6312016-02-01 20:48:10 +00007734bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7735 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007736 if (HasSameValue(LHS, RHS))
7737 return ICmpInst::isTrueWhenEqual(Pred);
7738
Dan Gohman07591692010-04-11 22:16:48 +00007739 // This code is split out from isKnownPredicate because it is called from
7740 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007741
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007742 auto CheckRanges =
7743 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7744 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7745 .contains(RangeLHS);
7746 };
7747
7748 // The check at the top of the function catches the case where the values are
7749 // known to be equal.
7750 if (Pred == CmpInst::ICMP_EQ)
7751 return false;
7752
7753 if (Pred == CmpInst::ICMP_NE)
7754 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7755 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7756 isKnownNonZero(getMinusSCEV(LHS, RHS));
7757
7758 if (CmpInst::isSigned(Pred))
7759 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7760
7761 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007762}
7763
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007764bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7765 const SCEV *LHS,
7766 const SCEV *RHS) {
7767
7768 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7769 // Return Y via OutY.
7770 auto MatchBinaryAddToConst =
7771 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7772 SCEV::NoWrapFlags ExpectedFlags) {
7773 const SCEV *NonConstOp, *ConstOp;
7774 SCEV::NoWrapFlags FlagsPresent;
7775
7776 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7777 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7778 return false;
7779
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007780 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007781 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7782 };
7783
7784 APInt C;
7785
7786 switch (Pred) {
7787 default:
7788 break;
7789
7790 case ICmpInst::ICMP_SGE:
7791 std::swap(LHS, RHS);
7792 case ICmpInst::ICMP_SLE:
7793 // X s<= (X + C)<nsw> if C >= 0
7794 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7795 return true;
7796
7797 // (X + C)<nsw> s<= X if C <= 0
7798 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7799 !C.isStrictlyPositive())
7800 return true;
7801 break;
7802
7803 case ICmpInst::ICMP_SGT:
7804 std::swap(LHS, RHS);
7805 case ICmpInst::ICMP_SLT:
7806 // X s< (X + C)<nsw> if C > 0
7807 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7808 C.isStrictlyPositive())
7809 return true;
7810
7811 // (X + C)<nsw> s< X if C < 0
7812 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7813 return true;
7814 break;
7815 }
7816
7817 return false;
7818}
7819
Sanjoy Das7d910f22015-10-02 18:50:30 +00007820bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7821 const SCEV *LHS,
7822 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007823 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007824 return false;
7825
7826 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7827 // the stack can result in exponential time complexity.
7828 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7829
7830 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7831 //
7832 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7833 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7834 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7835 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7836 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007837 return isKnownNonNegative(RHS) &&
7838 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7839 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007840}
7841
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007842bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7843 ICmpInst::Predicate Pred,
7844 const SCEV *LHS, const SCEV *RHS) {
7845 // No need to even try if we know the module has no guards.
7846 if (!HasGuards)
7847 return false;
7848
7849 return any_of(*BB, [&](Instruction &I) {
7850 using namespace llvm::PatternMatch;
7851
7852 Value *Condition;
7853 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7854 m_Value(Condition))) &&
7855 isImpliedCond(Pred, LHS, RHS, Condition, false);
7856 });
7857}
7858
Dan Gohmane65c9172009-07-13 21:35:55 +00007859/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7860/// protected by a conditional between LHS and RHS. This is used to
7861/// to eliminate casts.
7862bool
7863ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7864 ICmpInst::Predicate Pred,
7865 const SCEV *LHS, const SCEV *RHS) {
7866 // Interpret a null as meaning no loop, where there is obviously no guard
7867 // (interprocedural conditions notwithstanding).
7868 if (!L) return true;
7869
Sanjoy Das401e6312016-02-01 20:48:10 +00007870 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7871 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007872
Dan Gohmane65c9172009-07-13 21:35:55 +00007873 BasicBlock *Latch = L->getLoopLatch();
7874 if (!Latch)
7875 return false;
7876
7877 BranchInst *LoopContinuePredicate =
7878 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007879 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7880 isImpliedCond(Pred, LHS, RHS,
7881 LoopContinuePredicate->getCondition(),
7882 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7883 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007884
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007885 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007886 // -- that can lead to O(n!) time complexity.
7887 if (WalkingBEDominatingConds)
7888 return false;
7889
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007890 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007891
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007892 // See if we can exploit a trip count to prove the predicate.
7893 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7894 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7895 if (LatchBECount != getCouldNotCompute()) {
7896 // We know that Latch branches back to the loop header exactly
7897 // LatchBECount times. This means the backdege condition at Latch is
7898 // equivalent to "{0,+,1} u< LatchBECount".
7899 Type *Ty = LatchBECount->getType();
7900 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7901 const SCEV *LoopCounter =
7902 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7903 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7904 LatchBECount))
7905 return true;
7906 }
7907
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007908 // Check conditions due to any @llvm.assume intrinsics.
7909 for (auto &AssumeVH : AC.assumptions()) {
7910 if (!AssumeVH)
7911 continue;
7912 auto *CI = cast<CallInst>(AssumeVH);
7913 if (!DT.dominates(CI, Latch->getTerminator()))
7914 continue;
7915
7916 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7917 return true;
7918 }
7919
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007920 // If the loop is not reachable from the entry block, we risk running into an
7921 // infinite loop as we walk up into the dom tree. These loops do not matter
7922 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007923 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007924 return false;
7925
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007926 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7927 return true;
7928
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007929 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7930 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007931
7932 assert(DTN && "should reach the loop header before reaching the root!");
7933
7934 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007935 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7936 return true;
7937
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007938 BasicBlock *PBB = BB->getSinglePredecessor();
7939 if (!PBB)
7940 continue;
7941
7942 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7943 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7944 continue;
7945
7946 Value *Condition = ContinuePredicate->getCondition();
7947
7948 // If we have an edge `E` within the loop body that dominates the only
7949 // latch, the condition guarding `E` also guards the backedge. This
7950 // reasoning works only for loops with a single latch.
7951
7952 BasicBlockEdge DominatingEdge(PBB, BB);
7953 if (DominatingEdge.isSingleEdge()) {
7954 // We're constructively (and conservatively) enumerating edges within the
7955 // loop body that dominate the latch. The dominator tree better agree
7956 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007957 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007958
7959 if (isImpliedCond(Pred, LHS, RHS, Condition,
7960 BB != ContinuePredicate->getSuccessor(0)))
7961 return true;
7962 }
7963 }
7964
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007965 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007966}
7967
Dan Gohmane65c9172009-07-13 21:35:55 +00007968bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007969ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7970 ICmpInst::Predicate Pred,
7971 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007972 // Interpret a null as meaning no loop, where there is obviously no guard
7973 // (interprocedural conditions notwithstanding).
7974 if (!L) return false;
7975
Sanjoy Das401e6312016-02-01 20:48:10 +00007976 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7977 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007978
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007979 // Starting at the loop predecessor, climb up the predecessor chain, as long
7980 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00007981 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00007982 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00007983 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00007984 Pair.first;
7985 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00007986
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007987 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
7988 return true;
7989
Dan Gohman2a62fd92008-08-12 20:17:31 +00007990 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00007991 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00007992 if (!LoopEntryPredicate ||
7993 LoopEntryPredicate->isUnconditional())
7994 continue;
7995
Dan Gohmane18c2d62010-08-10 23:46:30 +00007996 if (isImpliedCond(Pred, LHS, RHS,
7997 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00007998 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00007999 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008000 }
8001
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008002 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008003 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00008004 if (!AssumeVH)
8005 continue;
8006 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008007 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008008 continue;
8009
8010 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8011 return true;
8012 }
8013
Dan Gohman2a62fd92008-08-12 20:17:31 +00008014 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008015}
8016
Benjamin Kramer039b1042015-10-28 13:54:36 +00008017namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008018/// RAII wrapper to prevent recursive application of isImpliedCond.
8019/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
8020/// currently evaluating isImpliedCond.
8021struct MarkPendingLoopPredicate {
8022 Value *Cond;
8023 DenseSet<Value*> &LoopPreds;
8024 bool Pending;
8025
8026 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
8027 : Cond(C), LoopPreds(LP) {
8028 Pending = !LoopPreds.insert(Cond).second;
8029 }
8030 ~MarkPendingLoopPredicate() {
8031 if (!Pending)
8032 LoopPreds.erase(Cond);
8033 }
8034};
Benjamin Kramer039b1042015-10-28 13:54:36 +00008035} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008036
Dan Gohmane18c2d62010-08-10 23:46:30 +00008037bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008038 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008039 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008040 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008041 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
8042 if (Mark.Pending)
8043 return false;
8044
Dan Gohman8b0a4192010-03-01 17:49:51 +00008045 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008047 if (BO->getOpcode() == Instruction::And) {
8048 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008049 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8050 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008051 } else if (BO->getOpcode() == Instruction::Or) {
8052 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008053 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8054 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008055 }
8056 }
8057
Dan Gohmane18c2d62010-08-10 23:46:30 +00008058 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008059 if (!ICI) return false;
8060
Andrew Trickfa594032012-11-29 18:35:13 +00008061 // Now that we found a conditional branch that dominates the loop or controls
8062 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008063 ICmpInst::Predicate FoundPred;
8064 if (Inverse)
8065 FoundPred = ICI->getInversePredicate();
8066 else
8067 FoundPred = ICI->getPredicate();
8068
8069 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8070 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008071
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008072 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8073}
8074
8075bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8076 const SCEV *RHS,
8077 ICmpInst::Predicate FoundPred,
8078 const SCEV *FoundLHS,
8079 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008080 // Balance the types.
8081 if (getTypeSizeInBits(LHS->getType()) <
8082 getTypeSizeInBits(FoundLHS->getType())) {
8083 if (CmpInst::isSigned(Pred)) {
8084 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8085 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8086 } else {
8087 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8088 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8089 }
8090 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008091 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008092 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008093 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8094 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8095 } else {
8096 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8097 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8098 }
8099 }
8100
Dan Gohman430f0cc2009-07-21 23:03:19 +00008101 // Canonicalize the query to match the way instcombine will have
8102 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008103 if (SimplifyICmpOperands(Pred, LHS, RHS))
8104 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008105 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008106 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8107 if (FoundLHS == FoundRHS)
8108 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008109
8110 // Check to see if we can make the LHS or RHS match.
8111 if (LHS == FoundRHS || RHS == FoundLHS) {
8112 if (isa<SCEVConstant>(RHS)) {
8113 std::swap(FoundLHS, FoundRHS);
8114 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8115 } else {
8116 std::swap(LHS, RHS);
8117 Pred = ICmpInst::getSwappedPredicate(Pred);
8118 }
8119 }
8120
8121 // Check whether the found predicate is the same as the desired predicate.
8122 if (FoundPred == Pred)
8123 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8124
8125 // Check whether swapping the found predicate makes it the same as the
8126 // desired predicate.
8127 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8128 if (isa<SCEVConstant>(RHS))
8129 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8130 else
8131 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8132 RHS, LHS, FoundLHS, FoundRHS);
8133 }
8134
Sanjoy Das6e78b172015-10-22 19:57:34 +00008135 // Unsigned comparison is the same as signed comparison when both the operands
8136 // are non-negative.
8137 if (CmpInst::isUnsigned(FoundPred) &&
8138 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8139 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8140 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8141
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008142 // Check if we can make progress by sharpening ranges.
8143 if (FoundPred == ICmpInst::ICMP_NE &&
8144 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8145
8146 const SCEVConstant *C = nullptr;
8147 const SCEV *V = nullptr;
8148
8149 if (isa<SCEVConstant>(FoundLHS)) {
8150 C = cast<SCEVConstant>(FoundLHS);
8151 V = FoundRHS;
8152 } else {
8153 C = cast<SCEVConstant>(FoundRHS);
8154 V = FoundLHS;
8155 }
8156
8157 // The guarding predicate tells us that C != V. If the known range
8158 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8159 // range we consider has to correspond to same signedness as the
8160 // predicate we're interested in folding.
8161
8162 APInt Min = ICmpInst::isSigned(Pred) ?
8163 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8164
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008165 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008166 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8167 // This is true even if (Min + 1) wraps around -- in case of
8168 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8169
8170 APInt SharperMin = Min + 1;
8171
8172 switch (Pred) {
8173 case ICmpInst::ICMP_SGE:
8174 case ICmpInst::ICMP_UGE:
8175 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8176 // RHS, we're done.
8177 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8178 getConstant(SharperMin)))
8179 return true;
8180
8181 case ICmpInst::ICMP_SGT:
8182 case ICmpInst::ICMP_UGT:
8183 // We know from the range information that (V `Pred` Min ||
8184 // V == Min). We know from the guarding condition that !(V
8185 // == Min). This gives us
8186 //
8187 // V `Pred` Min || V == Min && !(V == Min)
8188 // => V `Pred` Min
8189 //
8190 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8191
8192 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8193 return true;
8194
8195 default:
8196 // No change
8197 break;
8198 }
8199 }
8200 }
8201
Dan Gohman430f0cc2009-07-21 23:03:19 +00008202 // Check whether the actual condition is beyond sufficient.
8203 if (FoundPred == ICmpInst::ICMP_EQ)
8204 if (ICmpInst::isTrueWhenEqual(Pred))
8205 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8206 return true;
8207 if (Pred == ICmpInst::ICMP_NE)
8208 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8209 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8210 return true;
8211
8212 // Otherwise assume the worst.
8213 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008214}
8215
Sanjoy Das1ed69102015-10-13 02:53:27 +00008216bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8217 const SCEV *&L, const SCEV *&R,
8218 SCEV::NoWrapFlags &Flags) {
8219 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8220 if (!AE || AE->getNumOperands() != 2)
8221 return false;
8222
8223 L = AE->getOperand(0);
8224 R = AE->getOperand(1);
8225 Flags = AE->getNoWrapFlags();
8226 return true;
8227}
8228
8229bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
8230 const SCEV *More,
8231 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008232 // We avoid subtracting expressions here because this function is usually
8233 // fairly deep in the call stack (i.e. is called many times).
8234
Sanjoy Das96709c42015-09-25 23:53:45 +00008235 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8236 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8237 const auto *MAR = cast<SCEVAddRecExpr>(More);
8238
8239 if (LAR->getLoop() != MAR->getLoop())
8240 return false;
8241
8242 // We look at affine expressions only; not for correctness but to keep
8243 // getStepRecurrence cheap.
8244 if (!LAR->isAffine() || !MAR->isAffine())
8245 return false;
8246
Sanjoy Das1ed69102015-10-13 02:53:27 +00008247 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00008248 return false;
8249
8250 Less = LAR->getStart();
8251 More = MAR->getStart();
8252
8253 // fall through
8254 }
8255
8256 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008257 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8258 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008259 C = M - L;
8260 return true;
8261 }
8262
8263 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008264 SCEV::NoWrapFlags Flags;
8265 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008266 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8267 if (R == More) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008268 C = -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008269 return true;
8270 }
8271
Sanjoy Das1ed69102015-10-13 02:53:27 +00008272 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008273 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8274 if (R == Less) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008275 C = LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008276 return true;
8277 }
8278
8279 return false;
8280}
8281
8282bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8283 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8284 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8285 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8286 return false;
8287
8288 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8289 if (!AddRecLHS)
8290 return false;
8291
8292 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8293 if (!AddRecFoundLHS)
8294 return false;
8295
8296 // We'd like to let SCEV reason about control dependencies, so we constrain
8297 // both the inequalities to be about add recurrences on the same loop. This
8298 // way we can use isLoopEntryGuardedByCond later.
8299
8300 const Loop *L = AddRecFoundLHS->getLoop();
8301 if (L != AddRecLHS->getLoop())
8302 return false;
8303
8304 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8305 //
8306 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8307 // ... (2)
8308 //
8309 // Informal proof for (2), assuming (1) [*]:
8310 //
8311 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8312 //
8313 // Then
8314 //
8315 // FoundLHS s< FoundRHS s< INT_MIN - C
8316 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8317 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8318 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8319 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8320 // <=> FoundLHS + C s< FoundRHS + C
8321 //
8322 // [*]: (1) can be proved by ruling out overflow.
8323 //
8324 // [**]: This can be proved by analyzing all the four possibilities:
8325 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8326 // (A s>= 0, B s>= 0).
8327 //
8328 // Note:
8329 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8330 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8331 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8332 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8333 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8334 // C)".
8335
8336 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008337 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
8338 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00008339 LDiff != RDiff)
8340 return false;
8341
8342 if (LDiff == 0)
8343 return true;
8344
Sanjoy Das96709c42015-09-25 23:53:45 +00008345 APInt FoundRHSLimit;
8346
8347 if (Pred == CmpInst::ICMP_ULT) {
8348 FoundRHSLimit = -RDiff;
8349 } else {
8350 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00008351 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008352 }
8353
8354 // Try to prove (1) or (2), as needed.
8355 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8356 getConstant(FoundRHSLimit));
8357}
8358
Dan Gohman430f0cc2009-07-21 23:03:19 +00008359bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8360 const SCEV *LHS, const SCEV *RHS,
8361 const SCEV *FoundLHS,
8362 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008363 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8364 return true;
8365
Sanjoy Das96709c42015-09-25 23:53:45 +00008366 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8367 return true;
8368
Dan Gohman430f0cc2009-07-21 23:03:19 +00008369 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8370 FoundLHS, FoundRHS) ||
8371 // ~x < ~y --> x > y
8372 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8373 getNotSCEV(FoundRHS),
8374 getNotSCEV(FoundLHS));
8375}
8376
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008377
8378/// If Expr computes ~A, return A else return nullptr
8379static const SCEV *MatchNotExpr(const SCEV *Expr) {
8380 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008381 if (!Add || Add->getNumOperands() != 2 ||
8382 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008383 return nullptr;
8384
8385 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008386 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8387 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008388 return nullptr;
8389
8390 return AddRHS->getOperand(1);
8391}
8392
8393
8394/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8395template<typename MaxExprType>
8396static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8397 const SCEV *Candidate) {
8398 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8399 if (!MaxExpr) return false;
8400
Sanjoy Das347d2722015-12-01 07:49:27 +00008401 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008402}
8403
8404
8405/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8406template<typename MaxExprType>
8407static bool IsMinConsistingOf(ScalarEvolution &SE,
8408 const SCEV *MaybeMinExpr,
8409 const SCEV *Candidate) {
8410 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8411 if (!MaybeMaxExpr)
8412 return false;
8413
8414 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8415}
8416
Hal Finkela8d205f2015-08-19 01:51:51 +00008417static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8418 ICmpInst::Predicate Pred,
8419 const SCEV *LHS, const SCEV *RHS) {
8420
8421 // If both sides are affine addrecs for the same loop, with equal
8422 // steps, and we know the recurrences don't wrap, then we only
8423 // need to check the predicate on the starting values.
8424
8425 if (!ICmpInst::isRelational(Pred))
8426 return false;
8427
8428 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8429 if (!LAR)
8430 return false;
8431 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8432 if (!RAR)
8433 return false;
8434 if (LAR->getLoop() != RAR->getLoop())
8435 return false;
8436 if (!LAR->isAffine() || !RAR->isAffine())
8437 return false;
8438
8439 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8440 return false;
8441
Hal Finkelff08a2e2015-08-19 17:26:07 +00008442 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8443 SCEV::FlagNSW : SCEV::FlagNUW;
8444 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008445 return false;
8446
8447 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8448}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008449
8450/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8451/// expression?
8452static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8453 ICmpInst::Predicate Pred,
8454 const SCEV *LHS, const SCEV *RHS) {
8455 switch (Pred) {
8456 default:
8457 return false;
8458
8459 case ICmpInst::ICMP_SGE:
8460 std::swap(LHS, RHS);
8461 // fall through
8462 case ICmpInst::ICMP_SLE:
8463 return
8464 // min(A, ...) <= A
8465 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8466 // A <= max(A, ...)
8467 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8468
8469 case ICmpInst::ICMP_UGE:
8470 std::swap(LHS, RHS);
8471 // fall through
8472 case ICmpInst::ICMP_ULE:
8473 return
8474 // min(A, ...) <= A
8475 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8476 // A <= max(A, ...)
8477 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8478 }
8479
8480 llvm_unreachable("covered switch fell through?!");
8481}
8482
Dan Gohmane65c9172009-07-13 21:35:55 +00008483bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008484ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8485 const SCEV *LHS, const SCEV *RHS,
8486 const SCEV *FoundLHS,
8487 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008488 auto IsKnownPredicateFull =
8489 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008490 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008491 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008492 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8493 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008494 };
8495
Dan Gohmane65c9172009-07-13 21:35:55 +00008496 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008497 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8498 case ICmpInst::ICMP_EQ:
8499 case ICmpInst::ICMP_NE:
8500 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8501 return true;
8502 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008503 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008504 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008505 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8506 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008507 return true;
8508 break;
8509 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008510 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008511 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8512 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008513 return true;
8514 break;
8515 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008516 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008517 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8518 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008519 return true;
8520 break;
8521 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008522 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008523 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8524 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008525 return true;
8526 break;
8527 }
8528
8529 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008530}
8531
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008532bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8533 const SCEV *LHS,
8534 const SCEV *RHS,
8535 const SCEV *FoundLHS,
8536 const SCEV *FoundRHS) {
8537 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8538 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8539 // reduce the compile time impact of this optimization.
8540 return false;
8541
8542 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8543 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8544 !isa<SCEVConstant>(AddLHS->getOperand(0)))
8545 return false;
8546
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008547 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008548
8549 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8550 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8551 ConstantRange FoundLHSRange =
8552 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8553
8554 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8555 // for `LHS`:
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008556 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008557 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8558
8559 // We can also compute the range of values for `LHS` that satisfy the
8560 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008561 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008562 ConstantRange SatisfyingLHSRange =
8563 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8564
8565 // The antecedent implies the consequent if every value of `LHS` that
8566 // satisfies the antecedent also satisfies the consequent.
8567 return SatisfyingLHSRange.contains(LHSRange);
8568}
8569
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008570bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8571 bool IsSigned, bool NoWrap) {
8572 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008573
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008574 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008575 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008576
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008577 if (IsSigned) {
8578 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8579 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8580 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8581 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008582
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008583 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8584 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008585 }
Dan Gohman01048422009-06-21 23:46:38 +00008586
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008587 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8588 APInt MaxValue = APInt::getMaxValue(BitWidth);
8589 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8590 .getUnsignedMax();
8591
8592 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8593 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8594}
8595
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008596bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8597 bool IsSigned, bool NoWrap) {
8598 if (NoWrap) return false;
8599
8600 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008601 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008602
8603 if (IsSigned) {
8604 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8605 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8606 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8607 .getSignedMax();
8608
8609 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8610 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8611 }
8612
8613 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8614 APInt MinValue = APInt::getMinValue(BitWidth);
8615 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8616 .getUnsignedMax();
8617
8618 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8619 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8620}
8621
Johannes Doerfert2683e562015-02-09 12:34:23 +00008622const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008623 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008624 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008625 Delta = Equality ? getAddExpr(Delta, Step)
8626 : getAddExpr(Delta, getMinusSCEV(Step, One));
8627 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008628}
8629
Andrew Trick3ca3f982011-07-26 17:19:55 +00008630ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008631ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008632 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008633 bool ControlsExit, bool AllowPredicates) {
8634 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008635 // We handle only IV < Invariant
8636 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008637 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008638
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008639 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008640 if (!IV && AllowPredicates)
8641 // Try to make this an AddRec using runtime tests, in the first X
8642 // iterations of this loop, where X is the SCEV expression found by the
8643 // algorithm below.
8644 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Dan Gohman2b8da352009-04-30 20:47:05 +00008645
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008646 // Avoid weird loops
8647 if (!IV || IV->getLoop() != L || !IV->isAffine())
8648 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008649
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008650 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008651 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008652
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008653 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008654
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008655 // Avoid negative or zero stride values
8656 if (!isKnownPositive(Stride))
8657 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008658
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008659 // Avoid proven overflow cases: this will ensure that the backedge taken count
8660 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008661 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008662 // behaviors like the case of C language.
8663 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8664 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008665
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008666 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8667 : ICmpInst::ICMP_ULT;
8668 const SCEV *Start = IV->getStart();
8669 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008670 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8671 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
Dan Gohman51aaf022010-01-26 04:40:18 +00008672
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008673 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008674
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008675 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8676 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008677
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008678 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8679 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008680
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008681 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8682 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8683 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008684
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008685 // Although End can be a MAX expression we estimate MaxEnd considering only
8686 // the case End = RHS. This is safe because in the other case (End - Start)
8687 // is zero, leading to a zero maximum backedge taken count.
8688 APInt MaxEnd =
8689 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8690 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8691
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008692 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008693 if (isa<SCEVConstant>(BECount))
8694 MaxBECount = BECount;
8695 else
8696 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8697 getConstant(MinStride), false);
8698
8699 if (isa<SCEVCouldNotCompute>(MaxBECount))
8700 MaxBECount = BECount;
8701
Silviu Baranga6f444df2016-04-08 14:29:09 +00008702 return ExitLimit(BECount, MaxBECount, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008703}
8704
8705ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008706ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008707 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008708 bool ControlsExit, bool AllowPredicates) {
8709 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008710 // We handle only IV > Invariant
8711 if (!isLoopInvariant(RHS, L))
8712 return getCouldNotCompute();
8713
8714 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008715 if (!IV && AllowPredicates)
8716 // Try to make this an AddRec using runtime tests, in the first X
8717 // iterations of this loop, where X is the SCEV expression found by the
8718 // algorithm below.
8719 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008720
8721 // Avoid weird loops
8722 if (!IV || IV->getLoop() != L || !IV->isAffine())
8723 return getCouldNotCompute();
8724
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008725 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008726 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8727
8728 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8729
8730 // Avoid negative or zero stride values
8731 if (!isKnownPositive(Stride))
8732 return getCouldNotCompute();
8733
8734 // Avoid proven overflow cases: this will ensure that the backedge taken count
8735 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008736 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008737 // behaviors like the case of C language.
8738 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8739 return getCouldNotCompute();
8740
8741 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8742 : ICmpInst::ICMP_UGT;
8743
8744 const SCEV *Start = IV->getStart();
8745 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008746 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8747 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008748
8749 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8750
8751 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8752 : getUnsignedRange(Start).getUnsignedMax();
8753
8754 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8755 : getUnsignedRange(Stride).getUnsignedMin();
8756
8757 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8758 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8759 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8760
8761 // Although End can be a MIN expression we estimate MinEnd considering only
8762 // the case End = RHS. This is safe because in the other case (Start - End)
8763 // is zero, leading to a zero maximum backedge taken count.
8764 APInt MinEnd =
8765 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8766 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8767
8768
8769 const SCEV *MaxBECount = getCouldNotCompute();
8770 if (isa<SCEVConstant>(BECount))
8771 MaxBECount = BECount;
8772 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008773 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008774 getConstant(MinStride), false);
8775
8776 if (isa<SCEVCouldNotCompute>(MaxBECount))
8777 MaxBECount = BECount;
8778
Silviu Baranga6f444df2016-04-08 14:29:09 +00008779 return ExitLimit(BECount, MaxBECount, P);
Chris Lattner587a75b2005-08-15 23:33:51 +00008780}
8781
Benjamin Kramerc321e532016-06-08 19:09:22 +00008782const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008783 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008784 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008785 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008786
8787 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008788 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008789 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008790 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008791 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008792 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008793 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008794 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008795 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008796 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008797 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008798 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008799 }
8800
8801 // The only time we can solve this is when we have all constant indices.
8802 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008803 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008804 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008805
8806 // Okay at this point we know that all elements of the chrec are constants and
8807 // that the start element is zero.
8808
8809 // First check to see if the range contains zero. If not, the first
8810 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008811 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008812 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008813 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008814
Chris Lattnerd934c702004-04-02 20:23:17 +00008815 if (isAffine()) {
8816 // If this is an affine expression then we have this situation:
8817 // Solve {0,+,A} in Range === Ax in Range
8818
Nick Lewycky52460262007-07-16 02:08:00 +00008819 // We know that zero is in the range. If A is positive then we know that
8820 // the upper value of the range must be the first possible exit value.
8821 // If A is negative then the lower of the range is the last possible loop
8822 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008823 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008824 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008825 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008826
Nick Lewycky52460262007-07-16 02:08:00 +00008827 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008828 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008829 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008830
8831 // Evaluate at the exit value. If we really did fall out of the valid
8832 // range, then we computed our trip count, otherwise wrap around or other
8833 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008834 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008835 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008836 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008837
8838 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008839 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008840 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008841 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008842 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008843 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008844 } else if (isQuadratic()) {
8845 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8846 // quadratic equation to solve it. To do this, we must frame our problem in
8847 // terms of figuring out when zero is crossed, instead of when
8848 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008849 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008850 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008851 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8852 // getNoWrapFlags(FlagNW)
8853 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008854
8855 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008856 if (auto Roots =
8857 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008858 const SCEVConstant *R1 = Roots->first;
8859 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008860 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008861 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8862 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008863 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008864 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008865
Chris Lattnerd934c702004-04-02 20:23:17 +00008866 // Make sure the root is not off by one. The returned iteration should
8867 // not be in the range, but the previous one should be. When solving
8868 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00008869 ConstantInt *R1Val =
8870 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008871 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008872 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008873 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008874 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008875
Dan Gohmana37eaf22007-10-22 18:31:58 +00008876 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008877 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008878 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00008879 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008880 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008881
Chris Lattnerd934c702004-04-02 20:23:17 +00008882 // If R1 was not in the range, then it is a good return value. Make
8883 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008884 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008885 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008886 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008887 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008888 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00008889 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008890 }
8891 }
8892 }
8893
Dan Gohman31efa302009-04-18 17:58:19 +00008894 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008895}
8896
Sebastian Pop448712b2014-05-07 18:01:20 +00008897namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008898struct FindUndefs {
8899 bool Found;
8900 FindUndefs() : Found(false) {}
8901
8902 bool follow(const SCEV *S) {
8903 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8904 if (isa<UndefValue>(C->getValue()))
8905 Found = true;
8906 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8907 if (isa<UndefValue>(C->getValue()))
8908 Found = true;
8909 }
8910
8911 // Keep looking if we haven't found it yet.
8912 return !Found;
8913 }
8914 bool isDone() const {
8915 // Stop recursion if we have found an undef.
8916 return Found;
8917 }
8918};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008919}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008920
8921// Return true when S contains at least an undef value.
8922static inline bool
8923containsUndefs(const SCEV *S) {
8924 FindUndefs F;
8925 SCEVTraversal<FindUndefs> ST(F);
8926 ST.visitAll(S);
8927
8928 return F.Found;
8929}
8930
8931namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008932// Collect all steps of SCEV expressions.
8933struct SCEVCollectStrides {
8934 ScalarEvolution &SE;
8935 SmallVectorImpl<const SCEV *> &Strides;
8936
8937 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8938 : SE(SE), Strides(S) {}
8939
8940 bool follow(const SCEV *S) {
8941 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8942 Strides.push_back(AR->getStepRecurrence(SE));
8943 return true;
8944 }
8945 bool isDone() const { return false; }
8946};
8947
8948// Collect all SCEVUnknown and SCEVMulExpr expressions.
8949struct SCEVCollectTerms {
8950 SmallVectorImpl<const SCEV *> &Terms;
8951
8952 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8953 : Terms(T) {}
8954
8955 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008956 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008957 if (!containsUndefs(S))
8958 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00008959
8960 // Stop recursion: once we collected a term, do not walk its operands.
8961 return false;
8962 }
8963
8964 // Keep looking.
8965 return true;
8966 }
8967 bool isDone() const { return false; }
8968};
Tobias Grosser374bce02015-10-12 08:02:00 +00008969
8970// Check if a SCEV contains an AddRecExpr.
8971struct SCEVHasAddRec {
8972 bool &ContainsAddRec;
8973
8974 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8975 ContainsAddRec = false;
8976 }
8977
8978 bool follow(const SCEV *S) {
8979 if (isa<SCEVAddRecExpr>(S)) {
8980 ContainsAddRec = true;
8981
8982 // Stop recursion: once we collected a term, do not walk its operands.
8983 return false;
8984 }
8985
8986 // Keep looking.
8987 return true;
8988 }
8989 bool isDone() const { return false; }
8990};
8991
8992// Find factors that are multiplied with an expression that (possibly as a
8993// subexpression) contains an AddRecExpr. In the expression:
8994//
8995// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
8996//
8997// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8998// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8999// parameters as they form a product with an induction variable.
9000//
9001// This collector expects all array size parameters to be in the same MulExpr.
9002// It might be necessary to later add support for collecting parameters that are
9003// spread over different nested MulExpr.
9004struct SCEVCollectAddRecMultiplies {
9005 SmallVectorImpl<const SCEV *> &Terms;
9006 ScalarEvolution &SE;
9007
9008 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9009 : Terms(T), SE(SE) {}
9010
9011 bool follow(const SCEV *S) {
9012 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9013 bool HasAddRec = false;
9014 SmallVector<const SCEV *, 0> Operands;
9015 for (auto Op : Mul->operands()) {
9016 if (isa<SCEVUnknown>(Op)) {
9017 Operands.push_back(Op);
9018 } else {
9019 bool ContainsAddRec;
9020 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9021 visitAll(Op, ContiansAddRec);
9022 HasAddRec |= ContainsAddRec;
9023 }
9024 }
9025 if (Operands.size() == 0)
9026 return true;
9027
9028 if (!HasAddRec)
9029 return false;
9030
9031 Terms.push_back(SE.getMulExpr(Operands));
9032 // Stop recursion: once we collected a term, do not walk its operands.
9033 return false;
9034 }
9035
9036 // Keep looking.
9037 return true;
9038 }
9039 bool isDone() const { return false; }
9040};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009041}
Sebastian Pop448712b2014-05-07 18:01:20 +00009042
Tobias Grosser374bce02015-10-12 08:02:00 +00009043/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9044/// two places:
9045/// 1) The strides of AddRec expressions.
9046/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009047void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9048 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009049 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009050 SCEVCollectStrides StrideCollector(*this, Strides);
9051 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009052
9053 DEBUG({
9054 dbgs() << "Strides:\n";
9055 for (const SCEV *S : Strides)
9056 dbgs() << *S << "\n";
9057 });
9058
9059 for (const SCEV *S : Strides) {
9060 SCEVCollectTerms TermCollector(Terms);
9061 visitAll(S, TermCollector);
9062 }
9063
9064 DEBUG({
9065 dbgs() << "Terms:\n";
9066 for (const SCEV *T : Terms)
9067 dbgs() << *T << "\n";
9068 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009069
9070 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9071 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009072}
9073
Sebastian Popb1a548f2014-05-12 19:01:53 +00009074static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009075 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009076 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009077 int Last = Terms.size() - 1;
9078 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009079
Sebastian Pop448712b2014-05-07 18:01:20 +00009080 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009081 if (Last == 0) {
9082 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009083 SmallVector<const SCEV *, 2> Qs;
9084 for (const SCEV *Op : M->operands())
9085 if (!isa<SCEVConstant>(Op))
9086 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009087
Sebastian Pope30bd352014-05-27 22:41:56 +00009088 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009089 }
9090
Sebastian Pope30bd352014-05-27 22:41:56 +00009091 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009092 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009093 }
9094
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009095 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009096 // Normalize the terms before the next call to findArrayDimensionsRec.
9097 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009098 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009099
9100 // Bail out when GCD does not evenly divide one of the terms.
9101 if (!R->isZero())
9102 return false;
9103
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009104 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009105 }
9106
Tobias Grosser3080cf12014-05-08 07:55:34 +00009107 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00009108 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
9109 return isa<SCEVConstant>(E);
9110 }),
9111 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009112
Sebastian Pop448712b2014-05-07 18:01:20 +00009113 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009114 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9115 return false;
9116
Sebastian Pope30bd352014-05-27 22:41:56 +00009117 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009118 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009119}
Sebastian Popc62c6792013-11-12 22:47:20 +00009120
Sebastian Pop448712b2014-05-07 18:01:20 +00009121// Returns true when S contains at least a SCEVUnknown parameter.
9122static inline bool
9123containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00009124 struct FindParameter {
9125 bool FoundParameter;
9126 FindParameter() : FoundParameter(false) {}
9127
9128 bool follow(const SCEV *S) {
9129 if (isa<SCEVUnknown>(S)) {
9130 FoundParameter = true;
9131 // Stop recursion: we found a parameter.
9132 return false;
9133 }
9134 // Keep looking.
9135 return true;
9136 }
9137 bool isDone() const {
9138 // Stop recursion if we have found a parameter.
9139 return FoundParameter;
9140 }
9141 };
9142
Sebastian Pop448712b2014-05-07 18:01:20 +00009143 FindParameter F;
9144 SCEVTraversal<FindParameter> ST(F);
9145 ST.visitAll(S);
9146
9147 return F.FoundParameter;
9148}
9149
9150// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9151static inline bool
9152containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9153 for (const SCEV *T : Terms)
9154 if (containsParameters(T))
9155 return true;
9156 return false;
9157}
9158
9159// Return the number of product terms in S.
9160static inline int numberOfTerms(const SCEV *S) {
9161 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9162 return Expr->getNumOperands();
9163 return 1;
9164}
9165
Sebastian Popa6e58602014-05-27 22:41:45 +00009166static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9167 if (isa<SCEVConstant>(T))
9168 return nullptr;
9169
9170 if (isa<SCEVUnknown>(T))
9171 return T;
9172
9173 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9174 SmallVector<const SCEV *, 2> Factors;
9175 for (const SCEV *Op : M->operands())
9176 if (!isa<SCEVConstant>(Op))
9177 Factors.push_back(Op);
9178
9179 return SE.getMulExpr(Factors);
9180 }
9181
9182 return T;
9183}
9184
9185/// Return the size of an element read or written by Inst.
9186const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9187 Type *Ty;
9188 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9189 Ty = Store->getValueOperand()->getType();
9190 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009191 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009192 else
9193 return nullptr;
9194
9195 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9196 return getSizeOfExpr(ETy, Ty);
9197}
9198
Sebastian Popa6e58602014-05-27 22:41:45 +00009199void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9200 SmallVectorImpl<const SCEV *> &Sizes,
9201 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009202 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009203 return;
9204
9205 // Early return when Terms do not contain parameters: we do not delinearize
9206 // non parametric SCEVs.
9207 if (!containsParameters(Terms))
9208 return;
9209
9210 DEBUG({
9211 dbgs() << "Terms:\n";
9212 for (const SCEV *T : Terms)
9213 dbgs() << *T << "\n";
9214 });
9215
9216 // Remove duplicates.
9217 std::sort(Terms.begin(), Terms.end());
9218 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9219
9220 // Put larger terms first.
9221 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9222 return numberOfTerms(LHS) > numberOfTerms(RHS);
9223 });
9224
Sebastian Popa6e58602014-05-27 22:41:45 +00009225 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9226
Tobias Grosser374bce02015-10-12 08:02:00 +00009227 // Try to divide all terms by the element size. If term is not divisible by
9228 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009229 for (const SCEV *&Term : Terms) {
9230 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009231 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009232 if (!Q->isZero())
9233 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009234 }
9235
9236 SmallVector<const SCEV *, 4> NewTerms;
9237
9238 // Remove constant factors.
9239 for (const SCEV *T : Terms)
9240 if (const SCEV *NewT = removeConstantFactors(SE, T))
9241 NewTerms.push_back(NewT);
9242
Sebastian Pop448712b2014-05-07 18:01:20 +00009243 DEBUG({
9244 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009245 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009246 dbgs() << *T << "\n";
9247 });
9248
Sebastian Popa6e58602014-05-27 22:41:45 +00009249 if (NewTerms.empty() ||
9250 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009251 Sizes.clear();
9252 return;
9253 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009254
Sebastian Popa6e58602014-05-27 22:41:45 +00009255 // The last element to be pushed into Sizes is the size of an element.
9256 Sizes.push_back(ElementSize);
9257
Sebastian Pop448712b2014-05-07 18:01:20 +00009258 DEBUG({
9259 dbgs() << "Sizes:\n";
9260 for (const SCEV *S : Sizes)
9261 dbgs() << *S << "\n";
9262 });
9263}
9264
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009265void ScalarEvolution::computeAccessFunctions(
9266 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9267 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009268
Sebastian Popb1a548f2014-05-12 19:01:53 +00009269 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009270 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009271 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009272
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009273 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009274 if (!AR->isAffine())
9275 return;
9276
9277 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009278 int Last = Sizes.size() - 1;
9279 for (int i = Last; i >= 0; i--) {
9280 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009281 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009282
9283 DEBUG({
9284 dbgs() << "Res: " << *Res << "\n";
9285 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9286 dbgs() << "Res divided by Sizes[i]:\n";
9287 dbgs() << "Quotient: " << *Q << "\n";
9288 dbgs() << "Remainder: " << *R << "\n";
9289 });
9290
9291 Res = Q;
9292
Sebastian Popa6e58602014-05-27 22:41:45 +00009293 // Do not record the last subscript corresponding to the size of elements in
9294 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009295 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009296
9297 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009298 if (isa<SCEVAddRecExpr>(R)) {
9299 Subscripts.clear();
9300 Sizes.clear();
9301 return;
9302 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009303
Sebastian Pop448712b2014-05-07 18:01:20 +00009304 continue;
9305 }
9306
9307 // Record the access function for the current subscript.
9308 Subscripts.push_back(R);
9309 }
9310
9311 // Also push in last position the remainder of the last division: it will be
9312 // the access function of the innermost dimension.
9313 Subscripts.push_back(Res);
9314
9315 std::reverse(Subscripts.begin(), Subscripts.end());
9316
9317 DEBUG({
9318 dbgs() << "Subscripts:\n";
9319 for (const SCEV *S : Subscripts)
9320 dbgs() << *S << "\n";
9321 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009322}
9323
Sebastian Popc62c6792013-11-12 22:47:20 +00009324/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9325/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009326/// is the offset start of the array. The SCEV->delinearize algorithm computes
9327/// the multiples of SCEV coefficients: that is a pattern matching of sub
9328/// expressions in the stride and base of a SCEV corresponding to the
9329/// computation of a GCD (greatest common divisor) of base and stride. When
9330/// SCEV->delinearize fails, it returns the SCEV unchanged.
9331///
9332/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9333///
9334/// void foo(long n, long m, long o, double A[n][m][o]) {
9335///
9336/// for (long i = 0; i < n; i++)
9337/// for (long j = 0; j < m; j++)
9338/// for (long k = 0; k < o; k++)
9339/// A[i][j][k] = 1.0;
9340/// }
9341///
9342/// the delinearization input is the following AddRec SCEV:
9343///
9344/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9345///
9346/// From this SCEV, we are able to say that the base offset of the access is %A
9347/// because it appears as an offset that does not divide any of the strides in
9348/// the loops:
9349///
9350/// CHECK: Base offset: %A
9351///
9352/// and then SCEV->delinearize determines the size of some of the dimensions of
9353/// the array as these are the multiples by which the strides are happening:
9354///
9355/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9356///
9357/// Note that the outermost dimension remains of UnknownSize because there are
9358/// no strides that would help identifying the size of the last dimension: when
9359/// the array has been statically allocated, one could compute the size of that
9360/// dimension by dividing the overall size of the array by the size of the known
9361/// dimensions: %m * %o * 8.
9362///
9363/// Finally delinearize provides the access functions for the array reference
9364/// that does correspond to A[i][j][k] of the above C testcase:
9365///
9366/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9367///
9368/// The testcases are checking the output of a function pass:
9369/// DelinearizationPass that walks through all loads and stores of a function
9370/// asking for the SCEV of the memory access with respect to all enclosing
9371/// loops, calling SCEV->delinearize on that and printing the results.
9372
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009373void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009374 SmallVectorImpl<const SCEV *> &Subscripts,
9375 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009376 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009377 // First step: collect parametric terms.
9378 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009379 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009380
Sebastian Popb1a548f2014-05-12 19:01:53 +00009381 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009382 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009383
Sebastian Pop448712b2014-05-07 18:01:20 +00009384 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009385 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009386
Sebastian Popb1a548f2014-05-12 19:01:53 +00009387 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009388 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009389
Sebastian Pop448712b2014-05-07 18:01:20 +00009390 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009391 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009392
Sebastian Pop28e6b972014-05-27 22:41:51 +00009393 if (Subscripts.empty())
9394 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009395
Sebastian Pop448712b2014-05-07 18:01:20 +00009396 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009397 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009398 dbgs() << "ArrayDecl[UnknownSize]";
9399 for (const SCEV *S : Sizes)
9400 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009401
Sebastian Pop444621a2014-05-09 22:45:02 +00009402 dbgs() << "\nArrayRef";
9403 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009404 dbgs() << "[" << *S << "]";
9405 dbgs() << "\n";
9406 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009407}
Chris Lattnerd934c702004-04-02 20:23:17 +00009408
9409//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009410// SCEVCallbackVH Class Implementation
9411//===----------------------------------------------------------------------===//
9412
Dan Gohmand33a0902009-05-19 19:22:47 +00009413void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009414 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009415 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9416 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009417 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009418 // this now dangles!
9419}
9420
Dan Gohman7a066722010-07-28 01:09:07 +00009421void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009422 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009423
Dan Gohman48f82222009-05-04 22:30:44 +00009424 // Forget all the expressions associated with users of the old value,
9425 // so that future queries will recompute the expressions using the new
9426 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009427 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009428 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009429 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009430 while (!Worklist.empty()) {
9431 User *U = Worklist.pop_back_val();
9432 // Deleting the Old value will cause this to dangle. Postpone
9433 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009434 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009435 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009436 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009437 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009438 if (PHINode *PN = dyn_cast<PHINode>(U))
9439 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009440 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009441 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009442 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009443 // Delete the Old value.
9444 if (PHINode *PN = dyn_cast<PHINode>(Old))
9445 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009446 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009447 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009448}
9449
Dan Gohmand33a0902009-05-19 19:22:47 +00009450ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009451 : CallbackVH(V), SE(se) {}
9452
9453//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009454// ScalarEvolution Class Implementation
9455//===----------------------------------------------------------------------===//
9456
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009457ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9458 AssumptionCache &AC, DominatorTree &DT,
9459 LoopInfo &LI)
9460 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9461 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009462 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9463 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009464 FirstUnknown(nullptr) {
9465
9466 // To use guards for proving predicates, we need to scan every instruction in
9467 // relevant basic blocks, and not just terminators. Doing this is a waste of
9468 // time if the IR does not actually contain any calls to
9469 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9470 //
9471 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9472 // to _add_ guards to the module when there weren't any before, and wants
9473 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9474 // efficient in lieu of being smart in that rather obscure case.
9475
9476 auto *GuardDecl = F.getParent()->getFunction(
9477 Intrinsic::getName(Intrinsic::experimental_guard));
9478 HasGuards = GuardDecl && !GuardDecl->use_empty();
9479}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009480
9481ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009482 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9483 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009484 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009485 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009486 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009487 PredicatedBackedgeTakenCounts(
9488 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009489 ConstantEvolutionLoopExitValue(
9490 std::move(Arg.ConstantEvolutionLoopExitValue)),
9491 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9492 LoopDispositions(std::move(Arg.LoopDispositions)),
9493 BlockDispositions(std::move(Arg.BlockDispositions)),
9494 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9495 SignedRanges(std::move(Arg.SignedRanges)),
9496 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009497 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009498 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9499 FirstUnknown(Arg.FirstUnknown) {
9500 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009501}
9502
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009503ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009504 // Iterate through all the SCEVUnknown instances and call their
9505 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009506 for (SCEVUnknown *U = FirstUnknown; U;) {
9507 SCEVUnknown *Tmp = U;
9508 U = U->Next;
9509 Tmp->~SCEVUnknown();
9510 }
Craig Topper9f008862014-04-15 04:59:12 +00009511 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009512
Wei Mia49559b2016-02-04 01:27:38 +00009513 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009514 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009515 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009516
9517 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9518 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009519 for (auto &BTCI : BackedgeTakenCounts)
9520 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009521 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9522 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009523
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009524 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009525 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009526 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009527}
9528
Dan Gohmanc8e23622009-04-21 23:15:49 +00009529bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009530 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009531}
9532
Dan Gohmanc8e23622009-04-21 23:15:49 +00009533static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009534 const Loop *L) {
9535 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009536 for (Loop *I : *L)
9537 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009538
Dan Gohmanbc694912010-01-09 18:17:45 +00009539 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009540 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009541 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009542
Dan Gohmancb0efec2009-12-18 01:14:11 +00009543 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009544 L->getExitBlocks(ExitBlocks);
9545 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009546 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009547
Dan Gohman0bddac12009-02-24 18:55:53 +00009548 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9549 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009550 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009551 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009552 }
9553
Dan Gohmanbc694912010-01-09 18:17:45 +00009554 OS << "\n"
9555 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009556 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009557 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009558
9559 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9560 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9561 } else {
9562 OS << "Unpredictable max backedge-taken count. ";
9563 }
9564
Silviu Baranga6f444df2016-04-08 14:29:09 +00009565 OS << "\n"
9566 "Loop ";
9567 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9568 OS << ": ";
9569
9570 SCEVUnionPredicate Pred;
9571 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9572 if (!isa<SCEVCouldNotCompute>(PBT)) {
9573 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9574 OS << " Predicates:\n";
9575 Pred.print(OS, 4);
9576 } else {
9577 OS << "Unpredictable predicated backedge-taken count. ";
9578 }
Dan Gohman69942932009-06-24 00:33:16 +00009579 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009580}
9581
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009582static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9583 switch (LD) {
9584 case ScalarEvolution::LoopVariant:
9585 return "Variant";
9586 case ScalarEvolution::LoopInvariant:
9587 return "Invariant";
9588 case ScalarEvolution::LoopComputable:
9589 return "Computable";
9590 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009591 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009592}
9593
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009594void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009595 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009596 // out SCEV values of all instructions that are interesting. Doing
9597 // this potentially causes it to create new SCEV objects though,
9598 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009599 // observable from outside the class though, so casting away the
9600 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009601 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009602
Dan Gohmanbc694912010-01-09 18:17:45 +00009603 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009604 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009605 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009606 for (Instruction &I : instructions(F))
9607 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9608 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009609 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009610 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009611 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009612 if (!isa<SCEVCouldNotCompute>(SV)) {
9613 OS << " U: ";
9614 SE.getUnsignedRange(SV).print(OS);
9615 OS << " S: ";
9616 SE.getSignedRange(SV).print(OS);
9617 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009618
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009619 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009620
Dan Gohmanaf752342009-07-07 17:06:11 +00009621 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009622 if (AtUse != SV) {
9623 OS << " --> ";
9624 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009625 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9626 OS << " U: ";
9627 SE.getUnsignedRange(AtUse).print(OS);
9628 OS << " S: ";
9629 SE.getSignedRange(AtUse).print(OS);
9630 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009631 }
9632
9633 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009634 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009635 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009636 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009637 OS << "<<Unknown>>";
9638 } else {
9639 OS << *ExitValue;
9640 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009641
9642 bool First = true;
9643 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9644 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009645 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009646 First = false;
9647 } else {
9648 OS << ", ";
9649 }
9650
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009651 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9652 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009653 }
9654
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009655 for (auto *InnerL : depth_first(L)) {
9656 if (InnerL == L)
9657 continue;
9658 if (First) {
9659 OS << "\t\t" "LoopDispositions: { ";
9660 First = false;
9661 } else {
9662 OS << ", ";
9663 }
9664
9665 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9666 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9667 }
9668
9669 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009670 }
9671
Chris Lattnerd934c702004-04-02 20:23:17 +00009672 OS << "\n";
9673 }
9674
Dan Gohmanbc694912010-01-09 18:17:45 +00009675 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009676 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009677 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009678 for (Loop *I : LI)
9679 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009680}
Dan Gohmane20f8242009-04-21 00:47:46 +00009681
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009682ScalarEvolution::LoopDisposition
9683ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009684 auto &Values = LoopDispositions[S];
9685 for (auto &V : Values) {
9686 if (V.getPointer() == L)
9687 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009688 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009689 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009690 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009691 auto &Values2 = LoopDispositions[S];
9692 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9693 if (V.getPointer() == L) {
9694 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009695 break;
9696 }
9697 }
9698 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009699}
9700
9701ScalarEvolution::LoopDisposition
9702ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009703 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009704 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009705 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009706 case scTruncate:
9707 case scZeroExtend:
9708 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009709 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009710 case scAddRecExpr: {
9711 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9712
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009713 // If L is the addrec's loop, it's computable.
9714 if (AR->getLoop() == L)
9715 return LoopComputable;
9716
Dan Gohmanafd6db92010-11-17 21:23:15 +00009717 // Add recurrences are never invariant in the function-body (null loop).
9718 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009719 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009720
9721 // This recurrence is variant w.r.t. L if L contains AR's loop.
9722 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009723 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009724
9725 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9726 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009727 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009728
9729 // This recurrence is variant w.r.t. L if any of its operands
9730 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009731 for (auto *Op : AR->operands())
9732 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009733 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009734
9735 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009736 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009737 }
9738 case scAddExpr:
9739 case scMulExpr:
9740 case scUMaxExpr:
9741 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009742 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009743 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9744 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009745 if (D == LoopVariant)
9746 return LoopVariant;
9747 if (D == LoopComputable)
9748 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009749 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009750 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009751 }
9752 case scUDivExpr: {
9753 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009754 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9755 if (LD == LoopVariant)
9756 return LoopVariant;
9757 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9758 if (RD == LoopVariant)
9759 return LoopVariant;
9760 return (LD == LoopInvariant && RD == LoopInvariant) ?
9761 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009762 }
9763 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009764 // All non-instruction values are loop invariant. All instructions are loop
9765 // invariant if they are not contained in the specified loop.
9766 // Instructions are never considered invariant in the function body
9767 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009768 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009769 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9770 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009771 case scCouldNotCompute:
9772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009773 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009774 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009775}
9776
9777bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9778 return getLoopDisposition(S, L) == LoopInvariant;
9779}
9780
9781bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9782 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009783}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009784
Dan Gohman8ea83d82010-11-18 00:34:22 +00009785ScalarEvolution::BlockDisposition
9786ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009787 auto &Values = BlockDispositions[S];
9788 for (auto &V : Values) {
9789 if (V.getPointer() == BB)
9790 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009791 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009792 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009793 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009794 auto &Values2 = BlockDispositions[S];
9795 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9796 if (V.getPointer() == BB) {
9797 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009798 break;
9799 }
9800 }
9801 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009802}
9803
Dan Gohman8ea83d82010-11-18 00:34:22 +00009804ScalarEvolution::BlockDisposition
9805ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009806 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009807 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009808 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009809 case scTruncate:
9810 case scZeroExtend:
9811 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009812 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009813 case scAddRecExpr: {
9814 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009815 // to test for proper dominance too, because the instruction which
9816 // produces the addrec's value is a PHI, and a PHI effectively properly
9817 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009818 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009819 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009820 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009821 }
9822 // FALL THROUGH into SCEVNAryExpr handling.
9823 case scAddExpr:
9824 case scMulExpr:
9825 case scUMaxExpr:
9826 case scSMaxExpr: {
9827 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009828 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009829 for (const SCEV *NAryOp : NAry->operands()) {
9830 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009831 if (D == DoesNotDominateBlock)
9832 return DoesNotDominateBlock;
9833 if (D == DominatesBlock)
9834 Proper = false;
9835 }
9836 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009837 }
9838 case scUDivExpr: {
9839 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009840 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9841 BlockDisposition LD = getBlockDisposition(LHS, BB);
9842 if (LD == DoesNotDominateBlock)
9843 return DoesNotDominateBlock;
9844 BlockDisposition RD = getBlockDisposition(RHS, BB);
9845 if (RD == DoesNotDominateBlock)
9846 return DoesNotDominateBlock;
9847 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9848 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009849 }
9850 case scUnknown:
9851 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009852 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9853 if (I->getParent() == BB)
9854 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009855 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009856 return ProperlyDominatesBlock;
9857 return DoesNotDominateBlock;
9858 }
9859 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009860 case scCouldNotCompute:
9861 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009862 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009863 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009864}
9865
9866bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9867 return getBlockDisposition(S, BB) >= DominatesBlock;
9868}
9869
9870bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9871 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009872}
Dan Gohman534749b2010-11-17 22:27:42 +00009873
9874bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009875 // Search for a SCEV expression node within an expression tree.
9876 // Implements SCEVTraversal::Visitor.
9877 struct SCEVSearch {
9878 const SCEV *Node;
9879 bool IsFound;
9880
9881 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9882
9883 bool follow(const SCEV *S) {
9884 IsFound |= (S == Node);
9885 return !IsFound;
9886 }
9887 bool isDone() const { return IsFound; }
9888 };
9889
Andrew Trick365e31c2012-07-13 23:33:03 +00009890 SCEVSearch Search(Op);
9891 visitAll(S, Search);
9892 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009893}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009894
9895void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9896 ValuesAtScopes.erase(S);
9897 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009898 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009899 UnsignedRanges.erase(S);
9900 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009901 ExprValueMap.erase(S);
9902 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009903
Silviu Baranga6f444df2016-04-08 14:29:09 +00009904 auto RemoveSCEVFromBackedgeMap =
9905 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9906 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9907 BackedgeTakenInfo &BEInfo = I->second;
9908 if (BEInfo.hasOperand(S, this)) {
9909 BEInfo.clear();
9910 Map.erase(I++);
9911 } else
9912 ++I;
9913 }
9914 };
9915
9916 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9917 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009918}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009919
9920typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009921
Alp Tokercb402912014-01-24 17:20:08 +00009922/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009923static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9924 size_t Pos = 0;
9925 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9926 Str.replace(Pos, From.size(), To.data(), To.size());
9927 Pos += To.size();
9928 }
9929}
9930
Benjamin Kramer214935e2012-10-26 17:31:32 +00009931/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9932static void
9933getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009934 std::string &S = Map[L];
9935 if (S.empty()) {
9936 raw_string_ostream OS(S);
9937 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009938
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009939 // false and 0 are semantically equivalent. This can happen in dead loops.
9940 replaceSubString(OS.str(), "false", "0");
9941 // Remove wrap flags, their use in SCEV is highly fragile.
9942 // FIXME: Remove this when SCEV gets smarter about them.
9943 replaceSubString(OS.str(), "<nw>", "");
9944 replaceSubString(OS.str(), "<nsw>", "");
9945 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009946 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009947
JF Bastien61ad8b32015-12-23 18:18:53 +00009948 for (auto *R : reverse(*L))
9949 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009950}
9951
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009952void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009953 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9954
9955 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9956 // FIXME: It would be much better to store actual values instead of strings,
9957 // but SCEV pointers will change if we drop the caches.
9958 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009959 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009960 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9961
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009962 // Gather stringified backedge taken counts for all loops using a fresh
9963 // ScalarEvolution object.
9964 ScalarEvolution SE2(F, TLI, AC, DT, LI);
9965 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9966 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009967
9968 // Now compare whether they're the same with and without caches. This allows
9969 // verifying that no pass changed the cache.
9970 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9971 "New loops suddenly appeared!");
9972
9973 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9974 OldE = BackedgeDumpsOld.end(),
9975 NewI = BackedgeDumpsNew.begin();
9976 OldI != OldE; ++OldI, ++NewI) {
9977 assert(OldI->first == NewI->first && "Loop order changed!");
9978
9979 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9980 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009981 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009982 // means that a pass is buggy or SCEV has to learn a new pattern but is
9983 // usually not harmful.
9984 if (OldI->second != NewI->second &&
9985 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009986 NewI->second.find("undef") == std::string::npos &&
9987 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00009988 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009989 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00009990 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009991 << "' changed from '" << OldI->second
9992 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00009993 std::abort();
9994 }
9995 }
9996
9997 // TODO: Verify more things.
9998}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009999
Chandler Carruthb4faf132016-03-11 10:22:49 +000010000char ScalarEvolutionAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010001
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010002ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +000010003 AnalysisManager<Function> &AM) {
10004 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10005 AM.getResult<AssumptionAnalysis>(F),
10006 AM.getResult<DominatorTreeAnalysis>(F),
10007 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010008}
10009
10010PreservedAnalyses
Chandler Carruthb47f8012016-03-11 11:05:24 +000010011ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> &AM) {
10012 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010013 return PreservedAnalyses::all();
10014}
10015
10016INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10017 "Scalar Evolution Analysis", false, true)
10018INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10019INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10020INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10021INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10022INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10023 "Scalar Evolution Analysis", false, true)
10024char ScalarEvolutionWrapperPass::ID = 0;
10025
10026ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10027 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10028}
10029
10030bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10031 SE.reset(new ScalarEvolution(
10032 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10033 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10034 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10035 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10036 return false;
10037}
10038
10039void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10040
10041void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10042 SE->print(OS);
10043}
10044
10045void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10046 if (!VerifySCEV)
10047 return;
10048
10049 SE->verify();
10050}
10051
10052void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10053 AU.setPreservesAll();
10054 AU.addRequiredTransitive<AssumptionCacheTracker>();
10055 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10056 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10057 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10058}
Silviu Barangae3c05342015-11-02 14:41:02 +000010059
10060const SCEVPredicate *
10061ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10062 const SCEVConstant *RHS) {
10063 FoldingSetNodeID ID;
10064 // Unique this node based on the arguments
10065 ID.AddInteger(SCEVPredicate::P_Equal);
10066 ID.AddPointer(LHS);
10067 ID.AddPointer(RHS);
10068 void *IP = nullptr;
10069 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10070 return S;
10071 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10072 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10073 UniquePreds.InsertNode(Eq, IP);
10074 return Eq;
10075}
10076
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010077const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10078 const SCEVAddRecExpr *AR,
10079 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10080 FoldingSetNodeID ID;
10081 // Unique this node based on the arguments
10082 ID.AddInteger(SCEVPredicate::P_Wrap);
10083 ID.AddPointer(AR);
10084 ID.AddInteger(AddedFlags);
10085 void *IP = nullptr;
10086 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10087 return S;
10088 auto *OF = new (SCEVAllocator)
10089 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10090 UniquePreds.InsertNode(OF, IP);
10091 return OF;
10092}
10093
Benjamin Kramer83709b12015-11-16 09:01:28 +000010094namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010095
Silviu Barangae3c05342015-11-02 14:41:02 +000010096class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10097public:
Sanjoy Das807d33d2016-02-20 01:44:10 +000010098 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010099 // If Assume is true, rewrite is free to add further predicates to A
10100 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010101 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10102 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010103 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010104 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010105 }
10106
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010107 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10108 SCEVUnionPredicate &P, bool Assume)
10109 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010110
10111 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10112 auto ExprPreds = P.getPredicatesForExpr(Expr);
10113 for (auto *Pred : ExprPreds)
Sanjoy Dasb277a422016-06-15 06:53:55 +000010114 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
Silviu Barangae3c05342015-11-02 14:41:02 +000010115 if (IPred->getLHS() == Expr)
10116 return IPred->getRHS();
10117
10118 return Expr;
10119 }
10120
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010121 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10122 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010123 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010124 if (AR && AR->getLoop() == L && AR->isAffine()) {
10125 // This couldn't be folded because the operand didn't have the nuw
10126 // flag. Add the nusw flag as an assumption that we could make.
10127 const SCEV *Step = AR->getStepRecurrence(SE);
10128 Type *Ty = Expr->getType();
10129 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10130 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10131 SE.getSignExtendExpr(Step, Ty), L,
10132 AR->getNoWrapFlags());
10133 }
10134 return SE.getZeroExtendExpr(Operand, Expr->getType());
10135 }
10136
10137 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10138 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010139 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010140 if (AR && AR->getLoop() == L && AR->isAffine()) {
10141 // This couldn't be folded because the operand didn't have the nsw
10142 // flag. Add the nssw flag as an assumption that we could make.
10143 const SCEV *Step = AR->getStepRecurrence(SE);
10144 Type *Ty = Expr->getType();
10145 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10146 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10147 SE.getSignExtendExpr(Step, Ty), L,
10148 AR->getNoWrapFlags());
10149 }
10150 return SE.getSignExtendExpr(Operand, Expr->getType());
10151 }
10152
Silviu Barangae3c05342015-11-02 14:41:02 +000010153private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010154 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10155 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10156 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10157 if (!Assume) {
10158 // Check if we've already made this assumption.
10159 if (P.implies(A))
10160 return true;
10161 return false;
10162 }
10163 P.add(A);
10164 return true;
10165 }
10166
Silviu Barangae3c05342015-11-02 14:41:02 +000010167 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010168 const Loop *L;
10169 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +000010170};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010171} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010172
Sanjoy Das807d33d2016-02-20 01:44:10 +000010173const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010174 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +000010175 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010176}
10177
Silviu Barangad68ed852016-03-23 15:29:30 +000010178const SCEVAddRecExpr *
Sanjoy Das807d33d2016-02-20 01:44:10 +000010179ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
10180 SCEVUnionPredicate &Preds) {
Silviu Barangad68ed852016-03-23 15:29:30 +000010181 SCEVUnionPredicate TransformPreds;
10182 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true);
10183 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10184
10185 if (!AddRec)
10186 return nullptr;
10187
10188 // Since the transformation was successful, we can now transfer the SCEV
10189 // predicates.
10190 Preds.add(&TransformPreds);
10191 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010192}
10193
10194/// SCEV predicates
10195SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10196 SCEVPredicateKind Kind)
10197 : FastID(ID), Kind(Kind) {}
10198
10199SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10200 const SCEVUnknown *LHS,
10201 const SCEVConstant *RHS)
10202 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10203
10204bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010205 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010206
10207 if (!Op)
10208 return false;
10209
10210 return Op->LHS == LHS && Op->RHS == RHS;
10211}
10212
10213bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10214
10215const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10216
10217void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10218 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10219}
10220
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010221SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10222 const SCEVAddRecExpr *AR,
10223 IncrementWrapFlags Flags)
10224 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10225
10226const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10227
10228bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10229 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10230
10231 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10232}
10233
10234bool SCEVWrapPredicate::isAlwaysTrue() const {
10235 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10236 IncrementWrapFlags IFlags = Flags;
10237
10238 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10239 IFlags = clearFlags(IFlags, IncrementNSSW);
10240
10241 return IFlags == IncrementAnyWrap;
10242}
10243
10244void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10245 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10246 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10247 OS << "<nusw>";
10248 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10249 OS << "<nssw>";
10250 OS << "\n";
10251}
10252
10253SCEVWrapPredicate::IncrementWrapFlags
10254SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10255 ScalarEvolution &SE) {
10256 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10257 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10258
10259 // We can safely transfer the NSW flag as NSSW.
10260 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10261 ImpliedFlags = IncrementNSSW;
10262
10263 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10264 // If the increment is positive, the SCEV NUW flag will also imply the
10265 // WrapPredicate NUSW flag.
10266 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10267 if (Step->getValue()->getValue().isNonNegative())
10268 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10269 }
10270
10271 return ImpliedFlags;
10272}
10273
Silviu Barangae3c05342015-11-02 14:41:02 +000010274/// Union predicates don't get cached so create a dummy set ID for it.
10275SCEVUnionPredicate::SCEVUnionPredicate()
10276 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10277
10278bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010279 return all_of(Preds,
10280 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010281}
10282
10283ArrayRef<const SCEVPredicate *>
10284SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10285 auto I = SCEVToPreds.find(Expr);
10286 if (I == SCEVToPreds.end())
10287 return ArrayRef<const SCEVPredicate *>();
10288 return I->second;
10289}
10290
10291bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010292 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010293 return all_of(Set->Preds,
10294 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010295
10296 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10297 if (ScevPredsIt == SCEVToPreds.end())
10298 return false;
10299 auto &SCEVPreds = ScevPredsIt->second;
10300
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010301 return any_of(SCEVPreds,
10302 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010303}
10304
10305const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10306
10307void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10308 for (auto Pred : Preds)
10309 Pred->print(OS, Depth);
10310}
10311
10312void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010313 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010314 for (auto Pred : Set->Preds)
10315 add(Pred);
10316 return;
10317 }
10318
10319 if (implies(N))
10320 return;
10321
10322 const SCEV *Key = N->getExpr();
10323 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10324 " associated expression!");
10325
10326 SCEVToPreds[Key].push_back(N);
10327 Preds.push_back(N);
10328}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010329
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010330PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10331 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010332 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010333
10334const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10335 const SCEV *Expr = SE.getSCEV(V);
10336 RewriteEntry &Entry = RewriteMap[Expr];
10337
10338 // If we already have an entry and the version matches, return it.
10339 if (Entry.second && Generation == Entry.first)
10340 return Entry.second;
10341
10342 // We found an entry but it's stale. Rewrite the stale entry
10343 // acording to the current predicate.
10344 if (Entry.second)
10345 Expr = Entry.second;
10346
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010347 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010348 Entry = {Generation, NewSCEV};
10349
10350 return NewSCEV;
10351}
10352
Silviu Baranga6f444df2016-04-08 14:29:09 +000010353const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10354 if (!BackedgeCount) {
10355 SCEVUnionPredicate BackedgePred;
10356 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10357 addPredicate(BackedgePred);
10358 }
10359 return BackedgeCount;
10360}
10361
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010362void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10363 if (Preds.implies(&Pred))
10364 return;
10365 Preds.add(&Pred);
10366 updateGeneration();
10367}
10368
10369const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10370 return Preds;
10371}
10372
10373void PredicatedScalarEvolution::updateGeneration() {
10374 // If the generation number wrapped recompute everything.
10375 if (++Generation == 0) {
10376 for (auto &II : RewriteMap) {
10377 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010378 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010379 }
10380 }
10381}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010382
10383void PredicatedScalarEvolution::setNoOverflow(
10384 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10385 const SCEV *Expr = getSCEV(V);
10386 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10387
10388 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10389
10390 // Clear the statically implied flags.
10391 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10392 addPredicate(*SE.getWrapPredicate(AR, Flags));
10393
10394 auto II = FlagsMap.insert({V, Flags});
10395 if (!II.second)
10396 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10397}
10398
10399bool PredicatedScalarEvolution::hasNoOverflow(
10400 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10401 const SCEV *Expr = getSCEV(V);
10402 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10403
10404 Flags = SCEVWrapPredicate::clearFlags(
10405 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10406
10407 auto II = FlagsMap.find(V);
10408
10409 if (II != FlagsMap.end())
10410 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10411
10412 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10413}
10414
Silviu Barangad68ed852016-03-23 15:29:30 +000010415const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010416 const SCEV *Expr = this->getSCEV(V);
Silviu Barangad68ed852016-03-23 15:29:30 +000010417 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10418
10419 if (!New)
10420 return nullptr;
10421
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010422 updateGeneration();
10423 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10424 return New;
10425}
10426
Silviu Baranga6f444df2016-04-08 14:29:09 +000010427PredicatedScalarEvolution::PredicatedScalarEvolution(
10428 const PredicatedScalarEvolution &Init)
10429 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10430 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010431 for (const auto &I : Init.FlagsMap)
10432 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010433}
Silviu Barangab77365b2016-04-14 16:08:45 +000010434
10435void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10436 // For each block.
10437 for (auto *BB : L.getBlocks())
10438 for (auto &I : *BB) {
10439 if (!SE.isSCEVable(I.getType()))
10440 continue;
10441
10442 auto *Expr = SE.getSCEV(&I);
10443 auto II = RewriteMap.find(Expr);
10444
10445 if (II == RewriteMap.end())
10446 continue;
10447
10448 // Don't print things that are not interesting.
10449 if (II->second.second == Expr)
10450 continue;
10451
10452 OS.indent(Depth) << "[PSE]" << I << ":\n";
10453 OS.indent(Depth + 2) << *Expr << "\n";
10454 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10455 }
10456}