Bug Summary

File:lib/Analysis/ScalarEvolution.cpp
Warning:line 9195, column 15
Value stored to 'MaxBECount' during its initialization is never read

Annotated Source Code

<
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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
17// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
19//
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.
30//
31// 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//
35// 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
61#include "llvm/Analysis/ScalarEvolution.h"
62#include "llvm/ADT/Optional.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/Sequence.h"
66#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/Statistic.h"
68#include "llvm/Analysis/AssumptionCache.h"
69#include "llvm/Analysis/ConstantFolding.h"
70#include "llvm/Analysis/InstructionSimplify.h"
71#include "llvm/Analysis/LoopInfo.h"
72#include "llvm/Analysis/ScalarEvolutionExpressions.h"
73#include "llvm/Analysis/TargetLibraryInfo.h"
74#include "llvm/Analysis/ValueTracking.h"
75#include "llvm/IR/ConstantRange.h"
76#include "llvm/IR/Constants.h"
77#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/DerivedTypes.h"
79#include "llvm/IR/Dominators.h"
80#include "llvm/IR/GetElementPtrTypeIterator.h"
81#include "llvm/IR/GlobalAlias.h"
82#include "llvm/IR/GlobalVariable.h"
83#include "llvm/IR/InstIterator.h"
84#include "llvm/IR/Instructions.h"
85#include "llvm/IR/LLVMContext.h"
86#include "llvm/IR/Metadata.h"
87#include "llvm/IR/Operator.h"
88#include "llvm/IR/PatternMatch.h"
89#include "llvm/Support/CommandLine.h"
90#include "llvm/Support/Debug.h"
91#include "llvm/Support/ErrorHandling.h"
92#include "llvm/Support/MathExtras.h"
93#include "llvm/Support/raw_ostream.h"
94#include "llvm/Support/SaveAndRestore.h"
95#include <algorithm>
96using namespace llvm;
97
98#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
99
100STATISTIC(NumArrayLenItCounts,static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, false}
101 "Number of trip counts computed with array length")static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, false}
;
102STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, false}
103 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, false}
;
104STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, false}
105 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, false}
;
106STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, false}
107 "Number of loops with trip counts computed by force")static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, false}
;
108
109static cl::opt<unsigned>
110MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111 cl::desc("Maximum number of iterations SCEV will "
112 "symbolically execute a constant "
113 "derived loop"),
114 cl::init(100));
115
116// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
117static cl::opt<bool>
118VerifySCEV("verify-scev",
119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
120static cl::opt<bool>
121 VerifySCEVMap("verify-scev-maps",
122 cl::desc("Verify no dangling value in ScalarEvolution's "
123 "ExprValueMap (slow)"));
124
125static cl::opt<unsigned> MulOpsInlineThreshold(
126 "scev-mulops-inline-threshold", cl::Hidden,
127 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128 cl::init(1000));
129
130static cl::opt<unsigned> AddOpsInlineThreshold(
131 "scev-addops-inline-threshold", cl::Hidden,
132 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
133 cl::init(500));
134
135static cl::opt<unsigned> MaxSCEVCompareDepth(
136 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
137 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
138 cl::init(32));
139
140static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
141 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
142 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
143 cl::init(2));
144
145static cl::opt<unsigned> MaxValueCompareDepth(
146 "scalar-evolution-max-value-compare-depth", cl::Hidden,
147 cl::desc("Maximum depth of recursive value complexity comparisons"),
148 cl::init(2));
149
150static cl::opt<unsigned>
151 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
152 cl::desc("Maximum depth of recursive AddExpr"),
153 cl::init(32));
154
155static cl::opt<unsigned> MaxConstantEvolvingDepth(
156 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
157 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
158
159//===----------------------------------------------------------------------===//
160// SCEV class definitions
161//===----------------------------------------------------------------------===//
162
163//===----------------------------------------------------------------------===//
164// Implementation of the SCEV class.
165//
166
167#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
169 print(dbgs());
170 dbgs() << '\n';
171}
172#endif
173
174void SCEV::print(raw_ostream &OS) const {
175 switch (static_cast<SCEVTypes>(getSCEVType())) {
176 case scConstant:
177 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
178 return;
179 case scTruncate: {
180 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
181 const SCEV *Op = Trunc->getOperand();
182 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
183 << *Trunc->getType() << ")";
184 return;
185 }
186 case scZeroExtend: {
187 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
188 const SCEV *Op = ZExt->getOperand();
189 OS << "(zext " << *Op->getType() << " " << *Op << " to "
190 << *ZExt->getType() << ")";
191 return;
192 }
193 case scSignExtend: {
194 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
195 const SCEV *Op = SExt->getOperand();
196 OS << "(sext " << *Op->getType() << " " << *Op << " to "
197 << *SExt->getType() << ")";
198 return;
199 }
200 case scAddRecExpr: {
201 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
202 OS << "{" << *AR->getOperand(0);
203 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
204 OS << ",+," << *AR->getOperand(i);
205 OS << "}<";
206 if (AR->hasNoUnsignedWrap())
207 OS << "nuw><";
208 if (AR->hasNoSignedWrap())
209 OS << "nsw><";
210 if (AR->hasNoSelfWrap() &&
211 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
212 OS << "nw><";
213 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
214 OS << ">";
215 return;
216 }
217 case scAddExpr:
218 case scMulExpr:
219 case scUMaxExpr:
220 case scSMaxExpr: {
221 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
222 const char *OpStr = nullptr;
223 switch (NAry->getSCEVType()) {
224 case scAddExpr: OpStr = " + "; break;
225 case scMulExpr: OpStr = " * "; break;
226 case scUMaxExpr: OpStr = " umax "; break;
227 case scSMaxExpr: OpStr = " smax "; break;
228 }
229 OS << "(";
230 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
231 I != E; ++I) {
232 OS << **I;
233 if (std::next(I) != E)
234 OS << OpStr;
235 }
236 OS << ")";
237 switch (NAry->getSCEVType()) {
238 case scAddExpr:
239 case scMulExpr:
240 if (NAry->hasNoUnsignedWrap())
241 OS << "<nuw>";
242 if (NAry->hasNoSignedWrap())
243 OS << "<nsw>";
244 }
245 return;
246 }
247 case scUDivExpr: {
248 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
249 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
250 return;
251 }
252 case scUnknown: {
253 const SCEVUnknown *U = cast<SCEVUnknown>(this);
254 Type *AllocTy;
255 if (U->isSizeOf(AllocTy)) {
256 OS << "sizeof(" << *AllocTy << ")";
257 return;
258 }
259 if (U->isAlignOf(AllocTy)) {
260 OS << "alignof(" << *AllocTy << ")";
261 return;
262 }
263
264 Type *CTy;
265 Constant *FieldNo;
266 if (U->isOffsetOf(CTy, FieldNo)) {
267 OS << "offsetof(" << *CTy << ", ";
268 FieldNo->printAsOperand(OS, false);
269 OS << ")";
270 return;
271 }
272
273 // Otherwise just print it normally.
274 U->getValue()->printAsOperand(OS, false);
275 return;
276 }
277 case scCouldNotCompute:
278 OS << "***COULDNOTCOMPUTE***";
279 return;
280 }
281 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 281)
;
282}
283
284Type *SCEV::getType() const {
285 switch (static_cast<SCEVTypes>(getSCEVType())) {
286 case scConstant:
287 return cast<SCEVConstant>(this)->getType();
288 case scTruncate:
289 case scZeroExtend:
290 case scSignExtend:
291 return cast<SCEVCastExpr>(this)->getType();
292 case scAddRecExpr:
293 case scMulExpr:
294 case scUMaxExpr:
295 case scSMaxExpr:
296 return cast<SCEVNAryExpr>(this)->getType();
297 case scAddExpr:
298 return cast<SCEVAddExpr>(this)->getType();
299 case scUDivExpr:
300 return cast<SCEVUDivExpr>(this)->getType();
301 case scUnknown:
302 return cast<SCEVUnknown>(this)->getType();
303 case scCouldNotCompute:
304 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 304)
;
305 }
306 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 306)
;
307}
308
309bool SCEV::isZero() const {
310 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
311 return SC->getValue()->isZero();
312 return false;
313}
314
315bool SCEV::isOne() const {
316 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
317 return SC->getValue()->isOne();
318 return false;
319}
320
321bool SCEV::isAllOnesValue() const {
322 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
323 return SC->getValue()->isAllOnesValue();
324 return false;
325}
326
327bool SCEV::isNonConstantNegative() const {
328 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
329 if (!Mul) return false;
330
331 // If there is a constant factor, it will be first.
332 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
333 if (!SC) return false;
334
335 // Return true if the value is negative, this matches things like (-42 * V).
336 return SC->getAPInt().isNegative();
337}
338
339SCEVCouldNotCompute::SCEVCouldNotCompute() :
340 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
341
342bool SCEVCouldNotCompute::classof(const SCEV *S) {
343 return S->getSCEVType() == scCouldNotCompute;
344}
345
346const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
347 FoldingSetNodeID ID;
348 ID.AddInteger(scConstant);
349 ID.AddPointer(V);
350 void *IP = nullptr;
351 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
352 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
353 UniqueSCEVs.InsertNode(S, IP);
354 return S;
355}
356
357const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
358 return getConstant(ConstantInt::get(getContext(), Val));
359}
360
361const SCEV *
362ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
363 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
364 return getConstant(ConstantInt::get(ITy, V, isSigned));
365}
366
367SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
368 unsigned SCEVTy, const SCEV *op, Type *ty)
369 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
370
371SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
372 const SCEV *op, Type *ty)
373 : SCEVCastExpr(ID, scTruncate, op, ty) {
374 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 376, __PRETTY_FUNCTION__))
375 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 376, __PRETTY_FUNCTION__))
376 "Cannot truncate non-integer value!")(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 376, __PRETTY_FUNCTION__))
;
377}
378
379SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
380 const SCEV *op, Type *ty)
381 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
382 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 384, __PRETTY_FUNCTION__))
383 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 384, __PRETTY_FUNCTION__))
384 "Cannot zero extend non-integer value!")(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 384, __PRETTY_FUNCTION__))
;
385}
386
387SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
388 const SCEV *op, Type *ty)
389 : SCEVCastExpr(ID, scSignExtend, op, ty) {
390 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 392, __PRETTY_FUNCTION__))
391 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 392, __PRETTY_FUNCTION__))
392 "Cannot sign extend non-integer value!")(((Op->getType()->isIntegerTy() || Op->getType()->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 392, __PRETTY_FUNCTION__))
;
393}
394
395void SCEVUnknown::deleted() {
396 // Clear this SCEVUnknown from various maps.
397 SE->forgetMemoizedResults(this);
398
399 // Remove this SCEVUnknown from the uniquing map.
400 SE->UniqueSCEVs.RemoveNode(this);
401
402 // Release the value.
403 setValPtr(nullptr);
404}
405
406void SCEVUnknown::allUsesReplacedWith(Value *New) {
407 // Clear this SCEVUnknown from various maps.
408 SE->forgetMemoizedResults(this);
409
410 // Remove this SCEVUnknown from the uniquing map.
411 SE->UniqueSCEVs.RemoveNode(this);
412
413 // Update this SCEVUnknown to point to the new value. This is needed
414 // because there may still be outstanding SCEVs which still point to
415 // this SCEVUnknown.
416 setValPtr(New);
417}
418
419bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
420 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
421 if (VCE->getOpcode() == Instruction::PtrToInt)
422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
423 if (CE->getOpcode() == Instruction::GetElementPtr &&
424 CE->getOperand(0)->isNullValue() &&
425 CE->getNumOperands() == 2)
426 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
427 if (CI->isOne()) {
428 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
429 ->getElementType();
430 return true;
431 }
432
433 return false;
434}
435
436bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getOperand(0)->isNullValue()) {
442 Type *Ty =
443 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
444 if (StructType *STy = dyn_cast<StructType>(Ty))
445 if (!STy->isPacked() &&
446 CE->getNumOperands() == 3 &&
447 CE->getOperand(1)->isNullValue()) {
448 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
449 if (CI->isOne() &&
450 STy->getNumElements() == 2 &&
451 STy->getElementType(0)->isIntegerTy(1)) {
452 AllocTy = STy->getElementType(1);
453 return true;
454 }
455 }
456 }
457
458 return false;
459}
460
461bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
462 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
463 if (VCE->getOpcode() == Instruction::PtrToInt)
464 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
465 if (CE->getOpcode() == Instruction::GetElementPtr &&
466 CE->getNumOperands() == 3 &&
467 CE->getOperand(0)->isNullValue() &&
468 CE->getOperand(1)->isNullValue()) {
469 Type *Ty =
470 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
471 // Ignore vector types here so that ScalarEvolutionExpander doesn't
472 // emit getelementptrs that index into vectors.
473 if (Ty->isStructTy() || Ty->isArrayTy()) {
474 CTy = Ty;
475 FieldNo = CE->getOperand(2);
476 return true;
477 }
478 }
479
480 return false;
481}
482
483//===----------------------------------------------------------------------===//
484// SCEV Utilities
485//===----------------------------------------------------------------------===//
486
487/// Compare the two values \p LV and \p RV in terms of their "complexity" where
488/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
489/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
490/// have been previously deemed to be "equally complex" by this routine. It is
491/// intended to avoid exponential time complexity in cases like:
492///
493/// %a = f(%x, %y)
494/// %b = f(%a, %a)
495/// %c = f(%b, %b)
496///
497/// %d = f(%x, %y)
498/// %e = f(%d, %d)
499/// %f = f(%e, %e)
500///
501/// CompareValueComplexity(%f, %c)
502///
503/// Since we do not continue running this routine on expression trees once we
504/// have seen unequal values, there is no need to track them in the cache.
505static int
506CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
507 const LoopInfo *const LI, Value *LV, Value *RV,
508 unsigned Depth) {
509 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
510 return 0;
511
512 // Order pointer values after integer values. This helps SCEVExpander form
513 // GEPs.
514 bool LIsPointer = LV->getType()->isPointerTy(),
515 RIsPointer = RV->getType()->isPointerTy();
516 if (LIsPointer != RIsPointer)
517 return (int)LIsPointer - (int)RIsPointer;
518
519 // Compare getValueID values.
520 unsigned LID = LV->getValueID(), RID = RV->getValueID();
521 if (LID != RID)
522 return (int)LID - (int)RID;
523
524 // Sort arguments by their position.
525 if (const auto *LA = dyn_cast<Argument>(LV)) {
526 const auto *RA = cast<Argument>(RV);
527 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
528 return (int)LArgNo - (int)RArgNo;
529 }
530
531 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
532 const auto *RGV = cast<GlobalValue>(RV);
533
534 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
535 auto LT = GV->getLinkage();
536 return !(GlobalValue::isPrivateLinkage(LT) ||
537 GlobalValue::isInternalLinkage(LT));
538 };
539
540 // Use the names to distinguish the two values, but only if the
541 // names are semantically important.
542 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
543 return LGV->getName().compare(RGV->getName());
544 }
545
546 // For instructions, compare their loop depth, and their operand count. This
547 // is pretty loose.
548 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
549 const auto *RInst = cast<Instruction>(RV);
550
551 // Compare loop depths.
552 const BasicBlock *LParent = LInst->getParent(),
553 *RParent = RInst->getParent();
554 if (LParent != RParent) {
555 unsigned LDepth = LI->getLoopDepth(LParent),
556 RDepth = LI->getLoopDepth(RParent);
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Compare the number of operands.
562 unsigned LNumOps = LInst->getNumOperands(),
563 RNumOps = RInst->getNumOperands();
564 if (LNumOps != RNumOps)
565 return (int)LNumOps - (int)RNumOps;
566
567 for (unsigned Idx : seq(0u, LNumOps)) {
568 int Result =
569 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
570 RInst->getOperand(Idx), Depth + 1);
571 if (Result != 0)
572 return Result;
573 }
574 }
575
576 EqCache.insert({LV, RV});
577 return 0;
578}
579
580// Return negative, zero, or positive, if LHS is less than, equal to, or greater
581// than RHS, respectively. A three-way result allows recursive comparisons to be
582// more efficient.
583static int CompareSCEVComplexity(
584 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
585 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
586 unsigned Depth = 0) {
587 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
588 if (LHS == RHS)
589 return 0;
590
591 // Primarily, sort the SCEVs by their getSCEVType().
592 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
593 if (LType != RType)
594 return (int)LType - (int)RType;
595
596 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
597 return 0;
598 // Aside from the getSCEVType() ordering, the particular ordering
599 // isn't very important except that it's beneficial to be consistent,
600 // so that (a + b) and (b + a) don't end up as different expressions.
601 switch (static_cast<SCEVTypes>(LType)) {
602 case scUnknown: {
603 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
604 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
605
606 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
607 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
608 Depth + 1);
609 if (X == 0)
610 EqCacheSCEV.insert({LHS, RHS});
611 return X;
612 }
613
614 case scConstant: {
615 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
616 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
617
618 // Compare constant values.
619 const APInt &LA = LC->getAPInt();
620 const APInt &RA = RC->getAPInt();
621 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
622 if (LBitWidth != RBitWidth)
623 return (int)LBitWidth - (int)RBitWidth;
624 return LA.ult(RA) ? -1 : 1;
625 }
626
627 case scAddRecExpr: {
628 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
629 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
630
631 // Compare addrec loop depths.
632 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
633 if (LLoop != RLoop) {
634 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
635 if (LDepth != RDepth)
636 return (int)LDepth - (int)RDepth;
637 }
638
639 // Addrec complexity grows with operand count.
640 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
641 if (LNumOps != RNumOps)
642 return (int)LNumOps - (int)RNumOps;
643
644 // Lexicographically compare.
645 for (unsigned i = 0; i != LNumOps; ++i) {
646 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
647 RA->getOperand(i), Depth + 1);
648 if (X != 0)
649 return X;
650 }
651 EqCacheSCEV.insert({LHS, RHS});
652 return 0;
653 }
654
655 case scAddExpr:
656 case scMulExpr:
657 case scSMaxExpr:
658 case scUMaxExpr: {
659 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
660 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
661
662 // Lexicographically compare n-ary expressions.
663 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
664 if (LNumOps != RNumOps)
665 return (int)LNumOps - (int)RNumOps;
666
667 for (unsigned i = 0; i != LNumOps; ++i) {
668 if (i >= RNumOps)
669 return 1;
670 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
671 RC->getOperand(i), Depth + 1);
672 if (X != 0)
673 return X;
674 }
675 EqCacheSCEV.insert({LHS, RHS});
676 return 0;
677 }
678
679 case scUDivExpr: {
680 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
681 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
682
683 // Lexicographically compare udiv expressions.
684 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
685 Depth + 1);
686 if (X != 0)
687 return X;
688 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
689 Depth + 1);
690 if (X == 0)
691 EqCacheSCEV.insert({LHS, RHS});
692 return X;
693 }
694
695 case scTruncate:
696 case scZeroExtend:
697 case scSignExtend: {
698 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
699 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
700
701 // Compare cast expressions by operand.
702 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
703 RC->getOperand(), Depth + 1);
704 if (X == 0)
705 EqCacheSCEV.insert({LHS, RHS});
706 return X;
707 }
708
709 case scCouldNotCompute:
710 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 710)
;
711 }
712 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 712)
;
713}
714
715/// Given a list of SCEV objects, order them by their complexity, and group
716/// objects of the same complexity together by value. When this routine is
717/// finished, we know that any duplicates in the vector are consecutive and that
718/// complexity is monotonically increasing.
719///
720/// Note that we go take special precautions to ensure that we get deterministic
721/// results from this routine. In other words, we don't want the results of
722/// this to depend on where the addresses of various SCEV objects happened to
723/// land in memory.
724///
725static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
726 LoopInfo *LI) {
727 if (Ops.size() < 2) return; // Noop
728
729 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
730 if (Ops.size() == 2) {
731 // This is the common case, which also happens to be trivially simple.
732 // Special case it.
733 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
734 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
735 std::swap(LHS, RHS);
736 return;
737 }
738
739 // Do the rough sort by complexity.
740 std::stable_sort(Ops.begin(), Ops.end(),
741 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
742 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
743 });
744
745 // Now that we are sorted by complexity, group elements of the same
746 // complexity. Note that this is, at worst, N^2, but the vector is likely to
747 // be extremely short in practice. Note that we take this approach because we
748 // do not want to depend on the addresses of the objects we are grouping.
749 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
750 const SCEV *S = Ops[i];
751 unsigned Complexity = S->getSCEVType();
752
753 // If there are any objects of the same complexity and same value as this
754 // one, group them.
755 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
756 if (Ops[j] == S) { // Found a duplicate.
757 // Move it to immediately after i'th element.
758 std::swap(Ops[i+1], Ops[j]);
759 ++i; // no need to rescan it.
760 if (i == e-2) return; // Done!
761 }
762 }
763 }
764}
765
766// Returns the size of the SCEV S.
767static inline int sizeOfSCEV(const SCEV *S) {
768 struct FindSCEVSize {
769 int Size;
770 FindSCEVSize() : Size(0) {}
771
772 bool follow(const SCEV *S) {
773 ++Size;
774 // Keep looking at all operands of S.
775 return true;
776 }
777 bool isDone() const {
778 return false;
779 }
780 };
781
782 FindSCEVSize F;
783 SCEVTraversal<FindSCEVSize> ST(F);
784 ST.visitAll(S);
785 return F.Size;
786}
787
788namespace {
789
790struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
791public:
792 // Computes the Quotient and Remainder of the division of Numerator by
793 // Denominator.
794 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
795 const SCEV *Denominator, const SCEV **Quotient,
796 const SCEV **Remainder) {
797 assert(Numerator && Denominator && "Uninitialized SCEV")((Numerator && Denominator && "Uninitialized SCEV"
) ? static_cast<void> (0) : __assert_fail ("Numerator && Denominator && \"Uninitialized SCEV\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 797, __PRETTY_FUNCTION__))
;
798
799 SCEVDivision D(SE, Numerator, Denominator);
800
801 // Check for the trivial case here to avoid having to check for it in the
802 // rest of the code.
803 if (Numerator == Denominator) {
804 *Quotient = D.One;
805 *Remainder = D.Zero;
806 return;
807 }
808
809 if (Numerator->isZero()) {
810 *Quotient = D.Zero;
811 *Remainder = D.Zero;
812 return;
813 }
814
815 // A simple case when N/1. The quotient is N.
816 if (Denominator->isOne()) {
817 *Quotient = Numerator;
818 *Remainder = D.Zero;
819 return;
820 }
821
822 // Split the Denominator when it is a product.
823 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
824 const SCEV *Q, *R;
825 *Quotient = Numerator;
826 for (const SCEV *Op : T->operands()) {
827 divide(SE, *Quotient, Op, &Q, &R);
828 *Quotient = Q;
829
830 // Bail out when the Numerator is not divisible by one of the terms of
831 // the Denominator.
832 if (!R->isZero()) {
833 *Quotient = D.Zero;
834 *Remainder = Numerator;
835 return;
836 }
837 }
838 *Remainder = D.Zero;
839 return;
840 }
841
842 D.visit(Numerator);
843 *Quotient = D.Quotient;
844 *Remainder = D.Remainder;
845 }
846
847 // Except in the trivial case described above, we do not know how to divide
848 // Expr by Denominator for the following functions with empty implementation.
849 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
850 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
851 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
852 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
853 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
854 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
855 void visitUnknown(const SCEVUnknown *Numerator) {}
856 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
857
858 void visitConstant(const SCEVConstant *Numerator) {
859 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
860 APInt NumeratorVal = Numerator->getAPInt();
861 APInt DenominatorVal = D->getAPInt();
862 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
863 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
864
865 if (NumeratorBW > DenominatorBW)
866 DenominatorVal = DenominatorVal.sext(NumeratorBW);
867 else if (NumeratorBW < DenominatorBW)
868 NumeratorVal = NumeratorVal.sext(DenominatorBW);
869
870 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
871 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
872 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
873 Quotient = SE.getConstant(QuotientVal);
874 Remainder = SE.getConstant(RemainderVal);
875 return;
876 }
877 }
878
879 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
880 const SCEV *StartQ, *StartR, *StepQ, *StepR;
881 if (!Numerator->isAffine())
882 return cannotDivide(Numerator);
883 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
884 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
885 // Bail out if the types do not match.
886 Type *Ty = Denominator->getType();
887 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
888 Ty != StepQ->getType() || Ty != StepR->getType())
889 return cannotDivide(Numerator);
890 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
891 Numerator->getNoWrapFlags());
892 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
893 Numerator->getNoWrapFlags());
894 }
895
896 void visitAddExpr(const SCEVAddExpr *Numerator) {
897 SmallVector<const SCEV *, 2> Qs, Rs;
898 Type *Ty = Denominator->getType();
899
900 for (const SCEV *Op : Numerator->operands()) {
901 const SCEV *Q, *R;
902 divide(SE, Op, Denominator, &Q, &R);
903
904 // Bail out if types do not match.
905 if (Ty != Q->getType() || Ty != R->getType())
906 return cannotDivide(Numerator);
907
908 Qs.push_back(Q);
909 Rs.push_back(R);
910 }
911
912 if (Qs.size() == 1) {
913 Quotient = Qs[0];
914 Remainder = Rs[0];
915 return;
916 }
917
918 Quotient = SE.getAddExpr(Qs);
919 Remainder = SE.getAddExpr(Rs);
920 }
921
922 void visitMulExpr(const SCEVMulExpr *Numerator) {
923 SmallVector<const SCEV *, 2> Qs;
924 Type *Ty = Denominator->getType();
925
926 bool FoundDenominatorTerm = false;
927 for (const SCEV *Op : Numerator->operands()) {
928 // Bail out if types do not match.
929 if (Ty != Op->getType())
930 return cannotDivide(Numerator);
931
932 if (FoundDenominatorTerm) {
933 Qs.push_back(Op);
934 continue;
935 }
936
937 // Check whether Denominator divides one of the product operands.
938 const SCEV *Q, *R;
939 divide(SE, Op, Denominator, &Q, &R);
940 if (!R->isZero()) {
941 Qs.push_back(Op);
942 continue;
943 }
944
945 // Bail out if types do not match.
946 if (Ty != Q->getType())
947 return cannotDivide(Numerator);
948
949 FoundDenominatorTerm = true;
950 Qs.push_back(Q);
951 }
952
953 if (FoundDenominatorTerm) {
954 Remainder = Zero;
955 if (Qs.size() == 1)
956 Quotient = Qs[0];
957 else
958 Quotient = SE.getMulExpr(Qs);
959 return;
960 }
961
962 if (!isa<SCEVUnknown>(Denominator))
963 return cannotDivide(Numerator);
964
965 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
966 ValueToValueMap RewriteMap;
967 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
968 cast<SCEVConstant>(Zero)->getValue();
969 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
970
971 if (Remainder->isZero()) {
972 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
973 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
974 cast<SCEVConstant>(One)->getValue();
975 Quotient =
976 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
977 return;
978 }
979
980 // Quotient is (Numerator - Remainder) divided by Denominator.
981 const SCEV *Q, *R;
982 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
983 // This SCEV does not seem to simplify: fail the division here.
984 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
985 return cannotDivide(Numerator);
986 divide(SE, Diff, Denominator, &Q, &R);
987 if (R != Zero)
988 return cannotDivide(Numerator);
989 Quotient = Q;
990 }
991
992private:
993 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
994 const SCEV *Denominator)
995 : SE(S), Denominator(Denominator) {
996 Zero = SE.getZero(Denominator->getType());
997 One = SE.getOne(Denominator->getType());
998
999 // We generally do not know how to divide Expr by Denominator. We
1000 // initialize the division to a "cannot divide" state to simplify the rest
1001 // of the code.
1002 cannotDivide(Numerator);
1003 }
1004
1005 // Convenience function for giving up on the division. We set the quotient to
1006 // be equal to zero and the remainder to be equal to the numerator.
1007 void cannotDivide(const SCEV *Numerator) {
1008 Quotient = Zero;
1009 Remainder = Numerator;
1010 }
1011
1012 ScalarEvolution &SE;
1013 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1014};
1015
1016}
1017
1018//===----------------------------------------------------------------------===//
1019// Simple SCEV method implementations
1020//===----------------------------------------------------------------------===//
1021
1022/// Compute BC(It, K). The result has width W. Assume, K > 0.
1023static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1024 ScalarEvolution &SE,
1025 Type *ResultTy) {
1026 // Handle the simplest case efficiently.
1027 if (K == 1)
1028 return SE.getTruncateOrZeroExtend(It, ResultTy);
1029
1030 // We are using the following formula for BC(It, K):
1031 //
1032 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1033 //
1034 // Suppose, W is the bitwidth of the return value. We must be prepared for
1035 // overflow. Hence, we must assure that the result of our computation is
1036 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1037 // safe in modular arithmetic.
1038 //
1039 // However, this code doesn't use exactly that formula; the formula it uses
1040 // is something like the following, where T is the number of factors of 2 in
1041 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1042 // exponentiation:
1043 //
1044 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1045 //
1046 // This formula is trivially equivalent to the previous formula. However,
1047 // this formula can be implemented much more efficiently. The trick is that
1048 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1049 // arithmetic. To do exact division in modular arithmetic, all we have
1050 // to do is multiply by the inverse. Therefore, this step can be done at
1051 // width W.
1052 //
1053 // The next issue is how to safely do the division by 2^T. The way this
1054 // is done is by doing the multiplication step at a width of at least W + T
1055 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1056 // when we perform the division by 2^T (which is equivalent to a right shift
1057 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1058 // truncated out after the division by 2^T.
1059 //
1060 // In comparison to just directly using the first formula, this technique
1061 // is much more efficient; using the first formula requires W * K bits,
1062 // but this formula less than W + K bits. Also, the first formula requires
1063 // a division step, whereas this formula only requires multiplies and shifts.
1064 //
1065 // It doesn't matter whether the subtraction step is done in the calculation
1066 // width or the input iteration count's width; if the subtraction overflows,
1067 // the result must be zero anyway. We prefer here to do it in the width of
1068 // the induction variable because it helps a lot for certain cases; CodeGen
1069 // isn't smart enough to ignore the overflow, which leads to much less
1070 // efficient code if the width of the subtraction is wider than the native
1071 // register width.
1072 //
1073 // (It's possible to not widen at all by pulling out factors of 2 before
1074 // the multiplication; for example, K=2 can be calculated as
1075 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1076 // extra arithmetic, so it's not an obvious win, and it gets
1077 // much more complicated for K > 3.)
1078
1079 // Protection from insane SCEVs; this bound is conservative,
1080 // but it probably doesn't matter.
1081 if (K > 1000)
1082 return SE.getCouldNotCompute();
1083
1084 unsigned W = SE.getTypeSizeInBits(ResultTy);
1085
1086 // Calculate K! / 2^T and T; we divide out the factors of two before
1087 // multiplying for calculating K! / 2^T to avoid overflow.
1088 // Other overflow doesn't matter because we only care about the bottom
1089 // W bits of the result.
1090 APInt OddFactorial(W, 1);
1091 unsigned T = 1;
1092 for (unsigned i = 3; i <= K; ++i) {
1093 APInt Mult(W, i);
1094 unsigned TwoFactors = Mult.countTrailingZeros();
1095 T += TwoFactors;
1096 Mult.lshrInPlace(TwoFactors);
1097 OddFactorial *= Mult;
1098 }
1099
1100 // We need at least W + T bits for the multiplication step
1101 unsigned CalculationBits = W + T;
1102
1103 // Calculate 2^T, at width T+W.
1104 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1105
1106 // Calculate the multiplicative inverse of K! / 2^T;
1107 // this multiplication factor will perform the exact division by
1108 // K! / 2^T.
1109 APInt Mod = APInt::getSignedMinValue(W+1);
1110 APInt MultiplyFactor = OddFactorial.zext(W+1);
1111 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1112 MultiplyFactor = MultiplyFactor.trunc(W);
1113
1114 // Calculate the product, at width T+W
1115 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1116 CalculationBits);
1117 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1118 for (unsigned i = 1; i != K; ++i) {
1119 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1120 Dividend = SE.getMulExpr(Dividend,
1121 SE.getTruncateOrZeroExtend(S, CalculationTy));
1122 }
1123
1124 // Divide by 2^T
1125 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1126
1127 // Truncate the result, and divide by K! / 2^T.
1128
1129 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1130 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1131}
1132
1133/// Return the value of this chain of recurrences at the specified iteration
1134/// number. We can evaluate this recurrence by multiplying each element in the
1135/// chain by the binomial coefficient corresponding to it. In other words, we
1136/// can evaluate {A,+,B,+,C,+,D} as:
1137///
1138/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1139///
1140/// where BC(It, k) stands for binomial coefficient.
1141///
1142const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1143 ScalarEvolution &SE) const {
1144 const SCEV *Result = getStart();
1145 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1146 // The computation is correct in the face of overflow provided that the
1147 // multiplication is performed _after_ the evaluation of the binomial
1148 // coefficient.
1149 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1150 if (isa<SCEVCouldNotCompute>(Coeff))
1151 return Coeff;
1152
1153 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1154 }
1155 return Result;
1156}
1157
1158//===----------------------------------------------------------------------===//
1159// SCEV Expression folder implementations
1160//===----------------------------------------------------------------------===//
1161
1162const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1163 Type *Ty) {
1164 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1165, __PRETTY_FUNCTION__))
1165 "This is not a truncating conversion!")((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1165, __PRETTY_FUNCTION__))
;
1166 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1167, __PRETTY_FUNCTION__))
1167 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1167, __PRETTY_FUNCTION__))
;
1168 Ty = getEffectiveSCEVType(Ty);
1169
1170 FoldingSetNodeID ID;
1171 ID.AddInteger(scTruncate);
1172 ID.AddPointer(Op);
1173 ID.AddPointer(Ty);
1174 void *IP = nullptr;
1175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1176
1177 // Fold if the operand is constant.
1178 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1179 return getConstant(
1180 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1181
1182 // trunc(trunc(x)) --> trunc(x)
1183 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1184 return getTruncateExpr(ST->getOperand(), Ty);
1185
1186 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1187 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1188 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1189
1190 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1191 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1192 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1193
1194 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1195 // eliminate all the truncates, or we replace other casts with truncates.
1196 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1197 SmallVector<const SCEV *, 4> Operands;
1198 bool hasTrunc = false;
1199 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1200 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1201 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1202 hasTrunc = isa<SCEVTruncateExpr>(S);
1203 Operands.push_back(S);
1204 }
1205 if (!hasTrunc)
1206 return getAddExpr(Operands);
1207 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1208 }
1209
1210 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1211 // eliminate all the truncates, or we replace other casts with truncates.
1212 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1213 SmallVector<const SCEV *, 4> Operands;
1214 bool hasTrunc = false;
1215 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1216 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1217 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1218 hasTrunc = isa<SCEVTruncateExpr>(S);
1219 Operands.push_back(S);
1220 }
1221 if (!hasTrunc)
1222 return getMulExpr(Operands);
1223 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1224 }
1225
1226 // If the input value is a chrec scev, truncate the chrec's operands.
1227 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1228 SmallVector<const SCEV *, 4> Operands;
1229 for (const SCEV *Op : AddRec->operands())
1230 Operands.push_back(getTruncateExpr(Op, Ty));
1231 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1232 }
1233
1234 // The cast wasn't folded; create an explicit cast node. We can reuse
1235 // the existing insert position since if we get here, we won't have
1236 // made any changes which would invalidate it.
1237 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1238 Op, Ty);
1239 UniqueSCEVs.InsertNode(S, IP);
1240 return S;
1241}
1242
1243// Get the limit of a recurrence such that incrementing by Step cannot cause
1244// signed overflow as long as the value of the recurrence within the
1245// loop does not exceed this limit before incrementing.
1246static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1247 ICmpInst::Predicate *Pred,
1248 ScalarEvolution *SE) {
1249 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1250 if (SE->isKnownPositive(Step)) {
1251 *Pred = ICmpInst::ICMP_SLT;
1252 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1253 SE->getSignedRange(Step).getSignedMax());
1254 }
1255 if (SE->isKnownNegative(Step)) {
1256 *Pred = ICmpInst::ICMP_SGT;
1257 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1258 SE->getSignedRange(Step).getSignedMin());
1259 }
1260 return nullptr;
1261}
1262
1263// Get the limit of a recurrence such that incrementing by Step cannot cause
1264// unsigned overflow as long as the value of the recurrence within the loop does
1265// not exceed this limit before incrementing.
1266static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1267 ICmpInst::Predicate *Pred,
1268 ScalarEvolution *SE) {
1269 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1270 *Pred = ICmpInst::ICMP_ULT;
1271
1272 return SE->getConstant(APInt::getMinValue(BitWidth) -
1273 SE->getUnsignedRange(Step).getUnsignedMax());
1274}
1275
1276namespace {
1277
1278struct ExtendOpTraitsBase {
1279 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1280 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1281};
1282
1283// Used to make code generic over signed and unsigned overflow.
1284template <typename ExtendOp> struct ExtendOpTraits {
1285 // Members present:
1286 //
1287 // static const SCEV::NoWrapFlags WrapType;
1288 //
1289 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1290 //
1291 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1292 // ICmpInst::Predicate *Pred,
1293 // ScalarEvolution *SE);
1294};
1295
1296template <>
1297struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1298 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1299
1300 static const GetExtendExprTy GetExtendExpr;
1301
1302 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303 ICmpInst::Predicate *Pred,
1304 ScalarEvolution *SE) {
1305 return getSignedOverflowLimitForStep(Step, Pred, SE);
1306 }
1307};
1308
1309const ExtendOpTraitsBase::GetExtendExprTy
1310 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1311 &ScalarEvolution::getSignExtendExprCached;
1312
1313template <>
1314struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1315 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1316
1317 static const GetExtendExprTy GetExtendExpr;
1318
1319 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1320 ICmpInst::Predicate *Pred,
1321 ScalarEvolution *SE) {
1322 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1323 }
1324};
1325
1326const ExtendOpTraitsBase::GetExtendExprTy
1327 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1328 &ScalarEvolution::getZeroExtendExprCached;
1329}
1330
1331// The recurrence AR has been shown to have no signed/unsigned wrap or something
1332// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1333// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1334// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1335// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1336// expression "Step + sext/zext(PreIncAR)" is congruent with
1337// "sext/zext(PostIncAR)"
1338template <typename ExtendOpTy>
1339static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1340 ScalarEvolution *SE,
1341 ScalarEvolution::ExtendCacheTy &Cache) {
1342 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1343 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1344
1345 const Loop *L = AR->getLoop();
1346 const SCEV *Start = AR->getStart();
1347 const SCEV *Step = AR->getStepRecurrence(*SE);
1348
1349 // Check for a simple looking step prior to loop entry.
1350 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1351 if (!SA)
1352 return nullptr;
1353
1354 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1355 // subtraction is expensive. For this purpose, perform a quick and dirty
1356 // difference, by checking for Step in the operand list.
1357 SmallVector<const SCEV *, 4> DiffOps;
1358 for (const SCEV *Op : SA->operands())
1359 if (Op != Step)
1360 DiffOps.push_back(Op);
1361
1362 if (DiffOps.size() == SA->getNumOperands())
1363 return nullptr;
1364
1365 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1366 // `Step`:
1367
1368 // 1. NSW/NUW flags on the step increment.
1369 auto PreStartFlags =
1370 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1371 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1372 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1373 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1374
1375 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1376 // "S+X does not sign/unsign-overflow".
1377 //
1378
1379 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1380 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1381 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1382 return PreStart;
1383
1384 // 2. Direct overflow check on the step operation's expression.
1385 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1386 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1387 const SCEV *OperandExtendedStart =
1388 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1389 (SE->*GetExtendExpr)(Step, WideTy, Cache));
1390 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1391 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1392 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1393 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1394 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1395 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1396 }
1397 return PreStart;
1398 }
1399
1400 // 3. Loop precondition.
1401 ICmpInst::Predicate Pred;
1402 const SCEV *OverflowLimit =
1403 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1404
1405 if (OverflowLimit &&
1406 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1407 return PreStart;
1408
1409 return nullptr;
1410}
1411
1412// Get the normalized zero or sign extended expression for this AddRec's Start.
1413template <typename ExtendOpTy>
1414static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1415 ScalarEvolution *SE,
1416 ScalarEvolution::ExtendCacheTy &Cache) {
1417 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1418
1419 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1420 if (!PreStart)
1421 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1422
1423 return SE->getAddExpr(
1424 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1425 (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1426}
1427
1428// Try to prove away overflow by looking at "nearby" add recurrences. A
1429// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1430// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1431//
1432// Formally:
1433//
1434// {S,+,X} == {S-T,+,X} + T
1435// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1436//
1437// If ({S-T,+,X} + T) does not overflow ... (1)
1438//
1439// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1440//
1441// If {S-T,+,X} does not overflow ... (2)
1442//
1443// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1444// == {Ext(S-T)+Ext(T),+,Ext(X)}
1445//
1446// If (S-T)+T does not overflow ... (3)
1447//
1448// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1449// == {Ext(S),+,Ext(X)} == LHS
1450//
1451// Thus, if (1), (2) and (3) are true for some T, then
1452// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1453//
1454// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1455// does not overflow" restricted to the 0th iteration. Therefore we only need
1456// to check for (1) and (2).
1457//
1458// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1459// is `Delta` (defined below).
1460//
1461template <typename ExtendOpTy>
1462bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1463 const SCEV *Step,
1464 const Loop *L) {
1465 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1466
1467 // We restrict `Start` to a constant to prevent SCEV from spending too much
1468 // time here. It is correct (but more expensive) to continue with a
1469 // non-constant `Start` and do a general SCEV subtraction to compute
1470 // `PreStart` below.
1471 //
1472 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1473 if (!StartC)
1474 return false;
1475
1476 APInt StartAI = StartC->getAPInt();
1477
1478 for (unsigned Delta : {-2, -1, 1, 2}) {
1479 const SCEV *PreStart = getConstant(StartAI - Delta);
1480
1481 FoldingSetNodeID ID;
1482 ID.AddInteger(scAddRecExpr);
1483 ID.AddPointer(PreStart);
1484 ID.AddPointer(Step);
1485 ID.AddPointer(L);
1486 void *IP = nullptr;
1487 const auto *PreAR =
1488 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1489
1490 // Give up if we don't already have the add recurrence we need because
1491 // actually constructing an add recurrence is relatively expensive.
1492 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1493 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1494 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1495 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1496 DeltaS, &Pred, this);
1497 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1498 return true;
1499 }
1500 }
1501
1502 return false;
1503}
1504
1505const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1506 // Use the local cache to prevent exponential behavior of
1507 // getZeroExtendExprImpl.
1508 ExtendCacheTy Cache;
1509 return getZeroExtendExprCached(Op, Ty, Cache);
1510}
1511
1512/// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1513/// related entry in the \p Cache, call getZeroExtendExprImpl and save
1514/// the result in the \p Cache.
1515const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1516 ExtendCacheTy &Cache) {
1517 auto It = Cache.find({Op, Ty});
1518 if (It != Cache.end())
1519 return It->second;
1520 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1521 auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1522 assert(InsertResult.second && "Expect the key was not in the cache")((InsertResult.second && "Expect the key was not in the cache"
) ? static_cast<void> (0) : __assert_fail ("InsertResult.second && \"Expect the key was not in the cache\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1522, __PRETTY_FUNCTION__))
;
1523 (void)InsertResult;
1524 return ZExt;
1525}
1526
1527/// The real implementation of getZeroExtendExpr.
1528const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1529 ExtendCacheTy &Cache) {
1530 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1531, __PRETTY_FUNCTION__))
1531 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1531, __PRETTY_FUNCTION__))
;
1532 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1533, __PRETTY_FUNCTION__))
1533 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1533, __PRETTY_FUNCTION__))
;
1534 Ty = getEffectiveSCEVType(Ty);
1535
1536 // Fold if the operand is constant.
1537 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1538 return getConstant(
1539 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1540
1541 // zext(zext(x)) --> zext(x)
1542 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1543 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1544
1545 // Before doing any expensive analysis, check to see if we've already
1546 // computed a SCEV for this Op and Ty.
1547 FoldingSetNodeID ID;
1548 ID.AddInteger(scZeroExtend);
1549 ID.AddPointer(Op);
1550 ID.AddPointer(Ty);
1551 void *IP = nullptr;
1552 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1553
1554 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1555 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1556 // It's possible the bits taken off by the truncate were all zero bits. If
1557 // so, we should be able to simplify this further.
1558 const SCEV *X = ST->getOperand();
1559 ConstantRange CR = getUnsignedRange(X);
1560 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1561 unsigned NewBits = getTypeSizeInBits(Ty);
1562 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1563 CR.zextOrTrunc(NewBits)))
1564 return getTruncateOrZeroExtend(X, Ty);
1565 }
1566
1567 // If the input value is a chrec scev, and we can prove that the value
1568 // did not overflow the old, smaller, value, we can zero extend all of the
1569 // operands (often constants). This allows analysis of something like
1570 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1571 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1572 if (AR->isAffine()) {
1573 const SCEV *Start = AR->getStart();
1574 const SCEV *Step = AR->getStepRecurrence(*this);
1575 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1576 const Loop *L = AR->getLoop();
1577
1578 if (!AR->hasNoUnsignedWrap()) {
1579 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1580 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1581 }
1582
1583 // If we have special knowledge that this addrec won't overflow,
1584 // we don't need to do any further analysis.
1585 if (AR->hasNoUnsignedWrap())
1586 return getAddRecExpr(
1587 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1588 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1589
1590 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1591 // Note that this serves two purposes: It filters out loops that are
1592 // simply not analyzable, and it covers the case where this code is
1593 // being called from within backedge-taken count analysis, such that
1594 // attempting to ask for the backedge-taken count would likely result
1595 // in infinite recursion. In the later case, the analysis code will
1596 // cope with a conservative value, and it will take care to purge
1597 // that value once it has finished.
1598 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1599 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1600 // Manually compute the final value for AR, checking for
1601 // overflow.
1602
1603 // Check whether the backedge-taken count can be losslessly casted to
1604 // the addrec's type. The count is always unsigned.
1605 const SCEV *CastedMaxBECount =
1606 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1607 const SCEV *RecastedMaxBECount =
1608 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1609 if (MaxBECount == RecastedMaxBECount) {
1610 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1611 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1612 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1613 const SCEV *ZAdd =
1614 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1615 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1616 const SCEV *WideMaxBECount =
1617 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1618 const SCEV *OperandExtendedAdd = getAddExpr(
1619 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1620 Step, WideTy, Cache)));
1621 if (ZAdd == OperandExtendedAdd) {
1622 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1623 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1624 // Return the expression with the addrec on the outside.
1625 return getAddRecExpr(
1626 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1627 getZeroExtendExprCached(Step, Ty, Cache), L,
1628 AR->getNoWrapFlags());
1629 }
1630 // Similar to above, only this time treat the step value as signed.
1631 // This covers loops that count down.
1632 OperandExtendedAdd =
1633 getAddExpr(WideStart,
1634 getMulExpr(WideMaxBECount,
1635 getSignExtendExpr(Step, WideTy)));
1636 if (ZAdd == OperandExtendedAdd) {
1637 // Cache knowledge of AR NW, which is propagated to this AddRec.
1638 // Negative step causes unsigned wrap, but it still can't self-wrap.
1639 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1640 // Return the expression with the addrec on the outside.
1641 return getAddRecExpr(
1642 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1643 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1644 }
1645 }
1646 }
1647
1648 // Normally, in the cases we can prove no-overflow via a
1649 // backedge guarding condition, we can also compute a backedge
1650 // taken count for the loop. The exceptions are assumptions and
1651 // guards present in the loop -- SCEV is not great at exploiting
1652 // these to compute max backedge taken counts, but can still use
1653 // these to prove lack of overflow. Use this fact to avoid
1654 // doing extra work that may not pay off.
1655 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1656 !AC.assumptions().empty()) {
1657 // If the backedge is guarded by a comparison with the pre-inc
1658 // value the addrec is safe. Also, if the entry is guarded by
1659 // a comparison with the start value and the backedge is
1660 // guarded by a comparison with the post-inc value, the addrec
1661 // is safe.
1662 if (isKnownPositive(Step)) {
1663 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1664 getUnsignedRange(Step).getUnsignedMax());
1665 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1666 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1667 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1668 AR->getPostIncExpr(*this), N))) {
1669 // Cache knowledge of AR NUW, which is propagated to this
1670 // AddRec.
1671 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1672 // Return the expression with the addrec on the outside.
1673 return getAddRecExpr(
1674 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1675 getZeroExtendExprCached(Step, Ty, Cache), L,
1676 AR->getNoWrapFlags());
1677 }
1678 } else if (isKnownNegative(Step)) {
1679 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1680 getSignedRange(Step).getSignedMin());
1681 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1682 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1683 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1684 AR->getPostIncExpr(*this), N))) {
1685 // Cache knowledge of AR NW, which is propagated to this
1686 // AddRec. Negative step causes unsigned wrap, but it
1687 // still can't self-wrap.
1688 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1689 // Return the expression with the addrec on the outside.
1690 return getAddRecExpr(
1691 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1692 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1693 }
1694 }
1695 }
1696
1697 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1698 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1699 return getAddRecExpr(
1700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1701 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1702 }
1703 }
1704
1705 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1706 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1707 if (SA->hasNoUnsignedWrap()) {
1708 // If the addition does not unsign overflow then we can, by definition,
1709 // commute the zero extension with the addition operation.
1710 SmallVector<const SCEV *, 4> Ops;
1711 for (const auto *Op : SA->operands())
1712 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1713 return getAddExpr(Ops, SCEV::FlagNUW);
1714 }
1715 }
1716
1717 // The cast wasn't folded; create an explicit cast node.
1718 // Recompute the insert position, as it may have been invalidated.
1719 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1720 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1721 Op, Ty);
1722 UniqueSCEVs.InsertNode(S, IP);
1723 return S;
1724}
1725
1726const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1727 // Use the local cache to prevent exponential behavior of
1728 // getSignExtendExprImpl.
1729 ExtendCacheTy Cache;
1730 return getSignExtendExprCached(Op, Ty, Cache);
1731}
1732
1733/// Query \p Cache before calling getSignExtendExprImpl. If there is no
1734/// related entry in the \p Cache, call getSignExtendExprImpl and save
1735/// the result in the \p Cache.
1736const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1737 ExtendCacheTy &Cache) {
1738 auto It = Cache.find({Op, Ty});
1739 if (It != Cache.end())
1740 return It->second;
1741 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1742 auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1743 assert(InsertResult.second && "Expect the key was not in the cache")((InsertResult.second && "Expect the key was not in the cache"
) ? static_cast<void> (0) : __assert_fail ("InsertResult.second && \"Expect the key was not in the cache\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1743, __PRETTY_FUNCTION__))
;
1744 (void)InsertResult;
1745 return SExt;
1746}
1747
1748/// The real implementation of getSignExtendExpr.
1749const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1750 ExtendCacheTy &Cache) {
1751 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1752, __PRETTY_FUNCTION__))
1752 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1752, __PRETTY_FUNCTION__))
;
1753 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1754, __PRETTY_FUNCTION__))
1754 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1754, __PRETTY_FUNCTION__))
;
1755 Ty = getEffectiveSCEVType(Ty);
1756
1757 // Fold if the operand is constant.
1758 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1759 return getConstant(
1760 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1761
1762 // sext(sext(x)) --> sext(x)
1763 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1764 return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1765
1766 // sext(zext(x)) --> zext(x)
1767 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1768 return getZeroExtendExpr(SZ->getOperand(), Ty);
1769
1770 // Before doing any expensive analysis, check to see if we've already
1771 // computed a SCEV for this Op and Ty.
1772 FoldingSetNodeID ID;
1773 ID.AddInteger(scSignExtend);
1774 ID.AddPointer(Op);
1775 ID.AddPointer(Ty);
1776 void *IP = nullptr;
1777 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1778
1779 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1780 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1781 // It's possible the bits taken off by the truncate were all sign bits. If
1782 // so, we should be able to simplify this further.
1783 const SCEV *X = ST->getOperand();
1784 ConstantRange CR = getSignedRange(X);
1785 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1786 unsigned NewBits = getTypeSizeInBits(Ty);
1787 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1788 CR.sextOrTrunc(NewBits)))
1789 return getTruncateOrSignExtend(X, Ty);
1790 }
1791
1792 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1793 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1794 if (SA->getNumOperands() == 2) {
1795 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1796 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1797 if (SMul && SC1) {
1798 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1799 const APInt &C1 = SC1->getAPInt();
1800 const APInt &C2 = SC2->getAPInt();
1801 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1802 C2.ugt(C1) && C2.isPowerOf2())
1803 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1804 getSignExtendExprCached(SMul, Ty, Cache));
1805 }
1806 }
1807 }
1808
1809 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1810 if (SA->hasNoSignedWrap()) {
1811 // If the addition does not sign overflow then we can, by definition,
1812 // commute the sign extension with the addition operation.
1813 SmallVector<const SCEV *, 4> Ops;
1814 for (const auto *Op : SA->operands())
1815 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1816 return getAddExpr(Ops, SCEV::FlagNSW);
1817 }
1818 }
1819 // If the input value is a chrec scev, and we can prove that the value
1820 // did not overflow the old, smaller, value, we can sign extend all of the
1821 // operands (often constants). This allows analysis of something like
1822 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1823 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1824 if (AR->isAffine()) {
1825 const SCEV *Start = AR->getStart();
1826 const SCEV *Step = AR->getStepRecurrence(*this);
1827 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1828 const Loop *L = AR->getLoop();
1829
1830 if (!AR->hasNoSignedWrap()) {
1831 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1832 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1833 }
1834
1835 // If we have special knowledge that this addrec won't overflow,
1836 // we don't need to do any further analysis.
1837 if (AR->hasNoSignedWrap())
1838 return getAddRecExpr(
1839 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1840 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1841
1842 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1843 // Note that this serves two purposes: It filters out loops that are
1844 // simply not analyzable, and it covers the case where this code is
1845 // being called from within backedge-taken count analysis, such that
1846 // attempting to ask for the backedge-taken count would likely result
1847 // in infinite recursion. In the later case, the analysis code will
1848 // cope with a conservative value, and it will take care to purge
1849 // that value once it has finished.
1850 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1851 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1852 // Manually compute the final value for AR, checking for
1853 // overflow.
1854
1855 // Check whether the backedge-taken count can be losslessly casted to
1856 // the addrec's type. The count is always unsigned.
1857 const SCEV *CastedMaxBECount =
1858 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1859 const SCEV *RecastedMaxBECount =
1860 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1861 if (MaxBECount == RecastedMaxBECount) {
1862 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1863 // Check whether Start+Step*MaxBECount has no signed overflow.
1864 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1865 const SCEV *SAdd =
1866 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1867 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1868 const SCEV *WideMaxBECount =
1869 getZeroExtendExpr(CastedMaxBECount, WideTy);
1870 const SCEV *OperandExtendedAdd = getAddExpr(
1871 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1872 Step, WideTy, Cache)));
1873 if (SAdd == OperandExtendedAdd) {
1874 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1875 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1876 // Return the expression with the addrec on the outside.
1877 return getAddRecExpr(
1878 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1879 getSignExtendExprCached(Step, Ty, Cache), L,
1880 AR->getNoWrapFlags());
1881 }
1882 // Similar to above, only this time treat the step value as unsigned.
1883 // This covers loops that count up with an unsigned step.
1884 OperandExtendedAdd =
1885 getAddExpr(WideStart,
1886 getMulExpr(WideMaxBECount,
1887 getZeroExtendExpr(Step, WideTy)));
1888 if (SAdd == OperandExtendedAdd) {
1889 // If AR wraps around then
1890 //
1891 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1892 // => SAdd != OperandExtendedAdd
1893 //
1894 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1895 // (SAdd == OperandExtendedAdd => AR is NW)
1896
1897 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1898
1899 // Return the expression with the addrec on the outside.
1900 return getAddRecExpr(
1901 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1902 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1903 }
1904 }
1905 }
1906
1907 // Normally, in the cases we can prove no-overflow via a
1908 // backedge guarding condition, we can also compute a backedge
1909 // taken count for the loop. The exceptions are assumptions and
1910 // guards present in the loop -- SCEV is not great at exploiting
1911 // these to compute max backedge taken counts, but can still use
1912 // these to prove lack of overflow. Use this fact to avoid
1913 // doing extra work that may not pay off.
1914
1915 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1916 !AC.assumptions().empty()) {
1917 // If the backedge is guarded by a comparison with the pre-inc
1918 // value the addrec is safe. Also, if the entry is guarded by
1919 // a comparison with the start value and the backedge is
1920 // guarded by a comparison with the post-inc value, the addrec
1921 // is safe.
1922 ICmpInst::Predicate Pred;
1923 const SCEV *OverflowLimit =
1924 getSignedOverflowLimitForStep(Step, &Pred, this);
1925 if (OverflowLimit &&
1926 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1927 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1928 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1929 OverflowLimit)))) {
1930 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1931 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1932 return getAddRecExpr(
1933 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1934 getSignExtendExprCached(Step, Ty, Cache), L,
1935 AR->getNoWrapFlags());
1936 }
1937 }
1938
1939 // If Start and Step are constants, check if we can apply this
1940 // transformation:
1941 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1942 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1943 auto *SC2 = dyn_cast<SCEVConstant>(Step);
1944 if (SC1 && SC2) {
1945 const APInt &C1 = SC1->getAPInt();
1946 const APInt &C2 = SC2->getAPInt();
1947 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1948 C2.isPowerOf2()) {
1949 Start = getSignExtendExprCached(Start, Ty, Cache);
1950 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1951 AR->getNoWrapFlags());
1952 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1953 }
1954 }
1955
1956 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1957 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1958 return getAddRecExpr(
1959 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1960 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1961 }
1962 }
1963
1964 // If the input value is provably positive and we could not simplify
1965 // away the sext build a zext instead.
1966 if (isKnownNonNegative(Op))
1967 return getZeroExtendExpr(Op, Ty);
1968
1969 // The cast wasn't folded; create an explicit cast node.
1970 // Recompute the insert position, as it may have been invalidated.
1971 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1972 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1973 Op, Ty);
1974 UniqueSCEVs.InsertNode(S, IP);
1975 return S;
1976}
1977
1978/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1979/// unspecified bits out to the given type.
1980///
1981const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1982 Type *Ty) {
1983 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1984, __PRETTY_FUNCTION__))
1984 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1984, __PRETTY_FUNCTION__))
;
1985 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1986, __PRETTY_FUNCTION__))
1986 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 1986, __PRETTY_FUNCTION__))
;
1987 Ty = getEffectiveSCEVType(Ty);
1988
1989 // Sign-extend negative constants.
1990 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1991 if (SC->getAPInt().isNegative())
1992 return getSignExtendExpr(Op, Ty);
1993
1994 // Peel off a truncate cast.
1995 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1996 const SCEV *NewOp = T->getOperand();
1997 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1998 return getAnyExtendExpr(NewOp, Ty);
1999 return getTruncateOrNoop(NewOp, Ty);
2000 }
2001
2002 // Next try a zext cast. If the cast is folded, use it.
2003 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2004 if (!isa<SCEVZeroExtendExpr>(ZExt))
2005 return ZExt;
2006
2007 // Next try a sext cast. If the cast is folded, use it.
2008 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2009 if (!isa<SCEVSignExtendExpr>(SExt))
2010 return SExt;
2011
2012 // Force the cast to be folded into the operands of an addrec.
2013 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2014 SmallVector<const SCEV *, 4> Ops;
2015 for (const SCEV *Op : AR->operands())
2016 Ops.push_back(getAnyExtendExpr(Op, Ty));
2017 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2018 }
2019
2020 // If the expression is obviously signed, use the sext cast value.
2021 if (isa<SCEVSMaxExpr>(Op))
2022 return SExt;
2023
2024 // Absent any other information, use the zext cast value.
2025 return ZExt;
2026}
2027
2028/// Process the given Ops list, which is a list of operands to be added under
2029/// the given scale, update the given map. This is a helper function for
2030/// getAddRecExpr. As an example of what it does, given a sequence of operands
2031/// that would form an add expression like this:
2032///
2033/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2034///
2035/// where A and B are constants, update the map with these values:
2036///
2037/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2038///
2039/// and add 13 + A*B*29 to AccumulatedConstant.
2040/// This will allow getAddRecExpr to produce this:
2041///
2042/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2043///
2044/// This form often exposes folding opportunities that are hidden in
2045/// the original operand list.
2046///
2047/// Return true iff it appears that any interesting folding opportunities
2048/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2049/// the common case where no interesting opportunities are present, and
2050/// is also used as a check to avoid infinite recursion.
2051///
2052static bool
2053CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2054 SmallVectorImpl<const SCEV *> &NewOps,
2055 APInt &AccumulatedConstant,
2056 const SCEV *const *Ops, size_t NumOperands,
2057 const APInt &Scale,
2058 ScalarEvolution &SE) {
2059 bool Interesting = false;
2060
2061 // Iterate over the add operands. They are sorted, with constants first.
2062 unsigned i = 0;
2063 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2064 ++i;
2065 // Pull a buried constant out to the outside.
2066 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2067 Interesting = true;
2068 AccumulatedConstant += Scale * C->getAPInt();
2069 }
2070
2071 // Next comes everything else. We're especially interested in multiplies
2072 // here, but they're in the middle, so just visit the rest with one loop.
2073 for (; i != NumOperands; ++i) {
2074 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2075 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2076 APInt NewScale =
2077 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2078 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2079 // A multiplication of a constant with another add; recurse.
2080 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2081 Interesting |=
2082 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2083 Add->op_begin(), Add->getNumOperands(),
2084 NewScale, SE);
2085 } else {
2086 // A multiplication of a constant with some other value. Update
2087 // the map.
2088 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2089 const SCEV *Key = SE.getMulExpr(MulOps);
2090 auto Pair = M.insert({Key, NewScale});
2091 if (Pair.second) {
2092 NewOps.push_back(Pair.first->first);
2093 } else {
2094 Pair.first->second += NewScale;
2095 // The map already had an entry for this value, which may indicate
2096 // a folding opportunity.
2097 Interesting = true;
2098 }
2099 }
2100 } else {
2101 // An ordinary operand. Update the map.
2102 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2103 M.insert({Ops[i], Scale});
2104 if (Pair.second) {
2105 NewOps.push_back(Pair.first->first);
2106 } else {
2107 Pair.first->second += Scale;
2108 // The map already had an entry for this value, which may indicate
2109 // a folding opportunity.
2110 Interesting = true;
2111 }
2112 }
2113 }
2114
2115 return Interesting;
2116}
2117
2118// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2119// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2120// can't-overflow flags for the operation if possible.
2121static SCEV::NoWrapFlags
2122StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2123 const SmallVectorImpl<const SCEV *> &Ops,
2124 SCEV::NoWrapFlags Flags) {
2125 using namespace std::placeholders;
2126 typedef OverflowingBinaryOperator OBO;
2127
2128 bool CanAnalyze =
2129 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2130 (void)CanAnalyze;
2131 assert(CanAnalyze && "don't call from other places!")((CanAnalyze && "don't call from other places!") ? static_cast
<void> (0) : __assert_fail ("CanAnalyze && \"don't call from other places!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2131, __PRETTY_FUNCTION__))
;
2132
2133 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2134 SCEV::NoWrapFlags SignOrUnsignWrap =
2135 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2136
2137 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2138 auto IsKnownNonNegative = [&](const SCEV *S) {
2139 return SE->isKnownNonNegative(S);
2140 };
2141
2142 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2143 Flags =
2144 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2145
2146 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2147
2148 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2149 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2150
2151 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2152 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2153
2154 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2155 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2156 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2157 Instruction::Add, C, OBO::NoSignedWrap);
2158 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2159 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2160 }
2161 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2162 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2163 Instruction::Add, C, OBO::NoUnsignedWrap);
2164 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2165 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2166 }
2167 }
2168
2169 return Flags;
2170}
2171
2172/// Get a canonical add expression, or something simpler if possible.
2173const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2174 SCEV::NoWrapFlags Flags,
2175 unsigned Depth) {
2176 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed"
) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2177, __PRETTY_FUNCTION__))
2177 "only nuw or nsw allowed")((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed"
) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2177, __PRETTY_FUNCTION__))
;
2178 assert(!Ops.empty() && "Cannot get empty add!")((!Ops.empty() && "Cannot get empty add!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty add!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2178, __PRETTY_FUNCTION__))
;
2179 if (Ops.size() == 1) return Ops[0];
2180#ifndef NDEBUG
2181 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2182 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2183 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2184, __PRETTY_FUNCTION__))
2184 "SCEVAddExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2184, __PRETTY_FUNCTION__))
;
2185#endif
2186
2187 // Sort by complexity, this groups all similar expression types together.
2188 GroupByComplexity(Ops, &LI);
2189
2190 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2191
2192 // If there are any constants, fold them together.
2193 unsigned Idx = 0;
2194 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2195 ++Idx;
2196 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2196, __PRETTY_FUNCTION__))
;
2197 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2198 // We found two constants, fold them together!
2199 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2200 if (Ops.size() == 2) return Ops[0];
2201 Ops.erase(Ops.begin()+1); // Erase the folded element
2202 LHSC = cast<SCEVConstant>(Ops[0]);
2203 }
2204
2205 // If we are left with a constant zero being added, strip it off.
2206 if (LHSC->getValue()->isZero()) {
2207 Ops.erase(Ops.begin());
2208 --Idx;
2209 }
2210
2211 if (Ops.size() == 1) return Ops[0];
2212 }
2213
2214 // Limit recursion calls depth
2215 if (Depth > MaxAddExprDepth)
2216 return getOrCreateAddExpr(Ops, Flags);
2217
2218 // Okay, check to see if the same value occurs in the operand list more than
2219 // once. If so, merge them together into an multiply expression. Since we
2220 // sorted the list, these values are required to be adjacent.
2221 Type *Ty = Ops[0]->getType();
2222 bool FoundMatch = false;
2223 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2224 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2225 // Scan ahead to count how many equal operands there are.
2226 unsigned Count = 2;
2227 while (i+Count != e && Ops[i+Count] == Ops[i])
2228 ++Count;
2229 // Merge the values into a multiply.
2230 const SCEV *Scale = getConstant(Ty, Count);
2231 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2232 if (Ops.size() == Count)
2233 return Mul;
2234 Ops[i] = Mul;
2235 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2236 --i; e -= Count - 1;
2237 FoundMatch = true;
2238 }
2239 if (FoundMatch)
2240 return getAddExpr(Ops, Flags);
2241
2242 // Check for truncates. If all the operands are truncated from the same
2243 // type, see if factoring out the truncate would permit the result to be
2244 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2245 // if the contents of the resulting outer trunc fold to something simple.
2246 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2247 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2248 Type *DstType = Trunc->getType();
2249 Type *SrcType = Trunc->getOperand()->getType();
2250 SmallVector<const SCEV *, 8> LargeOps;
2251 bool Ok = true;
2252 // Check all the operands to see if they can be represented in the
2253 // source type of the truncate.
2254 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2255 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2256 if (T->getOperand()->getType() != SrcType) {
2257 Ok = false;
2258 break;
2259 }
2260 LargeOps.push_back(T->getOperand());
2261 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2262 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2263 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2264 SmallVector<const SCEV *, 8> LargeMulOps;
2265 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2266 if (const SCEVTruncateExpr *T =
2267 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2268 if (T->getOperand()->getType() != SrcType) {
2269 Ok = false;
2270 break;
2271 }
2272 LargeMulOps.push_back(T->getOperand());
2273 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2274 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2275 } else {
2276 Ok = false;
2277 break;
2278 }
2279 }
2280 if (Ok)
2281 LargeOps.push_back(getMulExpr(LargeMulOps));
2282 } else {
2283 Ok = false;
2284 break;
2285 }
2286 }
2287 if (Ok) {
2288 // Evaluate the expression in the larger type.
2289 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2290 // If it folds to something simple, use it. Otherwise, don't.
2291 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2292 return getTruncateExpr(Fold, DstType);
2293 }
2294 }
2295
2296 // Skip past any other cast SCEVs.
2297 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2298 ++Idx;
2299
2300 // If there are add operands they would be next.
2301 if (Idx < Ops.size()) {
2302 bool DeletedAdd = false;
2303 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2304 if (Ops.size() > AddOpsInlineThreshold ||
2305 Add->getNumOperands() > AddOpsInlineThreshold)
2306 break;
2307 // If we have an add, expand the add operands onto the end of the operands
2308 // list.
2309 Ops.erase(Ops.begin()+Idx);
2310 Ops.append(Add->op_begin(), Add->op_end());
2311 DeletedAdd = true;
2312 }
2313
2314 // If we deleted at least one add, we added operands to the end of the list,
2315 // and they are not necessarily sorted. Recurse to resort and resimplify
2316 // any operands we just acquired.
2317 if (DeletedAdd)
2318 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2319 }
2320
2321 // Skip over the add expression until we get to a multiply.
2322 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2323 ++Idx;
2324
2325 // Check to see if there are any folding opportunities present with
2326 // operands multiplied by constant values.
2327 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2328 uint64_t BitWidth = getTypeSizeInBits(Ty);
2329 DenseMap<const SCEV *, APInt> M;
2330 SmallVector<const SCEV *, 8> NewOps;
2331 APInt AccumulatedConstant(BitWidth, 0);
2332 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2333 Ops.data(), Ops.size(),
2334 APInt(BitWidth, 1), *this)) {
2335 struct APIntCompare {
2336 bool operator()(const APInt &LHS, const APInt &RHS) const {
2337 return LHS.ult(RHS);
2338 }
2339 };
2340
2341 // Some interesting folding opportunity is present, so its worthwhile to
2342 // re-generate the operands list. Group the operands by constant scale,
2343 // to avoid multiplying by the same constant scale multiple times.
2344 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2345 for (const SCEV *NewOp : NewOps)
2346 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2347 // Re-generate the operands list.
2348 Ops.clear();
2349 if (AccumulatedConstant != 0)
2350 Ops.push_back(getConstant(AccumulatedConstant));
2351 for (auto &MulOp : MulOpLists)
2352 if (MulOp.first != 0)
2353 Ops.push_back(getMulExpr(
2354 getConstant(MulOp.first),
2355 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2356 if (Ops.empty())
2357 return getZero(Ty);
2358 if (Ops.size() == 1)
2359 return Ops[0];
2360 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2361 }
2362 }
2363
2364 // If we are adding something to a multiply expression, make sure the
2365 // something is not already an operand of the multiply. If so, merge it into
2366 // the multiply.
2367 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2368 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2369 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2370 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2371 if (isa<SCEVConstant>(MulOpSCEV))
2372 continue;
2373 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2374 if (MulOpSCEV == Ops[AddOp]) {
2375 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2376 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2377 if (Mul->getNumOperands() != 2) {
2378 // If the multiply has more than two operands, we must get the
2379 // Y*Z term.
2380 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2381 Mul->op_begin()+MulOp);
2382 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2383 InnerMul = getMulExpr(MulOps);
2384 }
2385 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2386 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2387 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2388 if (Ops.size() == 2) return OuterMul;
2389 if (AddOp < Idx) {
2390 Ops.erase(Ops.begin()+AddOp);
2391 Ops.erase(Ops.begin()+Idx-1);
2392 } else {
2393 Ops.erase(Ops.begin()+Idx);
2394 Ops.erase(Ops.begin()+AddOp-1);
2395 }
2396 Ops.push_back(OuterMul);
2397 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2398 }
2399
2400 // Check this multiply against other multiplies being added together.
2401 for (unsigned OtherMulIdx = Idx+1;
2402 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2403 ++OtherMulIdx) {
2404 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2405 // If MulOp occurs in OtherMul, we can fold the two multiplies
2406 // together.
2407 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2408 OMulOp != e; ++OMulOp)
2409 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2410 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2411 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2412 if (Mul->getNumOperands() != 2) {
2413 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2414 Mul->op_begin()+MulOp);
2415 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2416 InnerMul1 = getMulExpr(MulOps);
2417 }
2418 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2419 if (OtherMul->getNumOperands() != 2) {
2420 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2421 OtherMul->op_begin()+OMulOp);
2422 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2423 InnerMul2 = getMulExpr(MulOps);
2424 }
2425 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2426 const SCEV *InnerMulSum =
2427 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2428 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2429 if (Ops.size() == 2) return OuterMul;
2430 Ops.erase(Ops.begin()+Idx);
2431 Ops.erase(Ops.begin()+OtherMulIdx-1);
2432 Ops.push_back(OuterMul);
2433 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2434 }
2435 }
2436 }
2437 }
2438
2439 // If there are any add recurrences in the operands list, see if any other
2440 // added values are loop invariant. If so, we can fold them into the
2441 // recurrence.
2442 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2443 ++Idx;
2444
2445 // Scan over all recurrences, trying to fold loop invariants into them.
2446 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2447 // Scan all of the other operands to this add and add them to the vector if
2448 // they are loop invariant w.r.t. the recurrence.
2449 SmallVector<const SCEV *, 8> LIOps;
2450 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2451 const Loop *AddRecLoop = AddRec->getLoop();
2452 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2453 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2454 LIOps.push_back(Ops[i]);
2455 Ops.erase(Ops.begin()+i);
2456 --i; --e;
2457 }
2458
2459 // If we found some loop invariants, fold them into the recurrence.
2460 if (!LIOps.empty()) {
2461 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2462 LIOps.push_back(AddRec->getStart());
2463
2464 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2465 AddRec->op_end());
2466 // This follows from the fact that the no-wrap flags on the outer add
2467 // expression are applicable on the 0th iteration, when the add recurrence
2468 // will be equal to its start value.
2469 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2470
2471 // Build the new addrec. Propagate the NUW and NSW flags if both the
2472 // outer add and the inner addrec are guaranteed to have no overflow.
2473 // Always propagate NW.
2474 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2475 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2476
2477 // If all of the other operands were loop invariant, we are done.
2478 if (Ops.size() == 1) return NewRec;
2479
2480 // Otherwise, add the folded AddRec by the non-invariant parts.
2481 for (unsigned i = 0;; ++i)
2482 if (Ops[i] == AddRec) {
2483 Ops[i] = NewRec;
2484 break;
2485 }
2486 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2487 }
2488
2489 // Okay, if there weren't any loop invariants to be folded, check to see if
2490 // there are multiple AddRec's with the same loop induction variable being
2491 // added together. If so, we can fold them.
2492 for (unsigned OtherIdx = Idx+1;
2493 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2494 ++OtherIdx)
2495 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2496 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2497 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2498 AddRec->op_end());
2499 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2500 ++OtherIdx)
2501 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2502 if (OtherAddRec->getLoop() == AddRecLoop) {
2503 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2504 i != e; ++i) {
2505 if (i >= AddRecOps.size()) {
2506 AddRecOps.append(OtherAddRec->op_begin()+i,
2507 OtherAddRec->op_end());
2508 break;
2509 }
2510 SmallVector<const SCEV *, 2> TwoOps = {
2511 AddRecOps[i], OtherAddRec->getOperand(i)};
2512 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2513 }
2514 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2515 }
2516 // Step size has changed, so we cannot guarantee no self-wraparound.
2517 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2518 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2519 }
2520
2521 // Otherwise couldn't fold anything into this recurrence. Move onto the
2522 // next one.
2523 }
2524
2525 // Okay, it looks like we really DO need an add expr. Check to see if we
2526 // already have one, otherwise create a new one.
2527 return getOrCreateAddExpr(Ops, Flags);
2528}
2529
2530const SCEV *
2531ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2532 SCEV::NoWrapFlags Flags) {
2533 FoldingSetNodeID ID;
2534 ID.AddInteger(scAddExpr);
2535 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2536 ID.AddPointer(Ops[i]);
2537 void *IP = nullptr;
2538 SCEVAddExpr *S =
2539 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2540 if (!S) {
2541 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2542 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2543 S = new (SCEVAllocator)
2544 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2545 UniqueSCEVs.InsertNode(S, IP);
2546 }
2547 S->setNoWrapFlags(Flags);
2548 return S;
2549}
2550
2551static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2552 uint64_t k = i*j;
2553 if (j > 1 && k / j != i) Overflow = true;
2554 return k;
2555}
2556
2557/// Compute the result of "n choose k", the binomial coefficient. If an
2558/// intermediate computation overflows, Overflow will be set and the return will
2559/// be garbage. Overflow is not cleared on absence of overflow.
2560static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2561 // We use the multiplicative formula:
2562 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2563 // At each iteration, we take the n-th term of the numeral and divide by the
2564 // (k-n)th term of the denominator. This division will always produce an
2565 // integral result, and helps reduce the chance of overflow in the
2566 // intermediate computations. However, we can still overflow even when the
2567 // final result would fit.
2568
2569 if (n == 0 || n == k) return 1;
2570 if (k > n) return 0;
2571
2572 if (k > n/2)
2573 k = n-k;
2574
2575 uint64_t r = 1;
2576 for (uint64_t i = 1; i <= k; ++i) {
2577 r = umul_ov(r, n-(i-1), Overflow);
2578 r /= i;
2579 }
2580 return r;
2581}
2582
2583/// Determine if any of the operands in this SCEV are a constant or if
2584/// any of the add or multiply expressions in this SCEV contain a constant.
2585static bool containsConstantSomewhere(const SCEV *StartExpr) {
2586 SmallVector<const SCEV *, 4> Ops;
2587 Ops.push_back(StartExpr);
2588 while (!Ops.empty()) {
2589 const SCEV *CurrentExpr = Ops.pop_back_val();
2590 if (isa<SCEVConstant>(*CurrentExpr))
2591 return true;
2592
2593 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2594 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2595 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2596 }
2597 }
2598 return false;
2599}
2600
2601/// Get a canonical multiply expression, or something simpler if possible.
2602const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2603 SCEV::NoWrapFlags Flags) {
2604 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2605, __PRETTY_FUNCTION__))
2605 "only nuw or nsw allowed")((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2605, __PRETTY_FUNCTION__))
;
2606 assert(!Ops.empty() && "Cannot get empty mul!")((!Ops.empty() && "Cannot get empty mul!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty mul!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2606, __PRETTY_FUNCTION__))
;
2607 if (Ops.size() == 1) return Ops[0];
2608#ifndef NDEBUG
2609 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2610 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2611 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2612, __PRETTY_FUNCTION__))
2612 "SCEVMulExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2612, __PRETTY_FUNCTION__))
;
2613#endif
2614
2615 // Sort by complexity, this groups all similar expression types together.
2616 GroupByComplexity(Ops, &LI);
2617
2618 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2619
2620 // If there are any constants, fold them together.
2621 unsigned Idx = 0;
2622 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2623
2624 // C1*(C2+V) -> C1*C2 + C1*V
2625 if (Ops.size() == 2)
2626 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2627 // If any of Add's ops are Adds or Muls with a constant,
2628 // apply this transformation as well.
2629 if (Add->getNumOperands() == 2)
2630 if (containsConstantSomewhere(Add))
2631 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2632 getMulExpr(LHSC, Add->getOperand(1)));
2633
2634 ++Idx;
2635 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2636 // We found two constants, fold them together!
2637 ConstantInt *Fold =
2638 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2639 Ops[0] = getConstant(Fold);
2640 Ops.erase(Ops.begin()+1); // Erase the folded element
2641 if (Ops.size() == 1) return Ops[0];
2642 LHSC = cast<SCEVConstant>(Ops[0]);
2643 }
2644
2645 // If we are left with a constant one being multiplied, strip it off.
2646 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2647 Ops.erase(Ops.begin());
2648 --Idx;
2649 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2650 // If we have a multiply of zero, it will always be zero.
2651 return Ops[0];
2652 } else if (Ops[0]->isAllOnesValue()) {
2653 // If we have a mul by -1 of an add, try distributing the -1 among the
2654 // add operands.
2655 if (Ops.size() == 2) {
2656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2657 SmallVector<const SCEV *, 4> NewOps;
2658 bool AnyFolded = false;
2659 for (const SCEV *AddOp : Add->operands()) {
2660 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2661 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2662 NewOps.push_back(Mul);
2663 }
2664 if (AnyFolded)
2665 return getAddExpr(NewOps);
2666 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2667 // Negation preserves a recurrence's no self-wrap property.
2668 SmallVector<const SCEV *, 4> Operands;
2669 for (const SCEV *AddRecOp : AddRec->operands())
2670 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2671
2672 return getAddRecExpr(Operands, AddRec->getLoop(),
2673 AddRec->getNoWrapFlags(SCEV::FlagNW));
2674 }
2675 }
2676 }
2677
2678 if (Ops.size() == 1)
2679 return Ops[0];
2680 }
2681
2682 // Skip over the add expression until we get to a multiply.
2683 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2684 ++Idx;
2685
2686 // If there are mul operands inline them all into this expression.
2687 if (Idx < Ops.size()) {
2688 bool DeletedMul = false;
2689 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2690 if (Ops.size() > MulOpsInlineThreshold)
2691 break;
2692 // If we have an mul, expand the mul operands onto the end of the operands
2693 // list.
2694 Ops.erase(Ops.begin()+Idx);
2695 Ops.append(Mul->op_begin(), Mul->op_end());
2696 DeletedMul = true;
2697 }
2698
2699 // If we deleted at least one mul, we added operands to the end of the list,
2700 // and they are not necessarily sorted. Recurse to resort and resimplify
2701 // any operands we just acquired.
2702 if (DeletedMul)
2703 return getMulExpr(Ops);
2704 }
2705
2706 // If there are any add recurrences in the operands list, see if any other
2707 // added values are loop invariant. If so, we can fold them into the
2708 // recurrence.
2709 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2710 ++Idx;
2711
2712 // Scan over all recurrences, trying to fold loop invariants into them.
2713 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2714 // Scan all of the other operands to this mul and add them to the vector if
2715 // they are loop invariant w.r.t. the recurrence.
2716 SmallVector<const SCEV *, 8> LIOps;
2717 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2718 const Loop *AddRecLoop = AddRec->getLoop();
2719 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2720 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2721 LIOps.push_back(Ops[i]);
2722 Ops.erase(Ops.begin()+i);
2723 --i; --e;
2724 }
2725
2726 // If we found some loop invariants, fold them into the recurrence.
2727 if (!LIOps.empty()) {
2728 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2729 SmallVector<const SCEV *, 4> NewOps;
2730 NewOps.reserve(AddRec->getNumOperands());
2731 const SCEV *Scale = getMulExpr(LIOps);
2732 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2733 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2734
2735 // Build the new addrec. Propagate the NUW and NSW flags if both the
2736 // outer mul and the inner addrec are guaranteed to have no overflow.
2737 //
2738 // No self-wrap cannot be guaranteed after changing the step size, but
2739 // will be inferred if either NUW or NSW is true.
2740 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2741 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2742
2743 // If all of the other operands were loop invariant, we are done.
2744 if (Ops.size() == 1) return NewRec;
2745
2746 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2747 for (unsigned i = 0;; ++i)
2748 if (Ops[i] == AddRec) {
2749 Ops[i] = NewRec;
2750 break;
2751 }
2752 return getMulExpr(Ops);
2753 }
2754
2755 // Okay, if there weren't any loop invariants to be folded, check to see if
2756 // there are multiple AddRec's with the same loop induction variable being
2757 // multiplied together. If so, we can fold them.
2758
2759 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2760 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2761 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2762 // ]]],+,...up to x=2n}.
2763 // Note that the arguments to choose() are always integers with values
2764 // known at compile time, never SCEV objects.
2765 //
2766 // The implementation avoids pointless extra computations when the two
2767 // addrec's are of different length (mathematically, it's equivalent to
2768 // an infinite stream of zeros on the right).
2769 bool OpsModified = false;
2770 for (unsigned OtherIdx = Idx+1;
2771 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2772 ++OtherIdx) {
2773 const SCEVAddRecExpr *OtherAddRec =
2774 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2775 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2776 continue;
2777
2778 bool Overflow = false;
2779 Type *Ty = AddRec->getType();
2780 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2781 SmallVector<const SCEV*, 7> AddRecOps;
2782 for (int x = 0, xe = AddRec->getNumOperands() +
2783 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2784 const SCEV *Term = getZero(Ty);
2785 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2786 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2787 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2788 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2789 z < ze && !Overflow; ++z) {
2790 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2791 uint64_t Coeff;
2792 if (LargerThan64Bits)
2793 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2794 else
2795 Coeff = Coeff1*Coeff2;
2796 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2797 const SCEV *Term1 = AddRec->getOperand(y-z);
2798 const SCEV *Term2 = OtherAddRec->getOperand(z);
2799 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2800 }
2801 }
2802 AddRecOps.push_back(Term);
2803 }
2804 if (!Overflow) {
2805 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2806 SCEV::FlagAnyWrap);
2807 if (Ops.size() == 2) return NewAddRec;
2808 Ops[Idx] = NewAddRec;
2809 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2810 OpsModified = true;
2811 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2812 if (!AddRec)
2813 break;
2814 }
2815 }
2816 if (OpsModified)
2817 return getMulExpr(Ops);
2818
2819 // Otherwise couldn't fold anything into this recurrence. Move onto the
2820 // next one.
2821 }
2822
2823 // Okay, it looks like we really DO need an mul expr. Check to see if we
2824 // already have one, otherwise create a new one.
2825 FoldingSetNodeID ID;
2826 ID.AddInteger(scMulExpr);
2827 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828 ID.AddPointer(Ops[i]);
2829 void *IP = nullptr;
2830 SCEVMulExpr *S =
2831 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2832 if (!S) {
2833 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2834 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2835 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2836 O, Ops.size());
2837 UniqueSCEVs.InsertNode(S, IP);
2838 }
2839 S->setNoWrapFlags(Flags);
2840 return S;
2841}
2842
2843/// Get a canonical unsigned division expression, or something simpler if
2844/// possible.
2845const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2846 const SCEV *RHS) {
2847 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2849, __PRETTY_FUNCTION__))
2848 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2849, __PRETTY_FUNCTION__))
2849 "SCEVUDivExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 2849, __PRETTY_FUNCTION__))
;
2850
2851 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2852 if (RHSC->getValue()->equalsInt(1))
2853 return LHS; // X udiv 1 --> x
2854 // If the denominator is zero, the result of the udiv is undefined. Don't
2855 // try to analyze it, because the resolution chosen here may differ from
2856 // the resolution chosen in other parts of the compiler.
2857 if (!RHSC->getValue()->isZero()) {
2858 // Determine if the division can be folded into the operands of
2859 // its operands.
2860 // TODO: Generalize this to non-constants by using known-bits information.
2861 Type *Ty = LHS->getType();
2862 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2863 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2864 // For non-power-of-two values, effectively round the value up to the
2865 // nearest power of two.
2866 if (!RHSC->getAPInt().isPowerOf2())
2867 ++MaxShiftAmt;
2868 IntegerType *ExtTy =
2869 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2870 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2871 if (const SCEVConstant *Step =
2872 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2873 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2874 const APInt &StepInt = Step->getAPInt();
2875 const APInt &DivInt = RHSC->getAPInt();
2876 if (!StepInt.urem(DivInt) &&
2877 getZeroExtendExpr(AR, ExtTy) ==
2878 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2879 getZeroExtendExpr(Step, ExtTy),
2880 AR->getLoop(), SCEV::FlagAnyWrap)) {
2881 SmallVector<const SCEV *, 4> Operands;
2882 for (const SCEV *Op : AR->operands())
2883 Operands.push_back(getUDivExpr(Op, RHS));
2884 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2885 }
2886 /// Get a canonical UDivExpr for a recurrence.
2887 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2888 // We can currently only fold X%N if X is constant.
2889 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2890 if (StartC && !DivInt.urem(StepInt) &&
2891 getZeroExtendExpr(AR, ExtTy) ==
2892 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2893 getZeroExtendExpr(Step, ExtTy),
2894 AR->getLoop(), SCEV::FlagAnyWrap)) {
2895 const APInt &StartInt = StartC->getAPInt();
2896 const APInt &StartRem = StartInt.urem(StepInt);
2897 if (StartRem != 0)
2898 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2899 AR->getLoop(), SCEV::FlagNW);
2900 }
2901 }
2902 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2903 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2904 SmallVector<const SCEV *, 4> Operands;
2905 for (const SCEV *Op : M->operands())
2906 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2907 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2908 // Find an operand that's safely divisible.
2909 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2910 const SCEV *Op = M->getOperand(i);
2911 const SCEV *Div = getUDivExpr(Op, RHSC);
2912 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2913 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2914 M->op_end());
2915 Operands[i] = Div;
2916 return getMulExpr(Operands);
2917 }
2918 }
2919 }
2920 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2921 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2922 SmallVector<const SCEV *, 4> Operands;
2923 for (const SCEV *Op : A->operands())
2924 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2925 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2926 Operands.clear();
2927 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2928 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2929 if (isa<SCEVUDivExpr>(Op) ||
2930 getMulExpr(Op, RHS) != A->getOperand(i))
2931 break;
2932 Operands.push_back(Op);
2933 }
2934 if (Operands.size() == A->getNumOperands())
2935 return getAddExpr(Operands);
2936 }
2937 }
2938
2939 // Fold if both operands are constant.
2940 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2941 Constant *LHSCV = LHSC->getValue();
2942 Constant *RHSCV = RHSC->getValue();
2943 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2944 RHSCV)));
2945 }
2946 }
2947 }
2948
2949 FoldingSetNodeID ID;
2950 ID.AddInteger(scUDivExpr);
2951 ID.AddPointer(LHS);
2952 ID.AddPointer(RHS);
2953 void *IP = nullptr;
2954 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2955 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2956 LHS, RHS);
2957 UniqueSCEVs.InsertNode(S, IP);
2958 return S;
2959}
2960
2961static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2962 APInt A = C1->getAPInt().abs();
2963 APInt B = C2->getAPInt().abs();
2964 uint32_t ABW = A.getBitWidth();
2965 uint32_t BBW = B.getBitWidth();
2966
2967 if (ABW > BBW)
2968 B = B.zext(ABW);
2969 else if (ABW < BBW)
2970 A = A.zext(BBW);
2971
2972 return APIntOps::GreatestCommonDivisor(A, B);
2973}
2974
2975/// Get a canonical unsigned division expression, or something simpler if
2976/// possible. There is no representation for an exact udiv in SCEV IR, but we
2977/// can attempt to remove factors from the LHS and RHS. We can't do this when
2978/// it's not exact because the udiv may be clearing bits.
2979const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2980 const SCEV *RHS) {
2981 // TODO: we could try to find factors in all sorts of things, but for now we
2982 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2983 // end of this file for inspiration.
2984
2985 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2986 if (!Mul || !Mul->hasNoUnsignedWrap())
2987 return getUDivExpr(LHS, RHS);
2988
2989 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2990 // If the mulexpr multiplies by a constant, then that constant must be the
2991 // first element of the mulexpr.
2992 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2993 if (LHSCst == RHSCst) {
2994 SmallVector<const SCEV *, 2> Operands;
2995 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2996 return getMulExpr(Operands);
2997 }
2998
2999 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3000 // that there's a factor provided by one of the other terms. We need to
3001 // check.
3002 APInt Factor = gcd(LHSCst, RHSCst);
3003 if (!Factor.isIntN(1)) {
3004 LHSCst =
3005 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3006 RHSCst =
3007 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3008 SmallVector<const SCEV *, 2> Operands;
3009 Operands.push_back(LHSCst);
3010 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3011 LHS = getMulExpr(Operands);
3012 RHS = RHSCst;
3013 Mul = dyn_cast<SCEVMulExpr>(LHS);
3014 if (!Mul)
3015 return getUDivExactExpr(LHS, RHS);
3016 }
3017 }
3018 }
3019
3020 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3021 if (Mul->getOperand(i) == RHS) {
3022 SmallVector<const SCEV *, 2> Operands;
3023 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3024 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3025 return getMulExpr(Operands);
3026 }
3027 }
3028
3029 return getUDivExpr(LHS, RHS);
3030}
3031
3032/// Get an add recurrence expression for the specified loop. Simplify the
3033/// expression as much as possible.
3034const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3035 const Loop *L,
3036 SCEV::NoWrapFlags Flags) {
3037 SmallVector<const SCEV *, 4> Operands;
3038 Operands.push_back(Start);
3039 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3040 if (StepChrec->getLoop() == L) {
3041 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3042 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3043 }
3044
3045 Operands.push_back(Step);
3046 return getAddRecExpr(Operands, L, Flags);
3047}
3048
3049/// Get an add recurrence expression for the specified loop. Simplify the
3050/// expression as much as possible.
3051const SCEV *
3052ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3053 const Loop *L, SCEV::NoWrapFlags Flags) {
3054 if (Operands.size() == 1) return Operands[0];
3055#ifndef NDEBUG
3056 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3057 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3058 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3059, __PRETTY_FUNCTION__))
3059 "SCEVAddRecExpr operand types don't match!")((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3059, __PRETTY_FUNCTION__))
;
3060 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3061 assert(isLoopInvariant(Operands[i], L) &&((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3062, __PRETTY_FUNCTION__))
3062 "SCEVAddRecExpr operand is not loop-invariant!")((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3062, __PRETTY_FUNCTION__))
;
3063#endif
3064
3065 if (Operands.back()->isZero()) {
3066 Operands.pop_back();
3067 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3068 }
3069
3070 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3071 // use that information to infer NUW and NSW flags. However, computing a
3072 // BE count requires calling getAddRecExpr, so we may not yet have a
3073 // meaningful BE count at this point (and if we don't, we'd be stuck
3074 // with a SCEVCouldNotCompute as the cached BE count).
3075
3076 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3077
3078 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3079 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3080 const Loop *NestedLoop = NestedAR->getLoop();
3081 if (L->contains(NestedLoop)
3082 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3083 : (!NestedLoop->contains(L) &&
3084 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3085 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3086 NestedAR->op_end());
3087 Operands[0] = NestedAR->getStart();
3088 // AddRecs require their operands be loop-invariant with respect to their
3089 // loops. Don't perform this transformation if it would break this
3090 // requirement.
3091 bool AllInvariant = all_of(
3092 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3093
3094 if (AllInvariant) {
3095 // Create a recurrence for the outer loop with the same step size.
3096 //
3097 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3098 // inner recurrence has the same property.
3099 SCEV::NoWrapFlags OuterFlags =
3100 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3101
3102 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3103 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3104 return isLoopInvariant(Op, NestedLoop);
3105 });
3106
3107 if (AllInvariant) {
3108 // Ok, both add recurrences are valid after the transformation.
3109 //
3110 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3111 // the outer recurrence has the same property.
3112 SCEV::NoWrapFlags InnerFlags =
3113 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3114 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3115 }
3116 }
3117 // Reset Operands to its original state.
3118 Operands[0] = NestedAR;
3119 }
3120 }
3121
3122 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3123 // already have one, otherwise create a new one.
3124 FoldingSetNodeID ID;
3125 ID.AddInteger(scAddRecExpr);
3126 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3127 ID.AddPointer(Operands[i]);
3128 ID.AddPointer(L);
3129 void *IP = nullptr;
3130 SCEVAddRecExpr *S =
3131 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3132 if (!S) {
3133 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3134 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3135 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3136 O, Operands.size(), L);
3137 UniqueSCEVs.InsertNode(S, IP);
3138 }
3139 S->setNoWrapFlags(Flags);
3140 return S;
3141}
3142
3143const SCEV *
3144ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3145 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3146 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3147 // getSCEV(Base)->getType() has the same address space as Base->getType()
3148 // because SCEV::getType() preserves the address space.
3149 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3150 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3151 // instruction to its SCEV, because the Instruction may be guarded by control
3152 // flow and the no-overflow bits may not be valid for the expression in any
3153 // context. This can be fixed similarly to how these flags are handled for
3154 // adds.
3155 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3156 : SCEV::FlagAnyWrap;
3157
3158 const SCEV *TotalOffset = getZero(IntPtrTy);
3159 // The array size is unimportant. The first thing we do on CurTy is getting
3160 // its element type.
3161 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3162 for (const SCEV *IndexExpr : IndexExprs) {
3163 // Compute the (potentially symbolic) offset in bytes for this index.
3164 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3165 // For a struct, add the member offset.
3166 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3167 unsigned FieldNo = Index->getZExtValue();
3168 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3169
3170 // Add the field offset to the running total offset.
3171 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3172
3173 // Update CurTy to the type of the field at Index.
3174 CurTy = STy->getTypeAtIndex(Index);
3175 } else {
3176 // Update CurTy to its element type.
3177 CurTy = cast<SequentialType>(CurTy)->getElementType();
3178 // For an array, add the element offset, explicitly scaled.
3179 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3180 // Getelementptr indices are signed.
3181 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3182
3183 // Multiply the index by the element size to compute the element offset.
3184 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3185
3186 // Add the element offset to the running total offset.
3187 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3188 }
3189 }
3190
3191 // Add the total offset from all the GEP indices to the base.
3192 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3193}
3194
3195const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3196 const SCEV *RHS) {
3197 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3198 return getSMaxExpr(Ops);
3199}
3200
3201const SCEV *
3202ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3203 assert(!Ops.empty() && "Cannot get empty smax!")((!Ops.empty() && "Cannot get empty smax!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty smax!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3203, __PRETTY_FUNCTION__))
;
3204 if (Ops.size() == 1) return Ops[0];
3205#ifndef NDEBUG
3206 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3207 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3208 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVSMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3209, __PRETTY_FUNCTION__))
3209 "SCEVSMaxExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVSMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3209, __PRETTY_FUNCTION__))
;
3210#endif
3211
3212 // Sort by complexity, this groups all similar expression types together.
3213 GroupByComplexity(Ops, &LI);
3214
3215 // If there are any constants, fold them together.
3216 unsigned Idx = 0;
3217 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3218 ++Idx;
3219 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3219, __PRETTY_FUNCTION__))
;
3220 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3221 // We found two constants, fold them together!
3222 ConstantInt *Fold = ConstantInt::get(
3223 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3224 Ops[0] = getConstant(Fold);
3225 Ops.erase(Ops.begin()+1); // Erase the folded element
3226 if (Ops.size() == 1) return Ops[0];
3227 LHSC = cast<SCEVConstant>(Ops[0]);
3228 }
3229
3230 // If we are left with a constant minimum-int, strip it off.
3231 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3232 Ops.erase(Ops.begin());
3233 --Idx;
3234 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3235 // If we have an smax with a constant maximum-int, it will always be
3236 // maximum-int.
3237 return Ops[0];
3238 }
3239
3240 if (Ops.size() == 1) return Ops[0];
3241 }
3242
3243 // Find the first SMax
3244 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3245 ++Idx;
3246
3247 // Check to see if one of the operands is an SMax. If so, expand its operands
3248 // onto our operand list, and recurse to simplify.
3249 if (Idx < Ops.size()) {
3250 bool DeletedSMax = false;
3251 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3252 Ops.erase(Ops.begin()+Idx);
3253 Ops.append(SMax->op_begin(), SMax->op_end());
3254 DeletedSMax = true;
3255 }
3256
3257 if (DeletedSMax)
3258 return getSMaxExpr(Ops);
3259 }
3260
3261 // Okay, check to see if the same value occurs in the operand list twice. If
3262 // so, delete one. Since we sorted the list, these values are required to
3263 // be adjacent.
3264 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3265 // X smax Y smax Y --> X smax Y
3266 // X smax Y --> X, if X is always greater than Y
3267 if (Ops[i] == Ops[i+1] ||
3268 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3269 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3270 --i; --e;
3271 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3272 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3273 --i; --e;
3274 }
3275
3276 if (Ops.size() == 1) return Ops[0];
3277
3278 assert(!Ops.empty() && "Reduced smax down to nothing!")((!Ops.empty() && "Reduced smax down to nothing!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Reduced smax down to nothing!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3278, __PRETTY_FUNCTION__))
;
3279
3280 // Okay, it looks like we really DO need an smax expr. Check to see if we
3281 // already have one, otherwise create a new one.
3282 FoldingSetNodeID ID;
3283 ID.AddInteger(scSMaxExpr);
3284 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3285 ID.AddPointer(Ops[i]);
3286 void *IP = nullptr;
3287 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3288 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3289 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3290 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3291 O, Ops.size());
3292 UniqueSCEVs.InsertNode(S, IP);
3293 return S;
3294}
3295
3296const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3297 const SCEV *RHS) {
3298 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3299 return getUMaxExpr(Ops);
3300}
3301
3302const SCEV *
3303ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3304 assert(!Ops.empty() && "Cannot get empty umax!")((!Ops.empty() && "Cannot get empty umax!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty umax!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3304, __PRETTY_FUNCTION__))
;
3305 if (Ops.size() == 1) return Ops[0];
3306#ifndef NDEBUG
3307 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3308 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3309 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVUMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3310, __PRETTY_FUNCTION__))
3310 "SCEVUMaxExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVUMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3310, __PRETTY_FUNCTION__))
;
3311#endif
3312
3313 // Sort by complexity, this groups all similar expression types together.
3314 GroupByComplexity(Ops, &LI);
3315
3316 // If there are any constants, fold them together.
3317 unsigned Idx = 0;
3318 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3319 ++Idx;
3320 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3320, __PRETTY_FUNCTION__))
;
3321 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3322 // We found two constants, fold them together!
3323 ConstantInt *Fold = ConstantInt::get(
3324 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3325 Ops[0] = getConstant(Fold);
3326 Ops.erase(Ops.begin()+1); // Erase the folded element
3327 if (Ops.size() == 1) return Ops[0];
3328 LHSC = cast<SCEVConstant>(Ops[0]);
3329 }
3330
3331 // If we are left with a constant minimum-int, strip it off.
3332 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3333 Ops.erase(Ops.begin());
3334 --Idx;
3335 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3336 // If we have an umax with a constant maximum-int, it will always be
3337 // maximum-int.
3338 return Ops[0];
3339 }
3340
3341 if (Ops.size() == 1) return Ops[0];
3342 }
3343
3344 // Find the first UMax
3345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3346 ++Idx;
3347
3348 // Check to see if one of the operands is a UMax. If so, expand its operands
3349 // onto our operand list, and recurse to simplify.
3350 if (Idx < Ops.size()) {
3351 bool DeletedUMax = false;
3352 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3353 Ops.erase(Ops.begin()+Idx);
3354 Ops.append(UMax->op_begin(), UMax->op_end());
3355 DeletedUMax = true;
3356 }
3357
3358 if (DeletedUMax)
3359 return getUMaxExpr(Ops);
3360 }
3361
3362 // Okay, check to see if the same value occurs in the operand list twice. If
3363 // so, delete one. Since we sorted the list, these values are required to
3364 // be adjacent.
3365 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3366 // X umax Y umax Y --> X umax Y
3367 // X umax Y --> X, if X is always greater than Y
3368 if (Ops[i] == Ops[i+1] ||
3369 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3370 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3371 --i; --e;
3372 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3373 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3374 --i; --e;
3375 }
3376
3377 if (Ops.size() == 1) return Ops[0];
3378
3379 assert(!Ops.empty() && "Reduced umax down to nothing!")((!Ops.empty() && "Reduced umax down to nothing!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Reduced umax down to nothing!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3379, __PRETTY_FUNCTION__))
;
3380
3381 // Okay, it looks like we really DO need a umax expr. Check to see if we
3382 // already have one, otherwise create a new one.
3383 FoldingSetNodeID ID;
3384 ID.AddInteger(scUMaxExpr);
3385 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3386 ID.AddPointer(Ops[i]);
3387 void *IP = nullptr;
3388 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3389 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3390 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3391 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3392 O, Ops.size());
3393 UniqueSCEVs.InsertNode(S, IP);
3394 return S;
3395}
3396
3397const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3398 const SCEV *RHS) {
3399 // ~smax(~x, ~y) == smin(x, y).
3400 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3401}
3402
3403const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3404 const SCEV *RHS) {
3405 // ~umax(~x, ~y) == umin(x, y)
3406 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3407}
3408
3409const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3410 // We can bypass creating a target-independent
3411 // constant expression and then folding it back into a ConstantInt.
3412 // This is just a compile-time optimization.
3413 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3414}
3415
3416const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3417 StructType *STy,
3418 unsigned FieldNo) {
3419 // We can bypass creating a target-independent
3420 // constant expression and then folding it back into a ConstantInt.
3421 // This is just a compile-time optimization.
3422 return getConstant(
3423 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3424}
3425
3426const SCEV *ScalarEvolution::getUnknown(Value *V) {
3427 // Don't attempt to do anything other than create a SCEVUnknown object
3428 // here. createSCEV only calls getUnknown after checking for all other
3429 // interesting possibilities, and any other code that calls getUnknown
3430 // is doing so in order to hide a value from SCEV canonicalization.
3431
3432 FoldingSetNodeID ID;
3433 ID.AddInteger(scUnknown);
3434 ID.AddPointer(V);
3435 void *IP = nullptr;
3436 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3437 assert(cast<SCEVUnknown>(S)->getValue() == V &&((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3438, __PRETTY_FUNCTION__))
3438 "Stale SCEVUnknown in uniquing map!")((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3438, __PRETTY_FUNCTION__))
;
3439 return S;
3440 }
3441 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3442 FirstUnknown);
3443 FirstUnknown = cast<SCEVUnknown>(S);
3444 UniqueSCEVs.InsertNode(S, IP);
3445 return S;
3446}
3447
3448//===----------------------------------------------------------------------===//
3449// Basic SCEV Analysis and PHI Idiom Recognition Code
3450//
3451
3452/// Test if values of the given type are analyzable within the SCEV
3453/// framework. This primarily includes integer types, and it can optionally
3454/// include pointer types if the ScalarEvolution class has access to
3455/// target-specific information.
3456bool ScalarEvolution::isSCEVable(Type *Ty) const {
3457 // Integers and pointers are always SCEVable.
3458 return Ty->isIntegerTy() || Ty->isPointerTy();
3459}
3460
3461/// Return the size in bits of the specified type, for which isSCEVable must
3462/// return true.
3463uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3464 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3464, __PRETTY_FUNCTION__))
;
3465 return getDataLayout().getTypeSizeInBits(Ty);
3466}
3467
3468/// Return a type with the same bitwidth as the given type and which represents
3469/// how SCEV will treat the given type, for which isSCEVable must return
3470/// true. For pointer types, this is the pointer-sized integer type.
3471Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3472 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3472, __PRETTY_FUNCTION__))
;
3473
3474 if (Ty->isIntegerTy())
3475 return Ty;
3476
3477 // The only other support type is pointer.
3478 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!")((Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"
) ? static_cast<void> (0) : __assert_fail ("Ty->isPointerTy() && \"Unexpected non-pointer non-integer type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3478, __PRETTY_FUNCTION__))
;
3479 return getDataLayout().getIntPtrType(Ty);
3480}
3481
3482Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3483 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3484}
3485
3486const SCEV *ScalarEvolution::getCouldNotCompute() {
3487 return CouldNotCompute.get();
3488}
3489
3490bool ScalarEvolution::checkValidity(const SCEV *S) const {
3491 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3492 auto *SU = dyn_cast<SCEVUnknown>(S);
3493 return SU && SU->getValue() == nullptr;
3494 });
3495
3496 return !ContainsNulls;
3497}
3498
3499bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3500 HasRecMapType::iterator I = HasRecMap.find(S);
3501 if (I != HasRecMap.end())
3502 return I->second;
3503
3504 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3505 HasRecMap.insert({S, FoundAddRec});
3506 return FoundAddRec;
3507}
3508
3509/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3510/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3511/// offset I, then return {S', I}, else return {\p S, nullptr}.
3512static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3513 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3514 if (!Add)
3515 return {S, nullptr};
3516
3517 if (Add->getNumOperands() != 2)
3518 return {S, nullptr};
3519
3520 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3521 if (!ConstOp)
3522 return {S, nullptr};
3523
3524 return {Add->getOperand(1), ConstOp->getValue()};
3525}
3526
3527/// Return the ValueOffsetPair set for \p S. \p S can be represented
3528/// by the value and offset from any ValueOffsetPair in the set.
3529SetVector<ScalarEvolution::ValueOffsetPair> *
3530ScalarEvolution::getSCEVValues(const SCEV *S) {
3531 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3532 if (SI == ExprValueMap.end())
3533 return nullptr;
3534#ifndef NDEBUG
3535 if (VerifySCEVMap) {
3536 // Check there is no dangling Value in the set returned.
3537 for (const auto &VE : SI->second)
3538 assert(ValueExprMap.count(VE.first))((ValueExprMap.count(VE.first)) ? static_cast<void> (0)
: __assert_fail ("ValueExprMap.count(VE.first)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3538, __PRETTY_FUNCTION__))
;
3539 }
3540#endif
3541 return &SI->second;
3542}
3543
3544/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3545/// cannot be used separately. eraseValueFromMap should be used to remove
3546/// V from ValueExprMap and ExprValueMap at the same time.
3547void ScalarEvolution::eraseValueFromMap(Value *V) {
3548 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3549 if (I != ValueExprMap.end()) {
3550 const SCEV *S = I->second;
3551 // Remove {V, 0} from the set of ExprValueMap[S]
3552 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3553 SV->remove({V, nullptr});
3554
3555 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3556 const SCEV *Stripped;
3557 ConstantInt *Offset;
3558 std::tie(Stripped, Offset) = splitAddExpr(S);
3559 if (Offset != nullptr) {
3560 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3561 SV->remove({V, Offset});
3562 }
3563 ValueExprMap.erase(V);
3564 }
3565}
3566
3567/// Return an existing SCEV if it exists, otherwise analyze the expression and
3568/// create a new one.
3569const SCEV *ScalarEvolution::getSCEV(Value *V) {
3570 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3570, __PRETTY_FUNCTION__))
;
3571
3572 const SCEV *S = getExistingSCEV(V);
3573 if (S == nullptr) {
3574 S = createSCEV(V);
3575 // During PHI resolution, it is possible to create two SCEVs for the same
3576 // V, so it is needed to double check whether V->S is inserted into
3577 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3578 std::pair<ValueExprMapType::iterator, bool> Pair =
3579 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3580 if (Pair.second) {
3581 ExprValueMap[S].insert({V, nullptr});
3582
3583 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3584 // ExprValueMap.
3585 const SCEV *Stripped = S;
3586 ConstantInt *Offset = nullptr;
3587 std::tie(Stripped, Offset) = splitAddExpr(S);
3588 // If stripped is SCEVUnknown, don't bother to save
3589 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3590 // increase the complexity of the expansion code.
3591 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3592 // because it may generate add/sub instead of GEP in SCEV expansion.
3593 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3594 !isa<GetElementPtrInst>(V))
3595 ExprValueMap[Stripped].insert({V, Offset});
3596 }
3597 }
3598 return S;
3599}
3600
3601const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3602 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3602, __PRETTY_FUNCTION__))
;
3603
3604 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3605 if (I != ValueExprMap.end()) {
3606 const SCEV *S = I->second;
3607 if (checkValidity(S))
3608 return S;
3609 eraseValueFromMap(V);
3610 forgetMemoizedResults(S);
3611 }
3612 return nullptr;
3613}
3614
3615/// Return a SCEV corresponding to -V = -1*V
3616///
3617const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3618 SCEV::NoWrapFlags Flags) {
3619 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3620 return getConstant(
3621 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3622
3623 Type *Ty = V->getType();
3624 Ty = getEffectiveSCEVType(Ty);
3625 return getMulExpr(
3626 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3627}
3628
3629/// Return a SCEV corresponding to ~V = -1-V
3630const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3631 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3632 return getConstant(
3633 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3634
3635 Type *Ty = V->getType();
3636 Ty = getEffectiveSCEVType(Ty);
3637 const SCEV *AllOnes =
3638 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3639 return getMinusSCEV(AllOnes, V);
3640}
3641
3642const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3643 SCEV::NoWrapFlags Flags) {
3644 // Fast path: X - X --> 0.
3645 if (LHS == RHS)
3646 return getZero(LHS->getType());
3647
3648 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3649 // makes it so that we cannot make much use of NUW.
3650 auto AddFlags = SCEV::FlagAnyWrap;
3651 const bool RHSIsNotMinSigned =
3652 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3653 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3654 // Let M be the minimum representable signed value. Then (-1)*RHS
3655 // signed-wraps if and only if RHS is M. That can happen even for
3656 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3657 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3658 // (-1)*RHS, we need to prove that RHS != M.
3659 //
3660 // If LHS is non-negative and we know that LHS - RHS does not
3661 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3662 // either by proving that RHS > M or that LHS >= 0.
3663 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3664 AddFlags = SCEV::FlagNSW;
3665 }
3666 }
3667
3668 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3669 // RHS is NSW and LHS >= 0.
3670 //
3671 // The difficulty here is that the NSW flag may have been proven
3672 // relative to a loop that is to be found in a recurrence in LHS and
3673 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3674 // larger scope than intended.
3675 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3676
3677 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3678}
3679
3680const SCEV *
3681ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3682 Type *SrcTy = V->getType();
3683 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3685, __PRETTY_FUNCTION__))
3684 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3685, __PRETTY_FUNCTION__))
3685 "Cannot truncate or zero extend with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3685, __PRETTY_FUNCTION__))
;
3686 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3687 return V; // No conversion
3688 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3689 return getTruncateExpr(V, Ty);
3690 return getZeroExtendExpr(V, Ty);
3691}
3692
3693const SCEV *
3694ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3695 Type *Ty) {
3696 Type *SrcTy = V->getType();
3697 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3699, __PRETTY_FUNCTION__))
3698 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3699, __PRETTY_FUNCTION__))
3699 "Cannot truncate or zero extend with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3699, __PRETTY_FUNCTION__))
;
3700 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3701 return V; // No conversion
3702 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3703 return getTruncateExpr(V, Ty);
3704 return getSignExtendExpr(V, Ty);
3705}
3706
3707const SCEV *
3708ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3709 Type *SrcTy = V->getType();
3710 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3712, __PRETTY_FUNCTION__))
3711 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3712, __PRETTY_FUNCTION__))
3712 "Cannot noop or zero extend with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3712, __PRETTY_FUNCTION__))
;
3713 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3714, __PRETTY_FUNCTION__))
3714 "getNoopOrZeroExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3714, __PRETTY_FUNCTION__))
;
3715 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3716 return V; // No conversion
3717 return getZeroExtendExpr(V, Ty);
3718}
3719
3720const SCEV *
3721ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3722 Type *SrcTy = V->getType();
3723 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or sign extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3725, __PRETTY_FUNCTION__))
3724 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or sign extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3725, __PRETTY_FUNCTION__))
3725 "Cannot noop or sign extend with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or sign extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3725, __PRETTY_FUNCTION__))
;
3726 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3727, __PRETTY_FUNCTION__))
3727 "getNoopOrSignExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3727, __PRETTY_FUNCTION__))
;
3728 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3729 return V; // No conversion
3730 return getSignExtendExpr(V, Ty);
3731}
3732
3733const SCEV *
3734ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3735 Type *SrcTy = V->getType();
3736 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or any extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3738, __PRETTY_FUNCTION__))
3737 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or any extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3738, __PRETTY_FUNCTION__))
3738 "Cannot noop or any extend with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot noop or any extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3738, __PRETTY_FUNCTION__))
;
3739 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3740, __PRETTY_FUNCTION__))
3740 "getNoopOrAnyExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3740, __PRETTY_FUNCTION__))
;
3741 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3742 return V; // No conversion
3743 return getAnyExtendExpr(V, Ty);
3744}
3745
3746const SCEV *
3747ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3748 Type *SrcTy = V->getType();
3749 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or noop with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3751, __PRETTY_FUNCTION__))
3750 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or noop with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3751, __PRETTY_FUNCTION__))
3751 "Cannot truncate or noop with non-integer arguments!")(((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
(Ty->isIntegerTy() || Ty->isPointerTy()) && "Cannot truncate or noop with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3751, __PRETTY_FUNCTION__))
;
3752 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3753, __PRETTY_FUNCTION__))
3753 "getTruncateOrNoop cannot extend!")((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 3753, __PRETTY_FUNCTION__))
;
3754 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3755 return V; // No conversion
3756 return getTruncateExpr(V, Ty);
3757}
3758
3759const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3760 const SCEV *RHS) {
3761 const SCEV *PromotedLHS = LHS;
3762 const SCEV *PromotedRHS = RHS;
3763
3764 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3765 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3766 else
3767 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3768
3769 return getUMaxExpr(PromotedLHS, PromotedRHS);
3770}
3771
3772const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3773 const SCEV *RHS) {
3774 const SCEV *PromotedLHS = LHS;
3775 const SCEV *PromotedRHS = RHS;
3776
3777 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3778 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3779 else
3780 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3781
3782 return getUMinExpr(PromotedLHS, PromotedRHS);
3783}
3784
3785const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3786 // A pointer operand may evaluate to a nonpointer expression, such as null.
3787 if (!V->getType()->isPointerTy())
3788 return V;
3789
3790 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3791 return getPointerBase(Cast->getOperand());
3792 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3793 const SCEV *PtrOp = nullptr;
3794 for (const SCEV *NAryOp : NAry->operands()) {
3795 if (NAryOp->getType()->isPointerTy()) {
3796 // Cannot find the base of an expression with multiple pointer operands.
3797 if (PtrOp)
3798 return V;
3799 PtrOp = NAryOp;
3800 }
3801 }
3802 if (!PtrOp)
3803 return V;
3804 return getPointerBase(PtrOp);
3805 }
3806 return V;
3807}
3808
3809/// Push users of the given Instruction onto the given Worklist.
3810static void
3811PushDefUseChildren(Instruction *I,
3812 SmallVectorImpl<Instruction *> &Worklist) {
3813 // Push the def-use children onto the Worklist stack.
3814 for (User *U : I->users())
3815 Worklist.push_back(cast<Instruction>(U));
3816}
3817
3818void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3819 SmallVector<Instruction *, 16> Worklist;
3820 PushDefUseChildren(PN, Worklist);
3821
3822 SmallPtrSet<Instruction *, 8> Visited;
3823 Visited.insert(PN);
3824 while (!Worklist.empty()) {
3825 Instruction *I = Worklist.pop_back_val();
3826 if (!Visited.insert(I).second)
3827 continue;
3828
3829 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3830 if (It != ValueExprMap.end()) {
3831 const SCEV *Old = It->second;
3832
3833 // Short-circuit the def-use traversal if the symbolic name
3834 // ceases to appear in expressions.
3835 if (Old != SymName && !hasOperand(Old, SymName))
3836 continue;
3837
3838 // SCEVUnknown for a PHI either means that it has an unrecognized
3839 // structure, it's a PHI that's in the progress of being computed
3840 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3841 // additional loop trip count information isn't going to change anything.
3842 // In the second case, createNodeForPHI will perform the necessary
3843 // updates on its own when it gets to that point. In the third, we do
3844 // want to forget the SCEVUnknown.
3845 if (!isa<PHINode>(I) ||
3846 !isa<SCEVUnknown>(Old) ||
3847 (I != PN && Old == SymName)) {
3848 eraseValueFromMap(It->first);
3849 forgetMemoizedResults(Old);
3850 }
3851 }
3852
3853 PushDefUseChildren(I, Worklist);
3854 }
3855}
3856
3857namespace {
3858class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3859public:
3860 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3861 ScalarEvolution &SE) {
3862 SCEVInitRewriter Rewriter(L, SE);
3863 const SCEV *Result = Rewriter.visit(S);
3864 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3865 }
3866
3867 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3868 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3869
3870 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3871 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3872 Valid = false;
3873 return Expr;
3874 }
3875
3876 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3877 // Only allow AddRecExprs for this loop.
3878 if (Expr->getLoop() == L)
3879 return Expr->getStart();
3880 Valid = false;
3881 return Expr;
3882 }
3883
3884 bool isValid() { return Valid; }
3885
3886private:
3887 const Loop *L;
3888 bool Valid;
3889};
3890
3891class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3892public:
3893 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3894 ScalarEvolution &SE) {
3895 SCEVShiftRewriter Rewriter(L, SE);
3896 const SCEV *Result = Rewriter.visit(S);
3897 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3898 }
3899
3900 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3901 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3902
3903 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3904 // Only allow AddRecExprs for this loop.
3905 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3906 Valid = false;
3907 return Expr;
3908 }
3909
3910 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3911 if (Expr->getLoop() == L && Expr->isAffine())
3912 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3913 Valid = false;
3914 return Expr;
3915 }
3916 bool isValid() { return Valid; }
3917
3918private:
3919 const Loop *L;
3920 bool Valid;
3921};
3922} // end anonymous namespace
3923
3924SCEV::NoWrapFlags
3925ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3926 if (!AR->isAffine())
3927 return SCEV::FlagAnyWrap;
3928
3929 typedef OverflowingBinaryOperator OBO;
3930 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3931
3932 if (!AR->hasNoSignedWrap()) {
3933 ConstantRange AddRecRange = getSignedRange(AR);
3934 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3935
3936 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3937 Instruction::Add, IncRange, OBO::NoSignedWrap);
3938 if (NSWRegion.contains(AddRecRange))
3939 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3940 }
3941
3942 if (!AR->hasNoUnsignedWrap()) {
3943 ConstantRange AddRecRange = getUnsignedRange(AR);
3944 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3945
3946 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3947 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3948 if (NUWRegion.contains(AddRecRange))
3949 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3950 }
3951
3952 return Result;
3953}
3954
3955namespace {
3956/// Represents an abstract binary operation. This may exist as a
3957/// normal instruction or constant expression, or may have been
3958/// derived from an expression tree.
3959struct BinaryOp {
3960 unsigned Opcode;
3961 Value *LHS;
3962 Value *RHS;
3963 bool IsNSW;
3964 bool IsNUW;
3965
3966 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3967 /// constant expression.
3968 Operator *Op;
3969
3970 explicit BinaryOp(Operator *Op)
3971 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3972 IsNSW(false), IsNUW(false), Op(Op) {
3973 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3974 IsNSW = OBO->hasNoSignedWrap();
3975 IsNUW = OBO->hasNoUnsignedWrap();
3976 }
3977 }
3978
3979 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3980 bool IsNUW = false)
3981 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3982 Op(nullptr) {}
3983};
3984}
3985
3986
3987/// Try to map \p V into a BinaryOp, and return \c None on failure.
3988static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3989 auto *Op = dyn_cast<Operator>(V);
3990 if (!Op)
3991 return None;
3992
3993 // Implementation detail: all the cleverness here should happen without
3994 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3995 // SCEV expressions when possible, and we should not break that.
3996
3997 switch (Op->getOpcode()) {
3998 case Instruction::Add:
3999 case Instruction::Sub:
4000 case Instruction::Mul:
4001 case Instruction::UDiv:
4002 case Instruction::And:
4003 case Instruction::Or:
4004 case Instruction::AShr:
4005 case Instruction::Shl:
4006 return BinaryOp(Op);
4007
4008 case Instruction::Xor:
4009 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4010 // If the RHS of the xor is a signmask, then this is just an add.
4011 // Instcombine turns add of signmask into xor as a strength reduction step.
4012 if (RHSC->getValue().isSignMask())
4013 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4014 return BinaryOp(Op);
4015
4016 case Instruction::LShr:
4017 // Turn logical shift right of a constant into a unsigned divide.
4018 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4019 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4020
4021 // If the shift count is not less than the bitwidth, the result of
4022 // the shift is undefined. Don't try to analyze it, because the
4023 // resolution chosen here may differ from the resolution chosen in
4024 // other parts of the compiler.
4025 if (SA->getValue().ult(BitWidth)) {
4026 Constant *X =
4027 ConstantInt::get(SA->getContext(),
4028 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4029 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4030 }
4031 }
4032 return BinaryOp(Op);
4033
4034 case Instruction::ExtractValue: {
4035 auto *EVI = cast<ExtractValueInst>(Op);
4036 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4037 break;
4038
4039 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4040 if (!CI)
4041 break;
4042
4043 if (auto *F = CI->getCalledFunction())
4044 switch (F->getIntrinsicID()) {
4045 case Intrinsic::sadd_with_overflow:
4046 case Intrinsic::uadd_with_overflow: {
4047 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4048 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4049 CI->getArgOperand(1));
4050
4051 // Now that we know that all uses of the arithmetic-result component of
4052 // CI are guarded by the overflow check, we can go ahead and pretend
4053 // that the arithmetic is non-overflowing.
4054 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4055 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4056 CI->getArgOperand(1), /* IsNSW = */ true,
4057 /* IsNUW = */ false);
4058 else
4059 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4060 CI->getArgOperand(1), /* IsNSW = */ false,
4061 /* IsNUW*/ true);
4062 }
4063
4064 case Intrinsic::ssub_with_overflow:
4065 case Intrinsic::usub_with_overflow:
4066 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4067 CI->getArgOperand(1));
4068
4069 case Intrinsic::smul_with_overflow:
4070 case Intrinsic::umul_with_overflow:
4071 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4072 CI->getArgOperand(1));
4073 default:
4074 break;
4075 }
4076 }
4077
4078 default:
4079 break;
4080 }
4081
4082 return None;
4083}
4084
4085const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4086 const Loop *L = LI.getLoopFor(PN->getParent());
4087 if (!L || L->getHeader() != PN->getParent())
4088 return nullptr;
4089
4090 // The loop may have multiple entrances or multiple exits; we can analyze
4091 // this phi as an addrec if it has a unique entry value and a unique
4092 // backedge value.
4093 Value *BEValueV = nullptr, *StartValueV = nullptr;
4094 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4095 Value *V = PN->getIncomingValue(i);
4096 if (L->contains(PN->getIncomingBlock(i))) {
4097 if (!BEValueV) {
4098 BEValueV = V;
4099 } else if (BEValueV != V) {
4100 BEValueV = nullptr;
4101 break;
4102 }
4103 } else if (!StartValueV) {
4104 StartValueV = V;
4105 } else if (StartValueV != V) {
4106 StartValueV = nullptr;
4107 break;
4108 }
4109 }
4110 if (BEValueV && StartValueV) {
4111 // While we are analyzing this PHI node, handle its value symbolically.
4112 const SCEV *SymbolicName = getUnknown(PN);
4113 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4114, __PRETTY_FUNCTION__))
4114 "PHI node already processed?")((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4114, __PRETTY_FUNCTION__))
;
4115 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4116
4117 // Using this symbolic name for the PHI, analyze the value coming around
4118 // the back-edge.
4119 const SCEV *BEValue = getSCEV(BEValueV);
4120
4121 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4122 // has a special value for the first iteration of the loop.
4123
4124 // If the value coming around the backedge is an add with the symbolic
4125 // value we just inserted, then we found a simple induction variable!
4126 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4127 // If there is a single occurrence of the symbolic value, replace it
4128 // with a recurrence.
4129 unsigned FoundIndex = Add->getNumOperands();
4130 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4131 if (Add->getOperand(i) == SymbolicName)
4132 if (FoundIndex == e) {
4133 FoundIndex = i;
4134 break;
4135 }
4136
4137 if (FoundIndex != Add->getNumOperands()) {
4138 // Create an add with everything but the specified operand.
4139 SmallVector<const SCEV *, 8> Ops;
4140 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4141 if (i != FoundIndex)
4142 Ops.push_back(Add->getOperand(i));
4143 const SCEV *Accum = getAddExpr(Ops);
4144
4145 // This is not a valid addrec if the step amount is varying each
4146 // loop iteration, but is not itself an addrec in this loop.
4147 if (isLoopInvariant(Accum, L) ||
4148 (isa<SCEVAddRecExpr>(Accum) &&
4149 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4150 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4151
4152 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4153 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4154 if (BO->IsNUW)
4155 Flags = setFlags(Flags, SCEV::FlagNUW);
4156 if (BO->IsNSW)
4157 Flags = setFlags(Flags, SCEV::FlagNSW);
4158 }
4159 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4160 // If the increment is an inbounds GEP, then we know the address
4161 // space cannot be wrapped around. We cannot make any guarantee
4162 // about signed or unsigned overflow because pointers are
4163 // unsigned but we may have a negative index from the base
4164 // pointer. We can guarantee that no unsigned wrap occurs if the
4165 // indices form a positive value.
4166 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4167 Flags = setFlags(Flags, SCEV::FlagNW);
4168
4169 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4170 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4171 Flags = setFlags(Flags, SCEV::FlagNUW);
4172 }
4173
4174 // We cannot transfer nuw and nsw flags from subtraction
4175 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4176 // for instance.
4177 }
4178
4179 const SCEV *StartVal = getSCEV(StartValueV);
4180 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4181
4182 // Okay, for the entire analysis of this edge we assumed the PHI
4183 // to be symbolic. We now need to go back and purge all of the
4184 // entries for the scalars that use the symbolic expression.
4185 forgetSymbolicName(PN, SymbolicName);
4186 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4187
4188 // We can add Flags to the post-inc expression only if we
4189 // know that it us *undefined behavior* for BEValueV to
4190 // overflow.
4191 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4192 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4193 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4194
4195 return PHISCEV;
4196 }
4197 }
4198 } else {
4199 // Otherwise, this could be a loop like this:
4200 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4201 // In this case, j = {1,+,1} and BEValue is j.
4202 // Because the other in-value of i (0) fits the evolution of BEValue
4203 // i really is an addrec evolution.
4204 //
4205 // We can generalize this saying that i is the shifted value of BEValue
4206 // by one iteration:
4207 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4208 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4209 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4210 if (Shifted != getCouldNotCompute() &&
4211 Start != getCouldNotCompute()) {
4212 const SCEV *StartVal = getSCEV(StartValueV);
4213 if (Start == StartVal) {
4214 // Okay, for the entire analysis of this edge we assumed the PHI
4215 // to be symbolic. We now need to go back and purge all of the
4216 // entries for the scalars that use the symbolic expression.
4217 forgetSymbolicName(PN, SymbolicName);
4218 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4219 return Shifted;
4220 }
4221 }
4222 }
4223
4224 // Remove the temporary PHI node SCEV that has been inserted while intending
4225 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4226 // as it will prevent later (possibly simpler) SCEV expressions to be added
4227 // to the ValueExprMap.
4228 eraseValueFromMap(PN);
4229 }
4230
4231 return nullptr;
4232}
4233
4234// Checks if the SCEV S is available at BB. S is considered available at BB
4235// if S can be materialized at BB without introducing a fault.
4236static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4237 BasicBlock *BB) {
4238 struct CheckAvailable {
4239 bool TraversalDone = false;
4240 bool Available = true;
4241
4242 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4243 BasicBlock *BB = nullptr;
4244 DominatorTree &DT;
4245
4246 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4247 : L(L), BB(BB), DT(DT) {}
4248
4249 bool setUnavailable() {
4250 TraversalDone = true;
4251 Available = false;
4252 return false;
4253 }
4254
4255 bool follow(const SCEV *S) {
4256 switch (S->getSCEVType()) {
4257 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4258 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4259 // These expressions are available if their operand(s) is/are.
4260 return true;
4261
4262 case scAddRecExpr: {
4263 // We allow add recurrences that are on the loop BB is in, or some
4264 // outer loop. This guarantees availability because the value of the
4265 // add recurrence at BB is simply the "current" value of the induction
4266 // variable. We can relax this in the future; for instance an add
4267 // recurrence on a sibling dominating loop is also available at BB.
4268 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4269 if (L && (ARLoop == L || ARLoop->contains(L)))
4270 return true;
4271
4272 return setUnavailable();
4273 }
4274
4275 case scUnknown: {
4276 // For SCEVUnknown, we check for simple dominance.
4277 const auto *SU = cast<SCEVUnknown>(S);
4278 Value *V = SU->getValue();
4279
4280 if (isa<Argument>(V))
4281 return false;
4282
4283 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4284 return false;
4285
4286 return setUnavailable();
4287 }
4288
4289 case scUDivExpr:
4290 case scCouldNotCompute:
4291 // We do not try to smart about these at all.
4292 return setUnavailable();
4293 }
4294 llvm_unreachable("switch should be fully covered!")::llvm::llvm_unreachable_internal("switch should be fully covered!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4294)
;
4295 }
4296
4297 bool isDone() { return TraversalDone; }
4298 };
4299
4300 CheckAvailable CA(L, BB, DT);
4301 SCEVTraversal<CheckAvailable> ST(CA);
4302
4303 ST.visitAll(S);
4304 return CA.Available;
4305}
4306
4307// Try to match a control flow sequence that branches out at BI and merges back
4308// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4309// match.
4310static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4311 Value *&C, Value *&LHS, Value *&RHS) {
4312 C = BI->getCondition();
4313
4314 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4315 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4316
4317 if (!LeftEdge.isSingleEdge())
4318 return false;
4319
4320 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()")((RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"
) ? static_cast<void> (0) : __assert_fail ("RightEdge.isSingleEdge() && \"Follows from LeftEdge.isSingleEdge()\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4320, __PRETTY_FUNCTION__))
;
4321
4322 Use &LeftUse = Merge->getOperandUse(0);
4323 Use &RightUse = Merge->getOperandUse(1);
4324
4325 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4326 LHS = LeftUse;
4327 RHS = RightUse;
4328 return true;
4329 }
4330
4331 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4332 LHS = RightUse;
4333 RHS = LeftUse;
4334 return true;
4335 }
4336
4337 return false;
4338}
4339
4340const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4341 auto IsReachable =
4342 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4343 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4344 const Loop *L = LI.getLoopFor(PN->getParent());
4345
4346 // We don't want to break LCSSA, even in a SCEV expression tree.
4347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4348 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4349 return nullptr;
4350
4351 // Try to match
4352 //
4353 // br %cond, label %left, label %right
4354 // left:
4355 // br label %merge
4356 // right:
4357 // br label %merge
4358 // merge:
4359 // V = phi [ %x, %left ], [ %y, %right ]
4360 //
4361 // as "select %cond, %x, %y"
4362
4363 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4364 assert(IDom && "At least the entry block should dominate PN")((IDom && "At least the entry block should dominate PN"
) ? static_cast<void> (0) : __assert_fail ("IDom && \"At least the entry block should dominate PN\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4364, __PRETTY_FUNCTION__))
;
4365
4366 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4367 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4368
4369 if (BI && BI->isConditional() &&
4370 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4371 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4372 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4373 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4374 }
4375
4376 return nullptr;
4377}
4378
4379const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4380 if (const SCEV *S = createAddRecFromPHI(PN))
4381 return S;
4382
4383 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4384 return S;
4385
4386 // If the PHI has a single incoming value, follow that value, unless the
4387 // PHI's incoming blocks are in a different loop, in which case doing so
4388 // risks breaking LCSSA form. Instcombine would normally zap these, but
4389 // it doesn't have DominatorTree information, so it may miss cases.
4390 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4391 if (LI.replacementPreservesLCSSAForm(PN, V))
4392 return getSCEV(V);
4393
4394 // If it's not a loop phi, we can't handle it yet.
4395 return getUnknown(PN);
4396}
4397
4398const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4399 Value *Cond,
4400 Value *TrueVal,
4401 Value *FalseVal) {
4402 // Handle "constant" branch or select. This can occur for instance when a
4403 // loop pass transforms an inner loop and moves on to process the outer loop.
4404 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4405 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4406
4407 // Try to match some simple smax or umax patterns.
4408 auto *ICI = dyn_cast<ICmpInst>(Cond);
4409 if (!ICI)
4410 return getUnknown(I);
4411
4412 Value *LHS = ICI->getOperand(0);
4413 Value *RHS = ICI->getOperand(1);
4414
4415 switch (ICI->getPredicate()) {
4416 case ICmpInst::ICMP_SLT:
4417 case ICmpInst::ICMP_SLE:
4418 std::swap(LHS, RHS);
4419 LLVM_FALLTHROUGH[[clang::fallthrough]];
4420 case ICmpInst::ICMP_SGT:
4421 case ICmpInst::ICMP_SGE:
4422 // a >s b ? a+x : b+x -> smax(a, b)+x
4423 // a >s b ? b+x : a+x -> smin(a, b)+x
4424 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4425 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4426 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4427 const SCEV *LA = getSCEV(TrueVal);
4428 const SCEV *RA = getSCEV(FalseVal);
4429 const SCEV *LDiff = getMinusSCEV(LA, LS);
4430 const SCEV *RDiff = getMinusSCEV(RA, RS);
4431 if (LDiff == RDiff)
4432 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4433 LDiff = getMinusSCEV(LA, RS);
4434 RDiff = getMinusSCEV(RA, LS);
4435 if (LDiff == RDiff)
4436 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4437 }
4438 break;
4439 case ICmpInst::ICMP_ULT:
4440 case ICmpInst::ICMP_ULE:
4441 std::swap(LHS, RHS);
4442 LLVM_FALLTHROUGH[[clang::fallthrough]];
4443 case ICmpInst::ICMP_UGT:
4444 case ICmpInst::ICMP_UGE:
4445 // a >u b ? a+x : b+x -> umax(a, b)+x
4446 // a >u b ? b+x : a+x -> umin(a, b)+x
4447 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4448 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4449 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4450 const SCEV *LA = getSCEV(TrueVal);
4451 const SCEV *RA = getSCEV(FalseVal);
4452 const SCEV *LDiff = getMinusSCEV(LA, LS);
4453 const SCEV *RDiff = getMinusSCEV(RA, RS);
4454 if (LDiff == RDiff)
4455 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4456 LDiff = getMinusSCEV(LA, RS);
4457 RDiff = getMinusSCEV(RA, LS);
4458 if (LDiff == RDiff)
4459 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4460 }
4461 break;
4462 case ICmpInst::ICMP_NE:
4463 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4464 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4465 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4466 const SCEV *One = getOne(I->getType());
4467 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4468 const SCEV *LA = getSCEV(TrueVal);
4469 const SCEV *RA = getSCEV(FalseVal);
4470 const SCEV *LDiff = getMinusSCEV(LA, LS);
4471 const SCEV *RDiff = getMinusSCEV(RA, One);
4472 if (LDiff == RDiff)
4473 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4474 }
4475 break;
4476 case ICmpInst::ICMP_EQ:
4477 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4478 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4479 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4480 const SCEV *One = getOne(I->getType());
4481 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4482 const SCEV *LA = getSCEV(TrueVal);
4483 const SCEV *RA = getSCEV(FalseVal);
4484 const SCEV *LDiff = getMinusSCEV(LA, One);
4485 const SCEV *RDiff = getMinusSCEV(RA, LS);
4486 if (LDiff == RDiff)
4487 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4488 }
4489 break;
4490 default:
4491 break;
4492 }
4493
4494 return getUnknown(I);
4495}
4496
4497/// Expand GEP instructions into add and multiply operations. This allows them
4498/// to be analyzed by regular SCEV code.
4499const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4500 // Don't attempt to analyze GEPs over unsized objects.
4501 if (!GEP->getSourceElementType()->isSized())
4502 return getUnknown(GEP);
4503
4504 SmallVector<const SCEV *, 4> IndexExprs;
4505 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4506 IndexExprs.push_back(getSCEV(*Index));
4507 return getGEPExpr(GEP, IndexExprs);
4508}
4509
4510uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4511 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4512 return C->getAPInt().countTrailingZeros();
4513
4514 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4515 return std::min(GetMinTrailingZeros(T->getOperand()),
4516 (uint32_t)getTypeSizeInBits(T->getType()));
4517
4518 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4519 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4520 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4521 ? getTypeSizeInBits(E->getType())
4522 : OpRes;
4523 }
4524
4525 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4526 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4527 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4528 ? getTypeSizeInBits(E->getType())
4529 : OpRes;
4530 }
4531
4532 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4533 // The result is the min of all operands results.
4534 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4535 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4536 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4537 return MinOpRes;
4538 }
4539
4540 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4541 // The result is the sum of all operands results.
4542 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4543 uint32_t BitWidth = getTypeSizeInBits(M->getType());
4544 for (unsigned i = 1, e = M->getNumOperands();
4545 SumOpRes != BitWidth && i != e; ++i)
4546 SumOpRes =
4547 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4548 return SumOpRes;
4549 }
4550
4551 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4552 // The result is the min of all operands results.
4553 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4554 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4555 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4556 return MinOpRes;
4557 }
4558
4559 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4560 // The result is the min of all operands results.
4561 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4562 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4563 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4564 return MinOpRes;
4565 }
4566
4567 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4568 // The result is the min of all operands results.
4569 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4570 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4571 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4572 return MinOpRes;
4573 }
4574
4575 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4576 // For a SCEVUnknown, ask ValueTracking.
4577 unsigned BitWidth = getTypeSizeInBits(U->getType());
4578 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4579 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4580 nullptr, &DT);
4581 return Zeros.countTrailingOnes();
4582 }
4583
4584 // SCEVUDivExpr
4585 return 0;
4586}
4587
4588uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4589 auto I = MinTrailingZerosCache.find(S);
4590 if (I != MinTrailingZerosCache.end())
4591 return I->second;
4592
4593 uint32_t Result = GetMinTrailingZerosImpl(S);
4594 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4595 assert(InsertPair.second && "Should insert a new key")((InsertPair.second && "Should insert a new key") ? static_cast
<void> (0) : __assert_fail ("InsertPair.second && \"Should insert a new key\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4595, __PRETTY_FUNCTION__))
;
4596 return InsertPair.first->second;
4597}
4598
4599/// Helper method to assign a range to V from metadata present in the IR.
4600static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4601 if (Instruction *I = dyn_cast<Instruction>(V))
4602 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4603 return getConstantRangeFromMetadata(*MD);
4604
4605 return None;
4606}
4607
4608/// Determine the range for a particular SCEV. If SignHint is
4609/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4610/// with a "cleaner" unsigned (resp. signed) representation.
4611ConstantRange
4612ScalarEvolution::getRange(const SCEV *S,
4613 ScalarEvolution::RangeSignHint SignHint) {
4614 DenseMap<const SCEV *, ConstantRange> &Cache =
4615 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4616 : SignedRanges;
4617
4618 // See if we've computed this range already.
4619 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4620 if (I != Cache.end())
4621 return I->second;
4622
4623 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4624 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4625
4626 unsigned BitWidth = getTypeSizeInBits(S->getType());
4627 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4628
4629 // If the value has known zeros, the maximum value will have those known zeros
4630 // as well.
4631 uint32_t TZ = GetMinTrailingZeros(S);
4632 if (TZ != 0) {
4633 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4634 ConservativeResult =
4635 ConstantRange(APInt::getMinValue(BitWidth),
4636 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4637 else
4638 ConservativeResult = ConstantRange(
4639 APInt::getSignedMinValue(BitWidth),
4640 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4641 }
4642
4643 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4644 ConstantRange X = getRange(Add->getOperand(0), SignHint);
4645 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4646 X = X.add(getRange(Add->getOperand(i), SignHint));
4647 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4648 }
4649
4650 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4651 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4652 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4653 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4654 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4655 }
4656
4657 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4658 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4659 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4660 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4661 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4662 }
4663
4664 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4665 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4666 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4667 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4668 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4669 }
4670
4671 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4672 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4673 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4674 return setRange(UDiv, SignHint,
4675 ConservativeResult.intersectWith(X.udiv(Y)));
4676 }
4677
4678 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4679 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4680 return setRange(ZExt, SignHint,
4681 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4682 }
4683
4684 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4685 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4686 return setRange(SExt, SignHint,
4687 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4688 }
4689
4690 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4691 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4692 return setRange(Trunc, SignHint,
4693 ConservativeResult.intersectWith(X.truncate(BitWidth)));
4694 }
4695
4696 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4697 // If there's no unsigned wrap, the value will never be less than its
4698 // initial value.
4699 if (AddRec->hasNoUnsignedWrap())
4700 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4701 if (!C->getValue()->isZero())
4702 ConservativeResult = ConservativeResult.intersectWith(
4703 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4704
4705 // If there's no signed wrap, and all the operands have the same sign or
4706 // zero, the value won't ever change sign.
4707 if (AddRec->hasNoSignedWrap()) {
4708 bool AllNonNeg = true;
4709 bool AllNonPos = true;
4710 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4711 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4712 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4713 }
4714 if (AllNonNeg)
4715 ConservativeResult = ConservativeResult.intersectWith(
4716 ConstantRange(APInt(BitWidth, 0),
4717 APInt::getSignedMinValue(BitWidth)));
4718 else if (AllNonPos)
4719 ConservativeResult = ConservativeResult.intersectWith(
4720 ConstantRange(APInt::getSignedMinValue(BitWidth),
4721 APInt(BitWidth, 1)));
4722 }
4723
4724 // TODO: non-affine addrec
4725 if (AddRec->isAffine()) {
4726 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4727 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4728 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4729 auto RangeFromAffine = getRangeForAffineAR(
4730 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4731 BitWidth);
4732 if (!RangeFromAffine.isFullSet())
4733 ConservativeResult =
4734 ConservativeResult.intersectWith(RangeFromAffine);
4735
4736 auto RangeFromFactoring = getRangeViaFactoring(
4737 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4738 BitWidth);
4739 if (!RangeFromFactoring.isFullSet())
4740 ConservativeResult =
4741 ConservativeResult.intersectWith(RangeFromFactoring);
4742 }
4743 }
4744
4745 return setRange(AddRec, SignHint, ConservativeResult);
4746 }
4747
4748 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4749 // Check if the IR explicitly contains !range metadata.
4750 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4751 if (MDRange.hasValue())
4752 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4753
4754 // Split here to avoid paying the compile-time cost of calling both
4755 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4756 // if needed.
4757 const DataLayout &DL = getDataLayout();
4758 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4759 // For a SCEVUnknown, ask ValueTracking.
4760 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4761 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4762 if (Ones != ~Zeros + 1)
4763 ConservativeResult =
4764 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4765 } else {
4766 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4767, __PRETTY_FUNCTION__))
4767 "generalize as needed!")((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4767, __PRETTY_FUNCTION__))
;
4768 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4769 if (NS > 1)
4770 ConservativeResult = ConservativeResult.intersectWith(
4771 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4772 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4773 }
4774
4775 return setRange(U, SignHint, ConservativeResult);
4776 }
4777
4778 return setRange(S, SignHint, ConservativeResult);
4779}
4780
4781// Given a StartRange, Step and MaxBECount for an expression compute a range of
4782// values that the expression can take. Initially, the expression has a value
4783// from StartRange and then is changed by Step up to MaxBECount times. Signed
4784// argument defines if we treat Step as signed or unsigned.
4785static ConstantRange getRangeForAffineARHelper(APInt Step,
4786 ConstantRange StartRange,
4787 APInt MaxBECount,
4788 unsigned BitWidth, bool Signed) {
4789 // If either Step or MaxBECount is 0, then the expression won't change, and we
4790 // just need to return the initial range.
4791 if (Step == 0 || MaxBECount == 0)
4792 return StartRange;
4793
4794 // If we don't know anything about the initial value (i.e. StartRange is
4795 // FullRange), then we don't know anything about the final range either.
4796 // Return FullRange.
4797 if (StartRange.isFullSet())
4798 return ConstantRange(BitWidth, /* isFullSet = */ true);
4799
4800 // If Step is signed and negative, then we use its absolute value, but we also
4801 // note that we're moving in the opposite direction.
4802 bool Descending = Signed && Step.isNegative();
4803
4804 if (Signed)
4805 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4806 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4807 // This equations hold true due to the well-defined wrap-around behavior of
4808 // APInt.
4809 Step = Step.abs();
4810
4811 // Check if Offset is more than full span of BitWidth. If it is, the
4812 // expression is guaranteed to overflow.
4813 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4814 return ConstantRange(BitWidth, /* isFullSet = */ true);
4815
4816 // Offset is by how much the expression can change. Checks above guarantee no
4817 // overflow here.
4818 APInt Offset = Step * MaxBECount;
4819
4820 // Minimum value of the final range will match the minimal value of StartRange
4821 // if the expression is increasing and will be decreased by Offset otherwise.
4822 // Maximum value of the final range will match the maximal value of StartRange
4823 // if the expression is decreasing and will be increased by Offset otherwise.
4824 APInt StartLower = StartRange.getLower();
4825 APInt StartUpper = StartRange.getUpper() - 1;
4826 APInt MovedBoundary =
4827 Descending ? (StartLower - Offset) : (StartUpper + Offset);
4828
4829 // It's possible that the new minimum/maximum value will fall into the initial
4830 // range (due to wrap around). This means that the expression can take any
4831 // value in this bitwidth, and we have to return full range.
4832 if (StartRange.contains(MovedBoundary))
4833 return ConstantRange(BitWidth, /* isFullSet = */ true);
4834
4835 APInt NewLower, NewUpper;
4836 if (Descending) {
4837 NewLower = MovedBoundary;
4838 NewUpper = StartUpper;
4839 } else {
4840 NewLower = StartLower;
4841 NewUpper = MovedBoundary;
4842 }
4843
4844 // If we end up with full range, return a proper full range.
4845 if (NewLower == NewUpper + 1)
4846 return ConstantRange(BitWidth, /* isFullSet = */ true);
4847
4848 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4849 return ConstantRange(NewLower, NewUpper + 1);
4850}
4851
4852ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4853 const SCEV *Step,
4854 const SCEV *MaxBECount,
4855 unsigned BitWidth) {
4856 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4858, __PRETTY_FUNCTION__))
4857 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4858, __PRETTY_FUNCTION__))
4858 "Precondition!")((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4858, __PRETTY_FUNCTION__))
;
4859
4860 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4861 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4862 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4863
4864 // First, consider step signed.
4865 ConstantRange StartSRange = getSignedRange(Start);
4866 ConstantRange StepSRange = getSignedRange(Step);
4867
4868 // If Step can be both positive and negative, we need to find ranges for the
4869 // maximum absolute step values in both directions and union them.
4870 ConstantRange SR =
4871 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4872 MaxBECountValue, BitWidth, /* Signed = */ true);
4873 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4874 StartSRange, MaxBECountValue,
4875 BitWidth, /* Signed = */ true));
4876
4877 // Next, consider step unsigned.
4878 ConstantRange UR = getRangeForAffineARHelper(
4879 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4880 MaxBECountValue, BitWidth, /* Signed = */ false);
4881
4882 // Finally, intersect signed and unsigned ranges.
4883 return SR.intersectWith(UR);
4884}
4885
4886ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4887 const SCEV *Step,
4888 const SCEV *MaxBECount,
4889 unsigned BitWidth) {
4890 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4891 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4892
4893 struct SelectPattern {
4894 Value *Condition = nullptr;
4895 APInt TrueValue;
4896 APInt FalseValue;
4897
4898 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4899 const SCEV *S) {
4900 Optional<unsigned> CastOp;
4901 APInt Offset(BitWidth, 0);
4902
4903 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&((SE.getTypeSizeInBits(S->getType()) == BitWidth &&
"Should be!") ? static_cast<void> (0) : __assert_fail (
"SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4904, __PRETTY_FUNCTION__))
4904 "Should be!")((SE.getTypeSizeInBits(S->getType()) == BitWidth &&
"Should be!") ? static_cast<void> (0) : __assert_fail (
"SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4904, __PRETTY_FUNCTION__))
;
4905
4906 // Peel off a constant offset:
4907 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4908 // In the future we could consider being smarter here and handle
4909 // {Start+Step,+,Step} too.
4910 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4911 return;
4912
4913 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4914 S = SA->getOperand(1);
4915 }
4916
4917 // Peel off a cast operation
4918 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4919 CastOp = SCast->getSCEVType();
4920 S = SCast->getOperand();
4921 }
4922
4923 using namespace llvm::PatternMatch;
4924
4925 auto *SU = dyn_cast<SCEVUnknown>(S);
4926 const APInt *TrueVal, *FalseVal;
4927 if (!SU ||
4928 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4929 m_APInt(FalseVal)))) {
4930 Condition = nullptr;
4931 return;
4932 }
4933
4934 TrueValue = *TrueVal;
4935 FalseValue = *FalseVal;
4936
4937 // Re-apply the cast we peeled off earlier
4938 if (CastOp.hasValue())
4939 switch (*CastOp) {
4940 default:
4941 llvm_unreachable("Unknown SCEV cast type!")::llvm::llvm_unreachable_internal("Unknown SCEV cast type!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 4941)
;
4942
4943 case scTruncate:
4944 TrueValue = TrueValue.trunc(BitWidth);
4945 FalseValue = FalseValue.trunc(BitWidth);
4946 break;
4947 case scZeroExtend:
4948 TrueValue = TrueValue.zext(BitWidth);
4949 FalseValue = FalseValue.zext(BitWidth);
4950 break;
4951 case scSignExtend:
4952 TrueValue = TrueValue.sext(BitWidth);
4953 FalseValue = FalseValue.sext(BitWidth);
4954 break;
4955 }
4956
4957 // Re-apply the constant offset we peeled off earlier
4958 TrueValue += Offset;
4959 FalseValue += Offset;
4960 }
4961
4962 bool isRecognized() { return Condition != nullptr; }
4963 };
4964
4965 SelectPattern StartPattern(*this, BitWidth, Start);
4966 if (!StartPattern.isRecognized())
4967 return ConstantRange(BitWidth, /* isFullSet = */ true);
4968
4969 SelectPattern StepPattern(*this, BitWidth, Step);
4970 if (!StepPattern.isRecognized())
4971 return ConstantRange(BitWidth, /* isFullSet = */ true);
4972
4973 if (StartPattern.Condition != StepPattern.Condition) {
4974 // We don't handle this case today; but we could, by considering four
4975 // possibilities below instead of two. I'm not sure if there are cases where
4976 // that will help over what getRange already does, though.
4977 return ConstantRange(BitWidth, /* isFullSet = */ true);
4978 }
4979
4980 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4981 // construct arbitrary general SCEV expressions here. This function is called
4982 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4983 // say) can end up caching a suboptimal value.
4984
4985 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4986 // C2352 and C2512 (otherwise it isn't needed).
4987
4988 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4989 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4990 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4991 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4992
4993 ConstantRange TrueRange =
4994 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4995 ConstantRange FalseRange =
4996 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4997
4998 return TrueRange.unionWith(FalseRange);
4999}
5000
5001SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5002 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5003 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5004
5005 // Return early if there are no flags to propagate to the SCEV.
5006 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5007 if (BinOp->hasNoUnsignedWrap())
5008 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5009 if (BinOp->hasNoSignedWrap())
5010 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5011 if (Flags == SCEV::FlagAnyWrap)
5012 return SCEV::FlagAnyWrap;
5013
5014 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5015}
5016
5017bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5018 // Here we check that I is in the header of the innermost loop containing I,
5019 // since we only deal with instructions in the loop header. The actual loop we
5020 // need to check later will come from an add recurrence, but getting that
5021 // requires computing the SCEV of the operands, which can be expensive. This
5022 // check we can do cheaply to rule out some cases early.
5023 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5024 if (InnermostContainingLoop == nullptr ||
5025 InnermostContainingLoop->getHeader() != I->getParent())
5026 return false;
5027
5028 // Only proceed if we can prove that I does not yield poison.
5029 if (!isKnownNotFullPoison(I)) return false;
5030
5031 // At this point we know that if I is executed, then it does not wrap
5032 // according to at least one of NSW or NUW. If I is not executed, then we do
5033 // not know if the calculation that I represents would wrap. Multiple
5034 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5035 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5036 // derived from other instructions that map to the same SCEV. We cannot make
5037 // that guarantee for cases where I is not executed. So we need to find the
5038 // loop that I is considered in relation to and prove that I is executed for
5039 // every iteration of that loop. That implies that the value that I
5040 // calculates does not wrap anywhere in the loop, so then we can apply the
5041 // flags to the SCEV.
5042 //
5043 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5044 // from different loops, so that we know which loop to prove that I is
5045 // executed in.
5046 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5047 // I could be an extractvalue from a call to an overflow intrinsic.
5048 // TODO: We can do better here in some cases.
5049 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5050 return false;
5051 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5052 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5053 bool AllOtherOpsLoopInvariant = true;
5054 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5055 ++OtherOpIndex) {
5056 if (OtherOpIndex != OpIndex) {
5057 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5058 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5059 AllOtherOpsLoopInvariant = false;
5060 break;
5061 }
5062 }
5063 }
5064 if (AllOtherOpsLoopInvariant &&
5065 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5066 return true;
5067 }
5068 }
5069 return false;
5070}
5071
5072bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5073 // If we know that \c I can never be poison period, then that's enough.
5074 if (isSCEVExprNeverPoison(I))
5075 return true;
5076
5077 // For an add recurrence specifically, we assume that infinite loops without
5078 // side effects are undefined behavior, and then reason as follows:
5079 //
5080 // If the add recurrence is poison in any iteration, it is poison on all
5081 // future iterations (since incrementing poison yields poison). If the result
5082 // of the add recurrence is fed into the loop latch condition and the loop
5083 // does not contain any throws or exiting blocks other than the latch, we now
5084 // have the ability to "choose" whether the backedge is taken or not (by
5085 // choosing a sufficiently evil value for the poison feeding into the branch)
5086 // for every iteration including and after the one in which \p I first became
5087 // poison. There are two possibilities (let's call the iteration in which \p
5088 // I first became poison as K):
5089 //
5090 // 1. In the set of iterations including and after K, the loop body executes
5091 // no side effects. In this case executing the backege an infinte number
5092 // of times will yield undefined behavior.
5093 //
5094 // 2. In the set of iterations including and after K, the loop body executes
5095 // at least one side effect. In this case, that specific instance of side
5096 // effect is control dependent on poison, which also yields undefined
5097 // behavior.
5098
5099 auto *ExitingBB = L->getExitingBlock();
5100 auto *LatchBB = L->getLoopLatch();
5101 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5102 return false;
5103
5104 SmallPtrSet<const Instruction *, 16> Pushed;
5105 SmallVector<const Instruction *, 8> PoisonStack;
5106
5107 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5108 // things that are known to be fully poison under that assumption go on the
5109 // PoisonStack.
5110 Pushed.insert(I);
5111 PoisonStack.push_back(I);
5112
5113 bool LatchControlDependentOnPoison = false;
5114 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5115 const Instruction *Poison = PoisonStack.pop_back_val();
5116
5117 for (auto *PoisonUser : Poison->users()) {
5118 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5119 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5120 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5121 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5122 assert(BI->isConditional() && "Only possibility!")((BI->isConditional() && "Only possibility!") ? static_cast
<void> (0) : __assert_fail ("BI->isConditional() && \"Only possibility!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5122, __PRETTY_FUNCTION__))
;
5123 if (BI->getParent() == LatchBB) {
5124 LatchControlDependentOnPoison = true;
5125 break;
5126 }
5127 }
5128 }
5129 }
5130
5131 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5132}
5133
5134ScalarEvolution::LoopProperties
5135ScalarEvolution::getLoopProperties(const Loop *L) {
5136 typedef ScalarEvolution::LoopProperties LoopProperties;
5137
5138 auto Itr = LoopPropertiesCache.find(L);
5139 if (Itr == LoopPropertiesCache.end()) {
5140 auto HasSideEffects = [](Instruction *I) {
5141 if (auto *SI = dyn_cast<StoreInst>(I))
5142 return !SI->isSimple();
5143
5144 return I->mayHaveSideEffects();
5145 };
5146
5147 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5148 /*HasNoSideEffects*/ true};
5149
5150 for (auto *BB : L->getBlocks())
5151 for (auto &I : *BB) {
5152 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5153 LP.HasNoAbnormalExits = false;
5154 if (HasSideEffects(&I))
5155 LP.HasNoSideEffects = false;
5156 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5157 break; // We're already as pessimistic as we can get.
5158 }
5159
5160 auto InsertPair = LoopPropertiesCache.insert({L, LP});
5161 assert(InsertPair.second && "We just checked!")((InsertPair.second && "We just checked!") ? static_cast
<void> (0) : __assert_fail ("InsertPair.second && \"We just checked!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5161, __PRETTY_FUNCTION__))
;
5162 Itr = InsertPair.first;
5163 }
5164
5165 return Itr->second;
5166}
5167
5168const SCEV *ScalarEvolution::createSCEV(Value *V) {
5169 if (!isSCEVable(V->getType()))
5170 return getUnknown(V);
5171
5172 if (Instruction *I = dyn_cast<Instruction>(V)) {
5173 // Don't attempt to analyze instructions in blocks that aren't
5174 // reachable. Such instructions don't matter, and they aren't required
5175 // to obey basic rules for definitions dominating uses which this
5176 // analysis depends on.
5177 if (!DT.isReachableFromEntry(I->getParent()))
5178 return getUnknown(V);
5179 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5180 return getConstant(CI);
5181 else if (isa<ConstantPointerNull>(V))
5182 return getZero(V->getType());
5183 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5184 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5185 else if (!isa<ConstantExpr>(V))
5186 return getUnknown(V);
5187
5188 Operator *U = cast<Operator>(V);
5189 if (auto BO = MatchBinaryOp(U, DT)) {
5190 switch (BO->Opcode) {
5191 case Instruction::Add: {
5192 // The simple thing to do would be to just call getSCEV on both operands
5193 // and call getAddExpr with the result. However if we're looking at a
5194 // bunch of things all added together, this can be quite inefficient,
5195 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5196 // Instead, gather up all the operands and make a single getAddExpr call.
5197 // LLVM IR canonical form means we need only traverse the left operands.
5198 SmallVector<const SCEV *, 4> AddOps;
5199 do {
5200 if (BO->Op) {
5201 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5202 AddOps.push_back(OpSCEV);
5203 break;
5204 }
5205
5206 // If a NUW or NSW flag can be applied to the SCEV for this
5207 // addition, then compute the SCEV for this addition by itself
5208 // with a separate call to getAddExpr. We need to do that
5209 // instead of pushing the operands of the addition onto AddOps,
5210 // since the flags are only known to apply to this particular
5211 // addition - they may not apply to other additions that can be
5212 // formed with operands from AddOps.
5213 const SCEV *RHS = getSCEV(BO->RHS);
5214 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5215 if (Flags != SCEV::FlagAnyWrap) {
5216 const SCEV *LHS = getSCEV(BO->LHS);
5217 if (BO->Opcode == Instruction::Sub)
5218 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5219 else
5220 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5221 break;
5222 }
5223 }
5224
5225 if (BO->Opcode == Instruction::Sub)
5226 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5227 else
5228 AddOps.push_back(getSCEV(BO->RHS));
5229
5230 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5231 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5232 NewBO->Opcode != Instruction::Sub)) {
5233 AddOps.push_back(getSCEV(BO->LHS));
5234 break;
5235 }
5236 BO = NewBO;
5237 } while (true);
5238
5239 return getAddExpr(AddOps);
5240 }
5241
5242 case Instruction::Mul: {
5243 SmallVector<const SCEV *, 4> MulOps;
5244 do {
5245 if (BO->Op) {
5246 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5247 MulOps.push_back(OpSCEV);
5248 break;
5249 }
5250
5251 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5252 if (Flags != SCEV::FlagAnyWrap) {
5253 MulOps.push_back(
5254 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5255 break;
5256 }
5257 }
5258
5259 MulOps.push_back(getSCEV(BO->RHS));
5260 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5261 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5262 MulOps.push_back(getSCEV(BO->LHS));
5263 break;
5264 }
5265 BO = NewBO;
5266 } while (true);
5267
5268 return getMulExpr(MulOps);
5269 }
5270 case Instruction::UDiv:
5271 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5272 case Instruction::Sub: {
5273 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5274 if (BO->Op)
5275 Flags = getNoWrapFlagsFromUB(BO->Op);
5276 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5277 }
5278 case Instruction::And:
5279 // For an expression like x&255 that merely masks off the high bits,
5280 // use zext(trunc(x)) as the SCEV expression.
5281 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5282 if (CI->isNullValue())
5283 return getSCEV(BO->RHS);
5284 if (CI->isAllOnesValue())
5285 return getSCEV(BO->LHS);
5286 const APInt &A = CI->getValue();
5287
5288 // Instcombine's ShrinkDemandedConstant may strip bits out of
5289 // constants, obscuring what would otherwise be a low-bits mask.
5290 // Use computeKnownBits to compute what ShrinkDemandedConstant
5291 // knew about to reconstruct a low-bits mask value.
5292 unsigned LZ = A.countLeadingZeros();
5293 unsigned TZ = A.countTrailingZeros();
5294 unsigned BitWidth = A.getBitWidth();
5295 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5296 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5297 0, &AC, nullptr, &DT);
5298
5299 APInt EffectiveMask =
5300 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5301 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5302 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5303 const SCEV *LHS = getSCEV(BO->LHS);
5304 const SCEV *ShiftedLHS = nullptr;
5305 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5306 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5307 // For an expression like (x * 8) & 8, simplify the multiply.
5308 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5309 unsigned GCD = std::min(MulZeros, TZ);
5310 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5311 SmallVector<const SCEV*, 4> MulOps;
5312 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5313 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5314 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5315 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5316 }
5317 }
5318 if (!ShiftedLHS)
5319 ShiftedLHS = getUDivExpr(LHS, MulCount);
5320 return getMulExpr(
5321 getZeroExtendExpr(
5322 getTruncateExpr(ShiftedLHS,
5323 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5324 BO->LHS->getType()),
5325 MulCount);
5326 }
5327 }
5328 break;
5329
5330 case Instruction::Or:
5331 // If the RHS of the Or is a constant, we may have something like:
5332 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5333 // optimizations will transparently handle this case.
5334 //
5335 // In order for this transformation to be safe, the LHS must be of the
5336 // form X*(2^n) and the Or constant must be less than 2^n.
5337 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5338 const SCEV *LHS = getSCEV(BO->LHS);
5339 const APInt &CIVal = CI->getValue();
5340 if (GetMinTrailingZeros(LHS) >=
5341 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5342 // Build a plain add SCEV.
5343 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5344 // If the LHS of the add was an addrec and it has no-wrap flags,
5345 // transfer the no-wrap flags, since an or won't introduce a wrap.
5346 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5347 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5348 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5349 OldAR->getNoWrapFlags());
5350 }
5351 return S;
5352 }
5353 }
5354 break;
5355
5356 case Instruction::Xor:
5357 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5358 // If the RHS of xor is -1, then this is a not operation.
5359 if (CI->isAllOnesValue())
5360 return getNotSCEV(getSCEV(BO->LHS));
5361
5362 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5363 // This is a variant of the check for xor with -1, and it handles
5364 // the case where instcombine has trimmed non-demanded bits out
5365 // of an xor with -1.
5366 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5367 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5368 if (LBO->getOpcode() == Instruction::And &&
5369 LCI->getValue() == CI->getValue())
5370 if (const SCEVZeroExtendExpr *Z =
5371 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5372 Type *UTy = BO->LHS->getType();
5373 const SCEV *Z0 = Z->getOperand();
5374 Type *Z0Ty = Z0->getType();
5375 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5376
5377 // If C is a low-bits mask, the zero extend is serving to
5378 // mask off the high bits. Complement the operand and
5379 // re-apply the zext.
5380 if (CI->getValue().isMask(Z0TySize))
5381 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5382
5383 // If C is a single bit, it may be in the sign-bit position
5384 // before the zero-extend. In this case, represent the xor
5385 // using an add, which is equivalent, and re-apply the zext.
5386 APInt Trunc = CI->getValue().trunc(Z0TySize);
5387 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5388 Trunc.isSignMask())
5389 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5390 UTy);
5391 }
5392 }
5393 break;
5394
5395 case Instruction::Shl:
5396 // Turn shift left of a constant amount into a multiply.
5397 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5398 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5399
5400 // If the shift count is not less than the bitwidth, the result of
5401 // the shift is undefined. Don't try to analyze it, because the
5402 // resolution chosen here may differ from the resolution chosen in
5403 // other parts of the compiler.
5404 if (SA->getValue().uge(BitWidth))
5405 break;
5406
5407 // It is currently not resolved how to interpret NSW for left
5408 // shift by BitWidth - 1, so we avoid applying flags in that
5409 // case. Remove this check (or this comment) once the situation
5410 // is resolved. See
5411 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5412 // and http://reviews.llvm.org/D8890 .
5413 auto Flags = SCEV::FlagAnyWrap;
5414 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5415 Flags = getNoWrapFlagsFromUB(BO->Op);
5416
5417 Constant *X = ConstantInt::get(getContext(),
5418 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5419 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5420 }
5421 break;
5422
5423 case Instruction::AShr:
5424 // AShr X, C, where C is a constant.
5425 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5426 if (!CI)
5427 break;
5428
5429 Type *OuterTy = BO->LHS->getType();
5430 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5431 // If the shift count is not less than the bitwidth, the result of
5432 // the shift is undefined. Don't try to analyze it, because the
5433 // resolution chosen here may differ from the resolution chosen in
5434 // other parts of the compiler.
5435 if (CI->getValue().uge(BitWidth))
5436 break;
5437
5438 if (CI->isNullValue())
5439 return getSCEV(BO->LHS); // shift by zero --> noop
5440
5441 uint64_t AShrAmt = CI->getZExtValue();
5442 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5443
5444 Operator *L = dyn_cast<Operator>(BO->LHS);
5445 if (L && L->getOpcode() == Instruction::Shl) {
5446 // X = Shl A, n
5447 // Y = AShr X, m
5448 // Both n and m are constant.
5449
5450 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5451 if (L->getOperand(1) == BO->RHS)
5452 // For a two-shift sext-inreg, i.e. n = m,
5453 // use sext(trunc(x)) as the SCEV expression.
5454 return getSignExtendExpr(
5455 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5456
5457 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5458 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5459 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5460 if (ShlAmt > AShrAmt) {
5461 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5462 // expression. We already checked that ShlAmt < BitWidth, so
5463 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5464 // ShlAmt - AShrAmt < Amt.
5465 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5466 ShlAmt - AShrAmt);
5467 return getSignExtendExpr(
5468 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5469 getConstant(Mul)), OuterTy);
5470 }
5471 }
5472 }
5473 break;
5474 }
5475 }
5476
5477 switch (U->getOpcode()) {
5478 case Instruction::Trunc:
5479 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5480
5481 case Instruction::ZExt:
5482 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5483
5484 case Instruction::SExt:
5485 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5486
5487 case Instruction::BitCast:
5488 // BitCasts are no-op casts so we just eliminate the cast.
5489 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5490 return getSCEV(U->getOperand(0));
5491 break;
5492
5493 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5494 // lead to pointer expressions which cannot safely be expanded to GEPs,
5495 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5496 // simplifying integer expressions.
5497
5498 case Instruction::GetElementPtr:
5499 return createNodeForGEP(cast<GEPOperator>(U));
5500
5501 case Instruction::PHI:
5502 return createNodeForPHI(cast<PHINode>(U));
5503
5504 case Instruction::Select:
5505 // U can also be a select constant expr, which let fall through. Since
5506 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5507 // constant expressions cannot have instructions as operands, we'd have
5508 // returned getUnknown for a select constant expressions anyway.
5509 if (isa<Instruction>(U))
5510 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5511 U->getOperand(1), U->getOperand(2));
5512 break;
5513
5514 case Instruction::Call:
5515 case Instruction::Invoke:
5516 if (Value *RV = CallSite(U).getReturnedArgOperand())
5517 return getSCEV(RV);
5518 break;
5519 }
5520
5521 return getUnknown(V);
5522}
5523
5524
5525
5526//===----------------------------------------------------------------------===//
5527// Iteration Count Computation Code
5528//
5529
5530static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5531 if (!ExitCount)
5532 return 0;
5533
5534 ConstantInt *ExitConst = ExitCount->getValue();
5535
5536 // Guard against huge trip counts.
5537 if (ExitConst->getValue().getActiveBits() > 32)
5538 return 0;
5539
5540 // In case of integer overflow, this returns 0, which is correct.
5541 return ((unsigned)ExitConst->getZExtValue()) + 1;
5542}
5543
5544unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5545 if (BasicBlock *ExitingBB = L->getExitingBlock())
5546 return getSmallConstantTripCount(L, ExitingBB);
5547
5548 // No trip count information for multiple exits.
5549 return 0;
5550}
5551
5552unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5553 BasicBlock *ExitingBlock) {
5554 assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!"
) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5554, __PRETTY_FUNCTION__))
;
5555 assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5556, __PRETTY_FUNCTION__))
5556 "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5556, __PRETTY_FUNCTION__))
;
5557 const SCEVConstant *ExitCount =
5558 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5559 return getConstantTripCount(ExitCount);
5560}
5561
5562unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5563 const auto *MaxExitCount =
5564 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5565 return getConstantTripCount(MaxExitCount);
5566}
5567
5568unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5569 if (BasicBlock *ExitingBB = L->getExitingBlock())
5570 return getSmallConstantTripMultiple(L, ExitingBB);
5571
5572 // No trip multiple information for multiple exits.
5573 return 0;
5574}
5575
5576/// Returns the largest constant divisor of the trip count of this loop as a
5577/// normal unsigned value, if possible. This means that the actual trip count is
5578/// always a multiple of the returned value (don't forget the trip count could
5579/// very well be zero as well!).
5580///
5581/// Returns 1 if the trip count is unknown or not guaranteed to be the
5582/// multiple of a constant (which is also the case if the trip count is simply
5583/// constant, use getSmallConstantTripCount for that case), Will also return 1
5584/// if the trip count is very large (>= 2^32).
5585///
5586/// As explained in the comments for getSmallConstantTripCount, this assumes
5587/// that control exits the loop via ExitingBlock.
5588unsigned
5589ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5590 BasicBlock *ExitingBlock) {
5591 assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!"
) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5591, __PRETTY_FUNCTION__))
;
5592 assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5593, __PRETTY_FUNCTION__))
5593 "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5593, __PRETTY_FUNCTION__))
;
5594 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5595 if (ExitCount == getCouldNotCompute())
5596 return 1;
5597
5598 // Get the trip count from the BE count by adding 1.
5599 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5600
5601 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5602 if (!TC)
5603 // Attempt to factor more general cases. Returns the greatest power of
5604 // two divisor. If overflow happens, the trip count expression is still
5605 // divisible by the greatest power of 2 divisor returned.
5606 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5607
5608 ConstantInt *Result = TC->getValue();
5609
5610 // Guard against huge trip counts (this requires checking
5611 // for zero to handle the case where the trip count == -1 and the
5612 // addition wraps).
5613 if (!Result || Result->getValue().getActiveBits() > 32 ||
5614 Result->getValue().getActiveBits() == 0)
5615 return 1;
5616
5617 return (unsigned)Result->getZExtValue();
5618}
5619
5620/// Get the expression for the number of loop iterations for which this loop is
5621/// guaranteed not to exit via ExitingBlock. Otherwise return
5622/// SCEVCouldNotCompute.
5623const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5624 BasicBlock *ExitingBlock) {
5625 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5626}
5627
5628const SCEV *
5629ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5630 SCEVUnionPredicate &Preds) {
5631 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5632}
5633
5634const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5635 return getBackedgeTakenInfo(L).getExact(this);
5636}
5637
5638/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5639/// known never to be less than the actual backedge taken count.
5640const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5641 return getBackedgeTakenInfo(L).getMax(this);
5642}
5643
5644bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5645 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5646}
5647
5648/// Push PHI nodes in the header of the given loop onto the given Worklist.
5649static void
5650PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5651 BasicBlock *Header = L->getHeader();
5652
5653 // Push all Loop-header PHIs onto the Worklist stack.
5654 for (BasicBlock::iterator I = Header->begin();
5655 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5656 Worklist.push_back(PN);
5657}
5658
5659const ScalarEvolution::BackedgeTakenInfo &
5660ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5661 auto &BTI = getBackedgeTakenInfo(L);
5662 if (BTI.hasFullInfo())
5663 return BTI;
5664
5665 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5666
5667 if (!Pair.second)
5668 return Pair.first->second;
5669
5670 BackedgeTakenInfo Result =
5671 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5672
5673 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5674}
5675
5676const ScalarEvolution::BackedgeTakenInfo &
5677ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5678 // Initially insert an invalid entry for this loop. If the insertion
5679 // succeeds, proceed to actually compute a backedge-taken count and
5680 // update the value. The temporary CouldNotCompute value tells SCEV
5681 // code elsewhere that it shouldn't attempt to request a new
5682 // backedge-taken count, which could result in infinite recursion.
5683 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5684 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5685 if (!Pair.second)
5686 return Pair.first->second;
5687
5688 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5689 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5690 // must be cleared in this scope.
5691 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5692
5693 if (Result.getExact(this) != getCouldNotCompute()) {
5694 assert(isLoopInvariant(Result.getExact(this), L) &&((isLoopInvariant(Result.getExact(this), L) && isLoopInvariant
(Result.getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5696, __PRETTY_FUNCTION__))
5695 isLoopInvariant(Result.getMax(this), L) &&((isLoopInvariant(Result.getExact(this), L) && isLoopInvariant
(Result.getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5696, __PRETTY_FUNCTION__))
5696 "Computed backedge-taken count isn't loop invariant for loop!")((isLoopInvariant(Result.getExact(this), L) && isLoopInvariant
(Result.getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5696, __PRETTY_FUNCTION__))
;
5697 ++NumTripCountsComputed;
5698 }
5699 else if (Result.getMax(this) == getCouldNotCompute() &&
5700 isa<PHINode>(L->getHeader()->begin())) {
5701 // Only count loops that have phi nodes as not being computable.
5702 ++NumTripCountsNotComputed;
5703 }
5704
5705 // Now that we know more about the trip count for this loop, forget any
5706 // existing SCEV values for PHI nodes in this loop since they are only
5707 // conservative estimates made without the benefit of trip count
5708 // information. This is similar to the code in forgetLoop, except that
5709 // it handles SCEVUnknown PHI nodes specially.
5710 if (Result.hasAnyInfo()) {
5711 SmallVector<Instruction *, 16> Worklist;
5712 PushLoopPHIs(L, Worklist);
5713
5714 SmallPtrSet<Instruction *, 8> Visited;
5715 while (!Worklist.empty()) {
5716 Instruction *I = Worklist.pop_back_val();
5717 if (!Visited.insert(I).second)
5718 continue;
5719
5720 ValueExprMapType::iterator It =
5721 ValueExprMap.find_as(static_cast<Value *>(I));
5722 if (It != ValueExprMap.end()) {
5723 const SCEV *Old = It->second;
5724
5725 // SCEVUnknown for a PHI either means that it has an unrecognized
5726 // structure, or it's a PHI that's in the progress of being computed
5727 // by createNodeForPHI. In the former case, additional loop trip
5728 // count information isn't going to change anything. In the later
5729 // case, createNodeForPHI will perform the necessary updates on its
5730 // own when it gets to that point.
5731 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5732 eraseValueFromMap(It->first);
5733 forgetMemoizedResults(Old);
5734 }
5735 if (PHINode *PN = dyn_cast<PHINode>(I))
5736 ConstantEvolutionLoopExitValue.erase(PN);
5737 }
5738
5739 PushDefUseChildren(I, Worklist);
5740 }
5741 }
5742
5743 // Re-lookup the insert position, since the call to
5744 // computeBackedgeTakenCount above could result in a
5745 // recusive call to getBackedgeTakenInfo (on a different
5746 // loop), which would invalidate the iterator computed
5747 // earlier.
5748 return BackedgeTakenCounts.find(L)->second = std::move(Result);
5749}
5750
5751void ScalarEvolution::forgetLoop(const Loop *L) {
5752 // Drop any stored trip count value.
5753 auto RemoveLoopFromBackedgeMap =
5754 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5755 auto BTCPos = Map.find(L);
5756 if (BTCPos != Map.end()) {
5757 BTCPos->second.clear();
5758 Map.erase(BTCPos);
5759 }
5760 };
5761
5762 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5763 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5764
5765 // Drop information about expressions based on loop-header PHIs.
5766 SmallVector<Instruction *, 16> Worklist;
5767 PushLoopPHIs(L, Worklist);
5768
5769 SmallPtrSet<Instruction *, 8> Visited;
5770 while (!Worklist.empty()) {
5771 Instruction *I = Worklist.pop_back_val();
5772 if (!Visited.insert(I).second)
5773 continue;
5774
5775 ValueExprMapType::iterator It =
5776 ValueExprMap.find_as(static_cast<Value *>(I));
5777 if (It != ValueExprMap.end()) {
5778 eraseValueFromMap(It->first);
5779 forgetMemoizedResults(It->second);
5780 if (PHINode *PN = dyn_cast<PHINode>(I))
5781 ConstantEvolutionLoopExitValue.erase(PN);
5782 }
5783
5784 PushDefUseChildren(I, Worklist);
5785 }
5786
5787 // Forget all contained loops too, to avoid dangling entries in the
5788 // ValuesAtScopes map.
5789 for (Loop *I : *L)
5790 forgetLoop(I);
5791
5792 LoopPropertiesCache.erase(L);
5793}
5794
5795void ScalarEvolution::forgetValue(Value *V) {
5796 Instruction *I = dyn_cast<Instruction>(V);
5797 if (!I) return;
5798
5799 // Drop information about expressions based on loop-header PHIs.
5800 SmallVector<Instruction *, 16> Worklist;
5801 Worklist.push_back(I);
5802
5803 SmallPtrSet<Instruction *, 8> Visited;
5804 while (!Worklist.empty()) {
5805 I = Worklist.pop_back_val();
5806 if (!Visited.insert(I).second)
5807 continue;
5808
5809 ValueExprMapType::iterator It =
5810 ValueExprMap.find_as(static_cast<Value *>(I));
5811 if (It != ValueExprMap.end()) {
5812 eraseValueFromMap(It->first);
5813 forgetMemoizedResults(It->second);
5814 if (PHINode *PN = dyn_cast<PHINode>(I))
5815 ConstantEvolutionLoopExitValue.erase(PN);
5816 }
5817
5818 PushDefUseChildren(I, Worklist);
5819 }
5820}
5821
5822/// Get the exact loop backedge taken count considering all loop exits. A
5823/// computable result can only be returned for loops with a single exit.
5824/// Returning the minimum taken count among all exits is incorrect because one
5825/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5826/// the limit of each loop test is never skipped. This is a valid assumption as
5827/// long as the loop exits via that test. For precise results, it is the
5828/// caller's responsibility to specify the relevant loop exit using
5829/// getExact(ExitingBlock, SE).
5830const SCEV *
5831ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5832 SCEVUnionPredicate *Preds) const {
5833 // If any exits were not computable, the loop is not computable.
5834 if (!isComplete() || ExitNotTaken.empty())
5835 return SE->getCouldNotCompute();
5836
5837 const SCEV *BECount = nullptr;
5838 for (auto &ENT : ExitNotTaken) {
5839 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV")((ENT.ExactNotTaken != SE->getCouldNotCompute() &&
"bad exit SCEV") ? static_cast<void> (0) : __assert_fail
("ENT.ExactNotTaken != SE->getCouldNotCompute() && \"bad exit SCEV\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5839, __PRETTY_FUNCTION__))
;
5840
5841 if (!BECount)
5842 BECount = ENT.ExactNotTaken;
5843 else if (BECount != ENT.ExactNotTaken)
5844 return SE->getCouldNotCompute();
5845 if (Preds && !ENT.hasAlwaysTruePredicate())
5846 Preds->add(ENT.Predicate.get());
5847
5848 assert((Preds || ENT.hasAlwaysTruePredicate()) &&(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!"
) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5849, __PRETTY_FUNCTION__))
5849 "Predicate should be always true!")(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!"
) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5849, __PRETTY_FUNCTION__))
;
5850 }
5851
5852 assert(BECount && "Invalid not taken count for loop exit")((BECount && "Invalid not taken count for loop exit")
? static_cast<void> (0) : __assert_fail ("BECount && \"Invalid not taken count for loop exit\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5852, __PRETTY_FUNCTION__))
;
5853 return BECount;
5854}
5855
5856/// Get the exact not taken count for this loop exit.
5857const SCEV *
5858ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5859 ScalarEvolution *SE) const {
5860 for (auto &ENT : ExitNotTaken)
5861 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5862 return ENT.ExactNotTaken;
5863
5864 return SE->getCouldNotCompute();
5865}
5866
5867/// getMax - Get the max backedge taken count for the loop.
5868const SCEV *
5869ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5870 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5871 return !ENT.hasAlwaysTruePredicate();
5872 };
5873
5874 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5875 return SE->getCouldNotCompute();
5876
5877 return getMax();
5878}
5879
5880bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5881 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5882 return !ENT.hasAlwaysTruePredicate();
5883 };
5884 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5885}
5886
5887bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5888 ScalarEvolution *SE) const {
5889 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5890 SE->hasOperand(getMax(), S))
5891 return true;
5892
5893 for (auto &ENT : ExitNotTaken)
5894 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5895 SE->hasOperand(ENT.ExactNotTaken, S))
5896 return true;
5897
5898 return false;
5899}
5900
5901/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5902/// computable exit into a persistent ExitNotTakenInfo array.
5903ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5904 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5905 &&ExitCounts,
5906 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5907 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5908 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5909 ExitNotTaken.reserve(ExitCounts.size());
5910 std::transform(
5911 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5912 [&](const EdgeExitInfo &EEI) {
5913 BasicBlock *ExitBB = EEI.first;
5914 const ExitLimit &EL = EEI.second;
5915 if (EL.Predicates.empty())
5916 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5917
5918 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5919 for (auto *Pred : EL.Predicates)
5920 Predicate->add(Pred);
5921
5922 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5923 });
5924}
5925
5926/// Invalidate this result and free the ExitNotTakenInfo array.
5927void ScalarEvolution::BackedgeTakenInfo::clear() {
5928 ExitNotTaken.clear();
5929}
5930
5931/// Compute the number of times the backedge of the specified loop will execute.
5932ScalarEvolution::BackedgeTakenInfo
5933ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5934 bool AllowPredicates) {
5935 SmallVector<BasicBlock *, 8> ExitingBlocks;
5936 L->getExitingBlocks(ExitingBlocks);
5937
5938 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5939
5940 SmallVector<EdgeExitInfo, 4> ExitCounts;
5941 bool CouldComputeBECount = true;
5942 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5943 const SCEV *MustExitMaxBECount = nullptr;
5944 const SCEV *MayExitMaxBECount = nullptr;
5945 bool MustExitMaxOrZero = false;
5946
5947 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5948 // and compute maxBECount.
5949 // Do a union of all the predicates here.
5950 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5951 BasicBlock *ExitBB = ExitingBlocks[i];
5952 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5953
5954 assert((AllowPredicates || EL.Predicates.empty()) &&(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!"
) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5955, __PRETTY_FUNCTION__))
5955 "Predicated exit limit when predicates are not allowed!")(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!"
) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 5955, __PRETTY_FUNCTION__))
;
5956
5957 // 1. For each exit that can be computed, add an entry to ExitCounts.
5958 // CouldComputeBECount is true only if all exits can be computed.
5959 if (EL.ExactNotTaken == getCouldNotCompute())
5960 // We couldn't compute an exact value for this exit, so
5961 // we won't be able to compute an exact value for the loop.
5962 CouldComputeBECount = false;
5963 else
5964 ExitCounts.emplace_back(ExitBB, EL);
5965
5966 // 2. Derive the loop's MaxBECount from each exit's max number of
5967 // non-exiting iterations. Partition the loop exits into two kinds:
5968 // LoopMustExits and LoopMayExits.
5969 //
5970 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5971 // is a LoopMayExit. If any computable LoopMustExit is found, then
5972 // MaxBECount is the minimum EL.MaxNotTaken of computable
5973 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5974 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5975 // computable EL.MaxNotTaken.
5976 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5977 DT.dominates(ExitBB, Latch)) {
5978 if (!MustExitMaxBECount) {
5979 MustExitMaxBECount = EL.MaxNotTaken;
5980 MustExitMaxOrZero = EL.MaxOrZero;
5981 } else {
5982 MustExitMaxBECount =
5983 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5984 }
5985 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5986 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5987 MayExitMaxBECount = EL.MaxNotTaken;
5988 else {
5989 MayExitMaxBECount =
5990 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5991 }
5992 }
5993 }
5994 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5995 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5996 // The loop backedge will be taken the maximum or zero times if there's
5997 // a single exit that must be taken the maximum or zero times.
5998 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
5999 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6000 MaxBECount, MaxOrZero);
6001}
6002
6003ScalarEvolution::ExitLimit
6004ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6005 bool AllowPredicates) {
6006
6007 // Okay, we've chosen an exiting block. See what condition causes us to exit
6008 // at this block and remember the exit block and whether all other targets
6009 // lead to the loop header.
6010 bool MustExecuteLoopHeader = true;
6011 BasicBlock *Exit = nullptr;
6012 for (auto *SBB : successors(ExitingBlock))
6013 if (!L->contains(SBB)) {
6014 if (Exit) // Multiple exit successors.
6015 return getCouldNotCompute();
6016 Exit = SBB;
6017 } else if (SBB != L->getHeader()) {
6018 MustExecuteLoopHeader = false;
6019 }
6020
6021 // At this point, we know we have a conditional branch that determines whether
6022 // the loop is exited. However, we don't know if the branch is executed each
6023 // time through the loop. If not, then the execution count of the branch will
6024 // not be equal to the trip count of the loop.
6025 //
6026 // Currently we check for this by checking to see if the Exit branch goes to
6027 // the loop header. If so, we know it will always execute the same number of
6028 // times as the loop. We also handle the case where the exit block *is* the
6029 // loop header. This is common for un-rotated loops.
6030 //
6031 // If both of those tests fail, walk up the unique predecessor chain to the
6032 // header, stopping if there is an edge that doesn't exit the loop. If the
6033 // header is reached, the execution count of the branch will be equal to the
6034 // trip count of the loop.
6035 //
6036 // More extensive analysis could be done to handle more cases here.
6037 //
6038 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6039 // The simple checks failed, try climbing the unique predecessor chain
6040 // up to the header.
6041 bool Ok = false;
6042 for (BasicBlock *BB = ExitingBlock; BB; ) {
6043 BasicBlock *Pred = BB->getUniquePredecessor();
6044 if (!Pred)
6045 return getCouldNotCompute();
6046 TerminatorInst *PredTerm = Pred->getTerminator();
6047 for (const BasicBlock *PredSucc : PredTerm->successors()) {
6048 if (PredSucc == BB)
6049 continue;
6050 // If the predecessor has a successor that isn't BB and isn't
6051 // outside the loop, assume the worst.
6052 if (L->contains(PredSucc))
6053 return getCouldNotCompute();
6054 }
6055 if (Pred == L->getHeader()) {
6056 Ok = true;
6057 break;
6058 }
6059 BB = Pred;
6060 }
6061 if (!Ok)
6062 return getCouldNotCompute();
6063 }
6064
6065 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6066 TerminatorInst *Term = ExitingBlock->getTerminator();
6067 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6068 assert(BI->isConditional() && "If unconditional, it can't be in loop!")((BI->isConditional() && "If unconditional, it can't be in loop!"
) ? static_cast<void> (0) : __assert_fail ("BI->isConditional() && \"If unconditional, it can't be in loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6068, __PRETTY_FUNCTION__))
;
6069 // Proceed to the next level to examine the exit condition expression.
6070 return computeExitLimitFromCond(
6071 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6072 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6073 }
6074
6075 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6076 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6077 /*ControlsExit=*/IsOnlyExit);
6078
6079 return getCouldNotCompute();
6080}
6081
6082ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6083 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6084 bool ControlsExit, bool AllowPredicates) {
6085 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6086 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6087 ControlsExit, AllowPredicates);
6088}
6089
6090Optional<ScalarEvolution::ExitLimit>
6091ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6092 BasicBlock *TBB, BasicBlock *FBB,
6093 bool ControlsExit, bool AllowPredicates) {
6094 (void)this->L;
6095 (void)this->TBB;
6096 (void)this->FBB;
6097 (void)this->AllowPredicates;
6098
6099 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6101, __PRETTY_FUNCTION__))
6100 this->AllowPredicates == AllowPredicates &&((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6101, __PRETTY_FUNCTION__))
6101 "Variance in assumed invariant key components!")((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6101, __PRETTY_FUNCTION__))
;
6102 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6103 if (Itr == TripCountMap.end())
6104 return None;
6105 return Itr->second;
6106}
6107
6108void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6109 BasicBlock *TBB, BasicBlock *FBB,
6110 bool ControlsExit,
6111 bool AllowPredicates,
6112 const ExitLimit &EL) {
6113 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6115, __PRETTY_FUNCTION__))
6114 this->AllowPredicates == AllowPredicates &&((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6115, __PRETTY_FUNCTION__))
6115 "Variance in assumed invariant key components!")((this->L == L && this->TBB == TBB && this
->FBB == FBB && this->AllowPredicates == AllowPredicates
&& "Variance in assumed invariant key components!") ?
static_cast<void> (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6115, __PRETTY_FUNCTION__))
;
6116
6117 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6118 assert(InsertResult.second && "Expected successful insertion!")((InsertResult.second && "Expected successful insertion!"
) ? static_cast<void> (0) : __assert_fail ("InsertResult.second && \"Expected successful insertion!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6118, __PRETTY_FUNCTION__))
;
6119 (void)InsertResult;
6120}
6121
6122ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6123 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6124 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6125
6126 if (auto MaybeEL =
6127 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6128 return *MaybeEL;
6129
6130 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6131 ControlsExit, AllowPredicates);
6132 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6133 return EL;
6134}
6135
6136ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6137 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6138 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6139 // Check if the controlling expression for this loop is an And or Or.
6140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6141 if (BO->getOpcode() == Instruction::And) {
6142 // Recurse on the operands of the and.
6143 bool EitherMayExit = L->contains(TBB);
6144 ExitLimit EL0 = computeExitLimitFromCondCached(
6145 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6146 AllowPredicates);
6147 ExitLimit EL1 = computeExitLimitFromCondCached(
6148 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6149 AllowPredicates);
6150 const SCEV *BECount = getCouldNotCompute();
6151 const SCEV *MaxBECount = getCouldNotCompute();
6152 if (EitherMayExit) {
6153 // Both conditions must be true for the loop to continue executing.
6154 // Choose the less conservative count.
6155 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6156 EL1.ExactNotTaken == getCouldNotCompute())
6157 BECount = getCouldNotCompute();
6158 else
6159 BECount =
6160 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6161 if (EL0.MaxNotTaken == getCouldNotCompute())
6162 MaxBECount = EL1.MaxNotTaken;
6163 else if (EL1.MaxNotTaken == getCouldNotCompute())
6164 MaxBECount = EL0.MaxNotTaken;
6165 else
6166 MaxBECount =
6167 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6168 } else {
6169 // Both conditions must be true at the same time for the loop to exit.
6170 // For now, be conservative.
6171 assert(L->contains(FBB) && "Loop block has no successor in loop!")((L->contains(FBB) && "Loop block has no successor in loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(FBB) && \"Loop block has no successor in loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6171, __PRETTY_FUNCTION__))
;
6172 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6173 MaxBECount = EL0.MaxNotTaken;
6174 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6175 BECount = EL0.ExactNotTaken;
6176 }
6177
6178 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6179 // to be more aggressive when computing BECount than when computing
6180 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6181 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6182 // to not.
6183 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6184 !isa<SCEVCouldNotCompute>(BECount))
6185 MaxBECount = BECount;
6186
6187 return ExitLimit(BECount, MaxBECount, false,
6188 {&EL0.Predicates, &EL1.Predicates});
6189 }
6190 if (BO->getOpcode() == Instruction::Or) {
6191 // Recurse on the operands of the or.
6192 bool EitherMayExit = L->contains(FBB);
6193 ExitLimit EL0 = computeExitLimitFromCondCached(
6194 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6195 AllowPredicates);
6196 ExitLimit EL1 = computeExitLimitFromCondCached(
6197 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6198 AllowPredicates);
6199 const SCEV *BECount = getCouldNotCompute();
6200 const SCEV *MaxBECount = getCouldNotCompute();
6201 if (EitherMayExit) {
6202 // Both conditions must be false for the loop to continue executing.
6203 // Choose the less conservative count.
6204 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6205 EL1.ExactNotTaken == getCouldNotCompute())
6206 BECount = getCouldNotCompute();
6207 else
6208 BECount =
6209 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6210 if (EL0.MaxNotTaken == getCouldNotCompute())
6211 MaxBECount = EL1.MaxNotTaken;
6212 else if (EL1.MaxNotTaken == getCouldNotCompute())
6213 MaxBECount = EL0.MaxNotTaken;
6214 else
6215 MaxBECount =
6216 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6217 } else {
6218 // Both conditions must be false at the same time for the loop to exit.
6219 // For now, be conservative.
6220 assert(L->contains(TBB) && "Loop block has no successor in loop!")((L->contains(TBB) && "Loop block has no successor in loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(TBB) && \"Loop block has no successor in loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6220, __PRETTY_FUNCTION__))
;
6221 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6222 MaxBECount = EL0.MaxNotTaken;
6223 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6224 BECount = EL0.ExactNotTaken;
6225 }
6226
6227 return ExitLimit(BECount, MaxBECount, false,
6228 {&EL0.Predicates, &EL1.Predicates});
6229 }
6230 }
6231
6232 // With an icmp, it may be feasible to compute an exact backedge-taken count.
6233 // Proceed to the next level to examine the icmp.
6234 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6235 ExitLimit EL =
6236 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6237 if (EL.hasFullInfo() || !AllowPredicates)
6238 return EL;
6239
6240 // Try again, but use SCEV predicates this time.
6241 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6242 /*AllowPredicates=*/true);
6243 }
6244
6245 // Check for a constant condition. These are normally stripped out by
6246 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6247 // preserve the CFG and is temporarily leaving constant conditions
6248 // in place.
6249 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6250 if (L->contains(FBB) == !CI->getZExtValue())
6251 // The backedge is always taken.
6252 return getCouldNotCompute();
6253 else
6254 // The backedge is never taken.
6255 return getZero(CI->getType());
6256 }
6257
6258 // If it's not an integer or pointer comparison then compute it the hard way.
6259 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6260}
6261
6262ScalarEvolution::ExitLimit
6263ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6264 ICmpInst *ExitCond,
6265 BasicBlock *TBB,
6266 BasicBlock *FBB,
6267 bool ControlsExit,
6268 bool AllowPredicates) {
6269
6270 // If the condition was exit on true, convert the condition to exit on false
6271 ICmpInst::Predicate Cond;
6272 if (!L->contains(FBB))
6273 Cond = ExitCond->getPredicate();
6274 else
6275 Cond = ExitCond->getInversePredicate();
6276
6277 // Handle common loops like: for (X = "string"; *X; ++X)
6278 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6279 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6280 ExitLimit ItCnt =
6281 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6282 if (ItCnt.hasAnyInfo())
6283 return ItCnt;
6284 }
6285
6286 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6287 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6288
6289 // Try to evaluate any dependencies out of the loop.
6290 LHS = getSCEVAtScope(LHS, L);
6291 RHS = getSCEVAtScope(RHS, L);
6292
6293 // At this point, we would like to compute how many iterations of the
6294 // loop the predicate will return true for these inputs.
6295 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6296 // If there is a loop-invariant, force it into the RHS.
6297 std::swap(LHS, RHS);
6298 Cond = ICmpInst::getSwappedPredicate(Cond);
6299 }
6300
6301 // Simplify the operands before analyzing them.
6302 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6303
6304 // If we have a comparison of a chrec against a constant, try to use value
6305 // ranges to answer this query.
6306 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6307 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6308 if (AddRec->getLoop() == L) {
6309 // Form the constant range.
6310 ConstantRange CompRange =
6311 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6312
6313 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6314 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6315 }
6316
6317 switch (Cond) {
6318 case ICmpInst::ICMP_NE: { // while (X != Y)
6319 // Convert to: while (X-Y != 0)
6320 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6321 AllowPredicates);
6322 if (EL.hasAnyInfo()) return EL;
6323 break;
6324 }
6325 case ICmpInst::ICMP_EQ: { // while (X == Y)
6326 // Convert to: while (X-Y == 0)
6327 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6328 if (EL.hasAnyInfo()) return EL;
6329 break;
6330 }
6331 case ICmpInst::ICMP_SLT:
6332 case ICmpInst::ICMP_ULT: { // while (X < Y)
6333 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6334 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6335 AllowPredicates);
6336 if (EL.hasAnyInfo()) return EL;
6337 break;
6338 }
6339 case ICmpInst::ICMP_SGT:
6340 case ICmpInst::ICMP_UGT: { // while (X > Y)
6341 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6342 ExitLimit EL =
6343 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6344 AllowPredicates);
6345 if (EL.hasAnyInfo()) return EL;
6346 break;
6347 }
6348 default:
6349 break;
6350 }
6351
6352 auto *ExhaustiveCount =
6353 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6354
6355 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6356 return ExhaustiveCount;
6357
6358 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6359 ExitCond->getOperand(1), L, Cond);
6360}
6361
6362ScalarEvolution::ExitLimit
6363ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6364 SwitchInst *Switch,
6365 BasicBlock *ExitingBlock,
6366 bool ControlsExit) {
6367 assert(!L->contains(ExitingBlock) && "Not an exiting block!")((!L->contains(ExitingBlock) && "Not an exiting block!"
) ? static_cast<void> (0) : __assert_fail ("!L->contains(ExitingBlock) && \"Not an exiting block!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6367, __PRETTY_FUNCTION__))
;
6368
6369 // Give up if the exit is the default dest of a switch.
6370 if (Switch->getDefaultDest() == ExitingBlock)
6371 return getCouldNotCompute();
6372
6373 assert(L->contains(Switch->getDefaultDest()) &&((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6374, __PRETTY_FUNCTION__))
6374 "Default case must not exit the loop!")((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6374, __PRETTY_FUNCTION__))
;
6375 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6376 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6377
6378 // while (X != Y) --> while (X-Y != 0)
6379 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6380 if (EL.hasAnyInfo())
6381 return EL;
6382
6383 return getCouldNotCompute();
6384}
6385
6386static ConstantInt *
6387EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6388 ScalarEvolution &SE) {
6389 const SCEV *InVal = SE.getConstant(C);
6390 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6391 assert(isa<SCEVConstant>(Val) &&((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6392, __PRETTY_FUNCTION__))
6392 "Evaluation of SCEV at constant didn't fold correctly?")((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6392, __PRETTY_FUNCTION__))
;
6393 return cast<SCEVConstant>(Val)->getValue();
6394}
6395
6396/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6397/// compute the backedge execution count.
6398ScalarEvolution::ExitLimit
6399ScalarEvolution::computeLoadConstantCompareExitLimit(
6400 LoadInst *LI,
6401 Constant *RHS,
6402 const Loop *L,
6403 ICmpInst::Predicate predicate) {
6404
6405 if (LI->isVolatile()) return getCouldNotCompute();
6406
6407 // Check to see if the loaded pointer is a getelementptr of a global.
6408 // TODO: Use SCEV instead of manually grubbing with GEPs.
6409 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6410 if (!GEP) return getCouldNotCompute();
6411
6412 // Make sure that it is really a constant global we are gepping, with an
6413 // initializer, and make sure the first IDX is really 0.
6414 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6415 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6416 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6417 !cast<Constant>(GEP->getOperand(1))->isNullValue())
6418 return getCouldNotCompute();
6419
6420 // Okay, we allow one non-constant index into the GEP instruction.
6421 Value *VarIdx = nullptr;
6422 std::vector<Constant*> Indexes;
6423 unsigned VarIdxNum = 0;
6424 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6425 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6426 Indexes.push_back(CI);
6427 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6428 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
6429 VarIdx = GEP->getOperand(i);
6430 VarIdxNum = i-2;
6431 Indexes.push_back(nullptr);
6432 }
6433
6434 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6435 if (!VarIdx)
6436 return getCouldNotCompute();
6437
6438 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6439 // Check to see if X is a loop variant variable value now.
6440 const SCEV *Idx = getSCEV(VarIdx);
6441 Idx = getSCEVAtScope(Idx, L);
6442
6443 // We can only recognize very limited forms of loop index expressions, in
6444 // particular, only affine AddRec's like {C1,+,C2}.
6445 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6446 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6447 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6448 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6449 return getCouldNotCompute();
6450
6451 unsigned MaxSteps = MaxBruteForceIterations;
6452 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6453 ConstantInt *ItCst = ConstantInt::get(
6454 cast<IntegerType>(IdxExpr->getType()), IterationNum);
6455 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6456
6457 // Form the GEP offset.
6458 Indexes[VarIdxNum] = Val;
6459
6460 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6461 Indexes);
6462 if (!Result) break; // Cannot compute!
6463
6464 // Evaluate the condition for this iteration.
6465 Result = ConstantExpr::getICmp(predicate, Result, RHS);
6466 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
6467 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6468 ++NumArrayLenItCounts;
6469 return getConstant(ItCst); // Found terminating iteration!
6470 }
6471 }
6472 return getCouldNotCompute();
6473}
6474
6475ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6476 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6477 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6478 if (!RHS)
6479 return getCouldNotCompute();
6480
6481 const BasicBlock *Latch = L->getLoopLatch();
6482 if (!Latch)
6483 return getCouldNotCompute();
6484
6485 const BasicBlock *Predecessor = L->getLoopPredecessor();
6486 if (!Predecessor)
6487 return getCouldNotCompute();
6488
6489 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6490 // Return LHS in OutLHS and shift_opt in OutOpCode.
6491 auto MatchPositiveShift =
6492 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6493
6494 using namespace PatternMatch;
6495
6496 ConstantInt *ShiftAmt;
6497 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6498 OutOpCode = Instruction::LShr;
6499 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6500 OutOpCode = Instruction::AShr;
6501 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6502 OutOpCode = Instruction::Shl;
6503 else
6504 return false;
6505
6506 return ShiftAmt->getValue().isStrictlyPositive();
6507 };
6508
6509 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6510 //
6511 // loop:
6512 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6513 // %iv.shifted = lshr i32 %iv, <positive constant>
6514 //
6515 // Return true on a successful match. Return the corresponding PHI node (%iv
6516 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6517 auto MatchShiftRecurrence =
6518 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6519 Optional<Instruction::BinaryOps> PostShiftOpCode;
6520
6521 {
6522 Instruction::BinaryOps OpC;
6523 Value *V;
6524
6525 // If we encounter a shift instruction, "peel off" the shift operation,
6526 // and remember that we did so. Later when we inspect %iv's backedge
6527 // value, we will make sure that the backedge value uses the same
6528 // operation.
6529 //
6530 // Note: the peeled shift operation does not have to be the same
6531 // instruction as the one feeding into the PHI's backedge value. We only
6532 // really care about it being the same *kind* of shift instruction --
6533 // that's all that is required for our later inferences to hold.
6534 if (MatchPositiveShift(LHS, V, OpC)) {
6535 PostShiftOpCode = OpC;
6536 LHS = V;
6537 }
6538 }
6539
6540 PNOut = dyn_cast<PHINode>(LHS);
6541 if (!PNOut || PNOut->getParent() != L->getHeader())
6542 return false;
6543
6544 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6545 Value *OpLHS;
6546
6547 return
6548 // The backedge value for the PHI node must be a shift by a positive
6549 // amount
6550 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6551
6552 // of the PHI node itself
6553 OpLHS == PNOut &&
6554
6555 // and the kind of shift should be match the kind of shift we peeled
6556 // off, if any.
6557 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6558 };
6559
6560 PHINode *PN;
6561 Instruction::BinaryOps OpCode;
6562 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6563 return getCouldNotCompute();
6564
6565 const DataLayout &DL = getDataLayout();
6566
6567 // The key rationale for this optimization is that for some kinds of shift
6568 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6569 // within a finite number of iterations. If the condition guarding the
6570 // backedge (in the sense that the backedge is taken if the condition is true)
6571 // is false for the value the shift recurrence stabilizes to, then we know
6572 // that the backedge is taken only a finite number of times.
6573
6574 ConstantInt *StableValue = nullptr;
6575 switch (OpCode) {
6576 default:
6577 llvm_unreachable("Impossible case!")::llvm::llvm_unreachable_internal("Impossible case!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6577)
;
6578
6579 case Instruction::AShr: {
6580 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6581 // bitwidth(K) iterations.
6582 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6583 bool KnownZero, KnownOne;
6584 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6585 Predecessor->getTerminator(), &DT);
6586 auto *Ty = cast<IntegerType>(RHS->getType());
6587 if (KnownZero)
6588 StableValue = ConstantInt::get(Ty, 0);
6589 else if (KnownOne)
6590 StableValue = ConstantInt::get(Ty, -1, true);
6591 else
6592 return getCouldNotCompute();
6593
6594 break;
6595 }
6596 case Instruction::LShr:
6597 case Instruction::Shl:
6598 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6599 // stabilize to 0 in at most bitwidth(K) iterations.
6600 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6601 break;
6602 }
6603
6604 auto *Result =
6605 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6606 assert(Result->getType()->isIntegerTy(1) &&((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction"
) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6607, __PRETTY_FUNCTION__))
6607 "Otherwise cannot be an operand to a branch instruction")((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction"
) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6607, __PRETTY_FUNCTION__))
;
6608
6609 if (Result->isZeroValue()) {
6610 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6611 const SCEV *UpperBound =
6612 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6613 return ExitLimit(getCouldNotCompute(), UpperBound, false);
6614 }
6615
6616 return getCouldNotCompute();
6617}
6618
6619/// Return true if we can constant fold an instruction of the specified type,
6620/// assuming that all operands were constants.
6621static bool CanConstantFold(const Instruction *I) {
6622 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6623 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6624 isa<LoadInst>(I))
6625 return true;
6626
6627 if (const CallInst *CI = dyn_cast<CallInst>(I))
6628 if (const Function *F = CI->getCalledFunction())
6629 return canConstantFoldCallTo(F);
6630 return false;
6631}
6632
6633/// Determine whether this instruction can constant evolve within this loop
6634/// assuming its operands can all constant evolve.
6635static bool canConstantEvolve(Instruction *I, const Loop *L) {
6636 // An instruction outside of the loop can't be derived from a loop PHI.
6637 if (!L->contains(I)) return false;
6638
6639 if (isa<PHINode>(I)) {
6640 // We don't currently keep track of the control flow needed to evaluate
6641 // PHIs, so we cannot handle PHIs inside of loops.
6642 return L->getHeader() == I->getParent();
6643 }
6644
6645 // If we won't be able to constant fold this expression even if the operands
6646 // are constants, bail early.
6647 return CanConstantFold(I);
6648}
6649
6650/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6651/// recursing through each instruction operand until reaching a loop header phi.
6652static PHINode *
6653getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6654 DenseMap<Instruction *, PHINode *> &PHIMap,
6655 unsigned Depth) {
6656 if (Depth > MaxConstantEvolvingDepth)
6657 return nullptr;
6658
6659 // Otherwise, we can evaluate this instruction if all of its operands are
6660 // constant or derived from a PHI node themselves.
6661 PHINode *PHI = nullptr;
6662 for (Value *Op : UseInst->operands()) {
6663 if (isa<Constant>(Op)) continue;
6664
6665 Instruction *OpInst = dyn_cast<Instruction>(Op);
6666 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6667
6668 PHINode *P = dyn_cast<PHINode>(OpInst);
6669 if (!P)
6670 // If this operand is already visited, reuse the prior result.
6671 // We may have P != PHI if this is the deepest point at which the
6672 // inconsistent paths meet.
6673 P = PHIMap.lookup(OpInst);
6674 if (!P) {
6675 // Recurse and memoize the results, whether a phi is found or not.
6676 // This recursive call invalidates pointers into PHIMap.
6677 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6678 PHIMap[OpInst] = P;
6679 }
6680 if (!P)
6681 return nullptr; // Not evolving from PHI
6682 if (PHI && PHI != P)
6683 return nullptr; // Evolving from multiple different PHIs.
6684 PHI = P;
6685 }
6686 // This is a expression evolving from a constant PHI!
6687 return PHI;
6688}
6689
6690/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6691/// in the loop that V is derived from. We allow arbitrary operations along the
6692/// way, but the operands of an operation must either be constants or a value
6693/// derived from a constant PHI. If this expression does not fit with these
6694/// constraints, return null.
6695static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6696 Instruction *I = dyn_cast<Instruction>(V);
6697 if (!I || !canConstantEvolve(I, L)) return nullptr;
6698
6699 if (PHINode *PN = dyn_cast<PHINode>(I))
6700 return PN;
6701
6702 // Record non-constant instructions contained by the loop.
6703 DenseMap<Instruction *, PHINode *> PHIMap;
6704 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6705}
6706
6707/// EvaluateExpression - Given an expression that passes the
6708/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6709/// in the loop has the value PHIVal. If we can't fold this expression for some
6710/// reason, return null.
6711static Constant *EvaluateExpression(Value *V, const Loop *L,
6712 DenseMap<Instruction *, Constant *> &Vals,
6713 const DataLayout &DL,
6714 const TargetLibraryInfo *TLI) {
6715 // Convenient constant check, but redundant for recursive calls.
6716 if (Constant *C = dyn_cast<Constant>(V)) return C;
6717 Instruction *I = dyn_cast<Instruction>(V);
6718 if (!I) return nullptr;
6719
6720 if (Constant *C = Vals.lookup(I)) return C;
6721
6722 // An instruction inside the loop depends on a value outside the loop that we
6723 // weren't given a mapping for, or a value such as a call inside the loop.
6724 if (!canConstantEvolve(I, L)) return nullptr;
6725
6726 // An unmapped PHI can be due to a branch or another loop inside this loop,
6727 // or due to this not being the initial iteration through a loop where we
6728 // couldn't compute the evolution of this particular PHI last time.
6729 if (isa<PHINode>(I)) return nullptr;
6730
6731 std::vector<Constant*> Operands(I->getNumOperands());
6732
6733 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6734 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6735 if (!Operand) {
6736 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6737 if (!Operands[i]) return nullptr;
6738 continue;
6739 }
6740 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6741 Vals[Operand] = C;
6742 if (!C) return nullptr;
6743 Operands[i] = C;
6744 }
6745
6746 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6747 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6748 Operands[1], DL, TLI);
6749 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6750 if (!LI->isVolatile())
6751 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6752 }
6753 return ConstantFoldInstOperands(I, Operands, DL, TLI);
6754}
6755
6756
6757// If every incoming value to PN except the one for BB is a specific Constant,
6758// return that, else return nullptr.
6759static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6760 Constant *IncomingVal = nullptr;
6761
6762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6763 if (PN->getIncomingBlock(i) == BB)
6764 continue;
6765
6766 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6767 if (!CurrentVal)
6768 return nullptr;
6769
6770 if (IncomingVal != CurrentVal) {
6771 if (IncomingVal)
6772 return nullptr;
6773 IncomingVal = CurrentVal;
6774 }
6775 }
6776
6777 return IncomingVal;
6778}
6779
6780/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6781/// in the header of its containing loop, we know the loop executes a
6782/// constant number of times, and the PHI node is just a recurrence
6783/// involving constants, fold it.
6784Constant *
6785ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6786 const APInt &BEs,
6787 const Loop *L) {
6788 auto I = ConstantEvolutionLoopExitValue.find(PN);
6789 if (I != ConstantEvolutionLoopExitValue.end())
6790 return I->second;
6791
6792 if (BEs.ugt(MaxBruteForceIterations))
6793 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
6794
6795 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6796
6797 DenseMap<Instruction *, Constant *> CurrentIterVals;
6798 BasicBlock *Header = L->getHeader();
6799 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6799, __PRETTY_FUNCTION__))
;
6800
6801 BasicBlock *Latch = L->getLoopLatch();
6802 if (!Latch)
6803 return nullptr;
6804
6805 for (auto &I : *Header) {
6806 PHINode *PHI = dyn_cast<PHINode>(&I);
6807 if (!PHI) break;
6808 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6809 if (!StartCST) continue;
6810 CurrentIterVals[PHI] = StartCST;
6811 }
6812 if (!CurrentIterVals.count(PN))
6813 return RetVal = nullptr;
6814
6815 Value *BEValue = PN->getIncomingValueForBlock(Latch);
6816
6817 // Execute the loop symbolically to determine the exit value.
6818 if (BEs.getActiveBits() >= 32)
6819 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6820
6821 unsigned NumIterations = BEs.getZExtValue(); // must be in range
6822 unsigned IterationNum = 0;
6823 const DataLayout &DL = getDataLayout();
6824 for (; ; ++IterationNum) {
6825 if (IterationNum == NumIterations)
6826 return RetVal = CurrentIterVals[PN]; // Got exit value!
6827
6828 // Compute the value of the PHIs for the next iteration.
6829 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6830 DenseMap<Instruction *, Constant *> NextIterVals;
6831 Constant *NextPHI =
6832 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6833 if (!NextPHI)
6834 return nullptr; // Couldn't evaluate!
6835 NextIterVals[PN] = NextPHI;
6836
6837 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6838
6839 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6840 // cease to be able to evaluate one of them or if they stop evolving,
6841 // because that doesn't necessarily prevent us from computing PN.
6842 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6843 for (const auto &I : CurrentIterVals) {
6844 PHINode *PHI = dyn_cast<PHINode>(I.first);
6845 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6846 PHIsToCompute.emplace_back(PHI, I.second);
6847 }
6848 // We use two distinct loops because EvaluateExpression may invalidate any
6849 // iterators into CurrentIterVals.
6850 for (const auto &I : PHIsToCompute) {
6851 PHINode *PHI = I.first;
6852 Constant *&NextPHI = NextIterVals[PHI];
6853 if (!NextPHI) { // Not already computed.
6854 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6855 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6856 }
6857 if (NextPHI != I.second)
6858 StoppedEvolving = false;
6859 }
6860
6861 // If all entries in CurrentIterVals == NextIterVals then we can stop
6862 // iterating, the loop can't continue to change.
6863 if (StoppedEvolving)
6864 return RetVal = CurrentIterVals[PN];
6865
6866 CurrentIterVals.swap(NextIterVals);
6867 }
6868}
6869
6870const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6871 Value *Cond,
6872 bool ExitWhen) {
6873 PHINode *PN = getConstantEvolvingPHI(Cond, L);
6874 if (!PN) return getCouldNotCompute();
6875
6876 // If the loop is canonicalized, the PHI will have exactly two entries.
6877 // That's the only form we support here.
6878 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6879
6880 DenseMap<Instruction *, Constant *> CurrentIterVals;
6881 BasicBlock *Header = L->getHeader();
6882 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6882, __PRETTY_FUNCTION__))
;
6883
6884 BasicBlock *Latch = L->getLoopLatch();
6885 assert(Latch && "Should follow from NumIncomingValues == 2!")((Latch && "Should follow from NumIncomingValues == 2!"
) ? static_cast<void> (0) : __assert_fail ("Latch && \"Should follow from NumIncomingValues == 2!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 6885, __PRETTY_FUNCTION__))
;
6886
6887 for (auto &I : *Header) {
6888 PHINode *PHI = dyn_cast<PHINode>(&I);
6889 if (!PHI)
6890 break;
6891 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6892 if (!StartCST) continue;
6893 CurrentIterVals[PHI] = StartCST;
6894 }
6895 if (!CurrentIterVals.count(PN))
6896 return getCouldNotCompute();
6897
6898 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6899 // the loop symbolically to determine when the condition gets a value of
6900 // "ExitWhen".
6901 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
6902 const DataLayout &DL = getDataLayout();
6903 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6904 auto *CondVal = dyn_cast_or_null<ConstantInt>(
6905 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6906
6907 // Couldn't symbolically evaluate.
6908 if (!CondVal) return getCouldNotCompute();
6909
6910 if (CondVal->getValue() == uint64_t(ExitWhen)) {
6911 ++NumBruteForceTripCountsComputed;
6912 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6913 }
6914
6915 // Update all the PHI nodes for the next iteration.
6916 DenseMap<Instruction *, Constant *> NextIterVals;
6917
6918 // Create a list of which PHIs we need to compute. We want to do this before
6919 // calling EvaluateExpression on them because that may invalidate iterators
6920 // into CurrentIterVals.
6921 SmallVector<PHINode *, 8> PHIsToCompute;
6922 for (const auto &I : CurrentIterVals) {
6923 PHINode *PHI = dyn_cast<PHINode>(I.first);
6924 if (!PHI || PHI->getParent() != Header) continue;
6925 PHIsToCompute.push_back(PHI);
6926 }
6927 for (PHINode *PHI : PHIsToCompute) {
6928 Constant *&NextPHI = NextIterVals[PHI];
6929 if (NextPHI) continue; // Already computed!
6930
6931 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6932 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6933 }
6934 CurrentIterVals.swap(NextIterVals);
6935 }
6936
6937 // Too many iterations were needed to evaluate.
6938 return getCouldNotCompute();
6939}
6940
6941const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6942 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6943 ValuesAtScopes[V];
6944 // Check to see if we've folded this expression at this loop before.
6945 for (auto &LS : Values)
6946 if (LS.first == L)
6947 return LS.second ? LS.second : V;
6948
6949 Values.emplace_back(L, nullptr);
6950
6951 // Otherwise compute it.
6952 const SCEV *C = computeSCEVAtScope(V, L);
6953 for (auto &LS : reverse(ValuesAtScopes[V]))
6954 if (LS.first == L) {
6955 LS.second = C;
6956 break;
6957 }
6958 return C;
6959}
6960
6961/// This builds up a Constant using the ConstantExpr interface. That way, we
6962/// will return Constants for objects which aren't represented by a
6963/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6964/// Returns NULL if the SCEV isn't representable as a Constant.
6965static Constant *BuildConstantFromSCEV(const SCEV *V) {
6966 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6967 case scCouldNotCompute:
6968 case scAddRecExpr:
6969 break;
6970 case scConstant:
6971 return cast<SCEVConstant>(V)->getValue();
6972 case scUnknown:
6973 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6974 case scSignExtend: {
6975 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6976 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6977 return ConstantExpr::getSExt(CastOp, SS->getType());
6978 break;
6979 }
6980 case scZeroExtend: {
6981 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6982 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6983 return ConstantExpr::getZExt(CastOp, SZ->getType());
6984 break;
6985 }
6986 case scTruncate: {
6987 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6988 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6989 return ConstantExpr::getTrunc(CastOp, ST->getType());
6990 break;
6991 }
6992 case scAddExpr: {
6993 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6994 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6995 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6996 unsigned AS = PTy->getAddressSpace();
6997 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6998 C = ConstantExpr::getBitCast(C, DestPtrTy);
6999 }
7000 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7001 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7002 if (!C2) return nullptr;
7003
7004 // First pointer!
7005 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7006 unsigned AS = C2->getType()->getPointerAddressSpace();
7007 std::swap(C, C2);
7008 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7009 // The offsets have been converted to bytes. We can add bytes to an
7010 // i8* by GEP with the byte count in the first index.
7011 C = ConstantExpr::getBitCast(C, DestPtrTy);
7012 }
7013
7014 // Don't bother trying to sum two pointers. We probably can't
7015 // statically compute a load that results from it anyway.
7016 if (C2->getType()->isPointerTy())
7017 return nullptr;
7018
7019 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7020 if (PTy->getElementType()->isStructTy())
7021 C2 = ConstantExpr::getIntegerCast(
7022 C2, Type::getInt32Ty(C->getContext()), true);
7023 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7024 } else
7025 C = ConstantExpr::getAdd(C, C2);
7026 }
7027 return C;
7028 }
7029 break;
7030 }
7031 case scMulExpr: {
7032 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7033 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7034 // Don't bother with pointers at all.
7035 if (C->getType()->isPointerTy()) return nullptr;
7036 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7037 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7038 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7039 C = ConstantExpr::getMul(C, C2);
7040 }
7041 return C;
7042 }
7043 break;
7044 }
7045 case scUDivExpr: {
7046 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7047 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7048 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7049 if (LHS->getType() == RHS->getType())
7050 return ConstantExpr::getUDiv(LHS, RHS);
7051 break;
7052 }
7053 case scSMaxExpr:
7054 case scUMaxExpr:
7055 break; // TODO: smax, umax.
7056 }
7057 return nullptr;
7058}
7059
7060const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7061 if (isa<SCEVConstant>(V)) return V;
7062
7063 // If this instruction is evolved from a constant-evolving PHI, compute the
7064 // exit value from the loop without using SCEVs.
7065 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7066 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7067 const Loop *LI = this->LI[I->getParent()];
7068 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
7069 if (PHINode *PN = dyn_cast<PHINode>(I))
7070 if (PN->getParent() == LI->getHeader()) {
7071 // Okay, there is no closed form solution for the PHI node. Check
7072 // to see if the loop that contains it has a known backedge-taken
7073 // count. If so, we may be able to force computation of the exit
7074 // value.
7075 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7076 if (const SCEVConstant *BTCC =
7077 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7078 // Okay, we know how many times the containing loop executes. If
7079 // this is a constant evolving PHI node, get the final value at
7080 // the specified iteration number.
7081 Constant *RV =
7082 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7083 if (RV) return getSCEV(RV);
7084 }
7085 }
7086
7087 // Okay, this is an expression that we cannot symbolically evaluate
7088 // into a SCEV. Check to see if it's possible to symbolically evaluate
7089 // the arguments into constants, and if so, try to constant propagate the
7090 // result. This is particularly useful for computing loop exit values.
7091 if (CanConstantFold(I)) {
7092 SmallVector<Constant *, 4> Operands;
7093 bool MadeImprovement = false;
7094 for (Value *Op : I->operands()) {
7095 if (Constant *C = dyn_cast<Constant>(Op)) {
7096 Operands.push_back(C);
7097 continue;
7098 }
7099
7100 // If any of the operands is non-constant and if they are
7101 // non-integer and non-pointer, don't even try to analyze them
7102 // with scev techniques.
7103 if (!isSCEVable(Op->getType()))
7104 return V;
7105
7106 const SCEV *OrigV = getSCEV(Op);
7107 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7108 MadeImprovement |= OrigV != OpV;
7109
7110 Constant *C = BuildConstantFromSCEV(OpV);
7111 if (!C) return V;
7112 if (C->getType() != Op->getType())
7113 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7114 Op->getType(),
7115 false),
7116 C, Op->getType());
7117 Operands.push_back(C);
7118 }
7119
7120 // Check to see if getSCEVAtScope actually made an improvement.
7121 if (MadeImprovement) {
7122 Constant *C = nullptr;
7123 const DataLayout &DL = getDataLayout();
7124 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7125 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7126 Operands[1], DL, &TLI);
7127 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7128 if (!LI->isVolatile())
7129 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7130 } else
7131 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7132 if (!C) return V;
7133 return getSCEV(C);
7134 }
7135 }
7136 }
7137
7138 // This is some other type of SCEVUnknown, just return it.
7139 return V;
7140 }
7141
7142 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7143 // Avoid performing the look-up in the common case where the specified
7144 // expression has no loop-variant portions.
7145 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7146 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7147 if (OpAtScope != Comm->getOperand(i)) {
7148 // Okay, at least one of these operands is loop variant but might be
7149 // foldable. Build a new instance of the folded commutative expression.
7150 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7151 Comm->op_begin()+i);
7152 NewOps.push_back(OpAtScope);
7153
7154 for (++i; i != e; ++i) {
7155 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7156 NewOps.push_back(OpAtScope);
7157 }
7158 if (isa<SCEVAddExpr>(Comm))
7159 return getAddExpr(NewOps);
7160 if (isa<SCEVMulExpr>(Comm))
7161 return getMulExpr(NewOps);
7162 if (isa<SCEVSMaxExpr>(Comm))
7163 return getSMaxExpr(NewOps);
7164 if (isa<SCEVUMaxExpr>(Comm))
7165 return getUMaxExpr(NewOps);
7166 llvm_unreachable("Unknown commutative SCEV type!")::llvm::llvm_unreachable_internal("Unknown commutative SCEV type!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 7166)
;
7167 }
7168 }
7169 // If we got here, all operands are loop invariant.
7170 return Comm;
7171 }
7172
7173 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7174 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7175 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7176 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7177 return Div; // must be loop invariant
7178 return getUDivExpr(LHS, RHS);
7179 }
7180
7181 // If this is a loop recurrence for a loop that does not contain L, then we
7182 // are dealing with the final value computed by the loop.
7183 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7184 // First, attempt to evaluate each operand.
7185 // Avoid performing the look-up in the common case where the specified
7186 // expression has no loop-variant portions.
7187 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7188 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7189 if (OpAtScope == AddRec->getOperand(i))
7190 continue;
7191
7192 // Okay, at least one of these operands is loop variant but might be
7193 // foldable. Build a new instance of the folded commutative expression.
7194 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7195 AddRec->op_begin()+i);
7196 NewOps.push_back(OpAtScope);
7197 for (++i; i != e; ++i)
7198 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7199
7200 const SCEV *FoldedRec =
7201 getAddRecExpr(NewOps, AddRec->getLoop(),
7202 AddRec->getNoWrapFlags(SCEV::FlagNW));
7203 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7204 // The addrec may be folded to a nonrecurrence, for example, if the
7205 // induction variable is multiplied by zero after constant folding. Go
7206 // ahead and return the folded value.
7207 if (!AddRec)
7208 return FoldedRec;
7209 break;
7210 }
7211
7212 // If the scope is outside the addrec's loop, evaluate it by using the
7213 // loop exit value of the addrec.
7214 if (!AddRec->getLoop()->contains(L)) {
7215 // To evaluate this recurrence, we need to know how many times the AddRec
7216 // loop iterates. Compute this now.
7217 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7218 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7219
7220 // Then, evaluate the AddRec.
7221 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7222 }
7223
7224 return AddRec;
7225 }
7226
7227 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7228 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7229 if (Op == Cast->getOperand())
7230 return Cast; // must be loop invariant
7231 return getZeroExtendExpr(Op, Cast->getType());
7232 }
7233
7234 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7235 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7236 if (Op == Cast->getOperand())
7237 return Cast; // must be loop invariant
7238 return getSignExtendExpr(Op, Cast->getType());
7239 }
7240
7241 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7242 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7243 if (Op == Cast->getOperand())
7244 return Cast; // must be loop invariant
7245 return getTruncateExpr(Op, Cast->getType());
7246 }
7247
7248 llvm_unreachable("Unknown SCEV type!")::llvm::llvm_unreachable_internal("Unknown SCEV type!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 7248)
;
7249}
7250
7251const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7252 return getSCEVAtScope(getSCEV(V), L);
7253}
7254
7255/// Finds the minimum unsigned root of the following equation:
7256///
7257/// A * X = B (mod N)
7258///
7259/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7260/// A and B isn't important.
7261///
7262/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7263static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7264 ScalarEvolution &SE) {
7265 uint32_t BW = A.getBitWidth();
7266 assert(BW == SE.getTypeSizeInBits(B->getType()))((BW == SE.getTypeSizeInBits(B->getType())) ? static_cast<
void> (0) : __assert_fail ("BW == SE.getTypeSizeInBits(B->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 7266, __PRETTY_FUNCTION__))
;
7267 assert(A != 0 && "A must be non-zero.")((A != 0 && "A must be non-zero.") ? static_cast<void
> (0) : __assert_fail ("A != 0 && \"A must be non-zero.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 7267, __PRETTY_FUNCTION__))
;
7268
7269 // 1. D = gcd(A, N)
7270 //
7271 // The gcd of A and N may have only one prime factor: 2. The number of
7272 // trailing zeros in A is its multiplicity
7273 uint32_t Mult2 = A.countTrailingZeros();
7274 // D = 2^Mult2
7275
7276 // 2. Check if B is divisible by D.
7277 //
7278 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7279 // is not less than multiplicity of this prime factor for D.
7280 if (SE.GetMinTrailingZeros(B) < Mult2)
7281 return SE.getCouldNotCompute();
7282
7283 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7284 // modulo (N / D).
7285 //
7286 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7287 // (N / D) in general. The inverse itself always fits into BW bits, though,
7288 // so we immediately truncate it.
7289 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7290 APInt Mod(BW + 1, 0);
7291 Mod.setBit(BW - Mult2); // Mod = N / D
7292 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7293
7294 // 4. Compute the minimum unsigned root of the equation:
7295 // I * (B / D) mod (N / D)
7296 // To simplify the computation, we factor out the divide by D:
7297 // (I * B mod N) / D
7298 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7299 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7300}
7301
7302/// Find the roots of the quadratic equation for the given quadratic chrec
7303/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7304/// two SCEVCouldNotCompute objects.
7305///
7306static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7307SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7308 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!")((AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"
) ? static_cast<void> (0) : __assert_fail ("AddRec->getNumOperands() == 3 && \"This is not a quadratic chrec!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301389/lib/Analysis/ScalarEvolution.cpp"
, 7308, __PRETTY_FUNCTION__))
;
7309 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7310 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7311 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7312
7313 // We currently can only solve this if the coefficients are constants.
7314 if (!LC || !MC || !NC)
7315 return None;
7316
7317 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7318 const APInt &L = LC->getAPInt();
7319 const APInt &M = MC->getAPInt();
7320 const APInt &N = NC->getAPInt();
7321 APInt Two(BitWidth, 2);
7322 APInt Four(BitWidth, 4);
7323
7324 {
7325 using namespace APIntOps;
7326 const APInt& C = L;
7327 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7328 // The B coefficient is M-N/2
7329 APInt B(M);
7330 B -= N.sdiv(Two);
7331
7332 // The A coefficient is N/2
7333 APInt A(N.sdiv(Two));
7334
7335 // Compute the B^2-4ac term.
7336 APInt SqrtTerm(B);
7337 SqrtTerm *= B;
7338 SqrtTerm -= Four * (A * C);
7339
7340 if (SqrtTerm.isNegative()) {
7341 // The loop is provably infinite.
7342 return None;
7343 }
7344
7345 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7346 // integer value or else APInt::sqrt() will assert.
7347 APInt SqrtVal(SqrtTerm.sqrt());
7348
7349 // Compute the two solutions for the quadratic formula.
7350 // The divisions must be performed as signed divisions.
7351 APInt NegB(-B);
7352 APInt TwoA(A << 1);
7353 if (TwoA.isMinValue())
7354 return None;
7355
7356 LLVMContext &Context = SE.getContext();
7357
7358 ConstantInt *Solution1 =
7359 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7360 ConstantInt *Solution2 =
7361 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7362
7363 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7364 cast<SCEVConstant>(SE.getConstant(Solution2)));
7365 } // end APIntOps namespace
7366}
7367
7368ScalarEvolution::ExitLimit
7369ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7370 bool AllowPredicates) {
7371
7372 // This is only used for loops with a "x != y" exit test. The exit condition
7373 // is now expressed as a single expression, V = x-y. So the exit test is
7374 // effectively V != 0. We know and take advantage of the fact that this
7375 // expression only being used in a comparison by zero context.
7376
7377 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7378 // If the value is a constant
7379 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7380 // If the value is already zero, the branch will execute zero times.
7381 if (C->getValue()->isZero()) return C;
7382 return getCouldNotCompute(); // Otherwise it will loop infinitely.
7383 }
7384
7385 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7386 if (!AddRec && AllowPredicates)
7387 // Try to make this an AddRec using runtime tests, in the first X
7388 // iterations of this loop, where X is the SCEV expression found by the
7389 // algorithm below.
7390 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7391
7392 if (!AddRec || AddRec->getLoop() != L)
7393 return getCouldNotCompute();
7394
7395 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7396 // the quadratic equation to solve it.
7397 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7398 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7399 const SCEVConstant *R1 = Roots->first;
7400 const SCEVConstant *R2 = Roots->second;
7401 // Pick the smallest positive root value.
7402 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7403 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7404 if (!CB->getZExtValue())
7405 std::swap(R1, R2); // R1 is the minimum root now.
7406
7407 // We can only use this value if the chrec ends up with an exact zero
7408 // value at this index. When solving for "X*X != 5", for example, we
7409 // should not accept a root of 2.
7410 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7411 if (Val->isZero())
7412 // We found a quadratic root!
7413 return ExitLimit(R1, R1, false, Predicates);
7414 }
7415 }
7416 return getCouldNotCompute();
7417 }
7418
7419 // Otherwise we can only handle this if it is affine.
7420 if (!AddRec->isAffine())
7421 return getCouldNotCompute();
7422
7423 // If this is an affine expression, the execution count of this branch is
7424 // the minimum unsigned root of the following equation:
7425 //
7426 // Start + Step*N = 0 (mod 2^BW)
7427 //
7428 // equivalent to:
7429 //
7430 // Step*N = -Start (mod 2^BW)
7431 //
7432 // where BW is the common bit width of Start and Step.
7433
7434 // Get the initial value for the loop.
7435 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7436 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7437
7438 // For now we handle only constant steps.
7439 //
7440 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7441 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7442 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7443 // We have not yet seen any such cases.
7444 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7445 if (!StepC || StepC->getValue()->equalsInt(0))
7446 return getCouldNotCompute();
7447
7448 // For positive steps (counting up until unsigned overflow):
7449 // N = -Start/Step (as unsigned)
7450 // For negative steps (counting down to zero):
7451 // N = Start/-Step
7452 // First compute the unsigned distance from zero in the direction of Step.
7453 bool CountDown = StepC->getAPInt().isNegative();
7454 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7455
7456 // Handle unitary steps, which cannot wraparound.
7457 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7458 // N = Distance (as unsigned)
7459 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7460 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7461
7462 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7463 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7464 // case, and see if we can improve the bound.
7465 //
7466 // Explicitly handling this here is necessary because getUnsignedRange
7467 // isn't context-sensitive; it doesn't know that we only care about the
7468 // range inside the loop.
7469 const SCEV *Zero = getZero(Distance->getType());
7470 const SCEV *One = getOne(Distance->getType());
7471 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7472 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7473 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7474 // as "unsigned_max(Distance + 1) - 1".
7475 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7476 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7477 }
7478 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7479 }
7480
7481 // If the condition controls loop exit (the loop exits only if the expression
7482 // is true) and the addition is no-wrap we can use unsigned divide to
7483