Bug Summary

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