Bug Summary

File:llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 6377, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ScalarEvolution.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp

1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
60#include "llvm/Analysis/ScalarEvolution.h"
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/DepthFirstIterator.h"
65#include "llvm/ADT/EquivalenceClasses.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/None.h"
68#include "llvm/ADT/Optional.h"
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/ScopeExit.h"
71#include "llvm/ADT/Sequence.h"
72#include "llvm/ADT/SetVector.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallSet.h"
75#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/Statistic.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/Analysis/AssumptionCache.h"
79#include "llvm/Analysis/ConstantFolding.h"
80#include "llvm/Analysis/InstructionSimplify.h"
81#include "llvm/Analysis/LoopInfo.h"
82#include "llvm/Analysis/ScalarEvolutionExpressions.h"
83#include "llvm/Analysis/TargetLibraryInfo.h"
84#include "llvm/Analysis/ValueTracking.h"
85#include "llvm/Config/llvm-config.h"
86#include "llvm/IR/Argument.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/CFG.h"
89#include "llvm/IR/CallSite.h"
90#include "llvm/IR/Constant.h"
91#include "llvm/IR/ConstantRange.h"
92#include "llvm/IR/Constants.h"
93#include "llvm/IR/DataLayout.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/Dominators.h"
96#include "llvm/IR/Function.h"
97#include "llvm/IR/GlobalAlias.h"
98#include "llvm/IR/GlobalValue.h"
99#include "llvm/IR/GlobalVariable.h"
100#include "llvm/IR/InstIterator.h"
101#include "llvm/IR/InstrTypes.h"
102#include "llvm/IR/Instruction.h"
103#include "llvm/IR/Instructions.h"
104#include "llvm/IR/IntrinsicInst.h"
105#include "llvm/IR/Intrinsics.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/Metadata.h"
108#include "llvm/IR/Operator.h"
109#include "llvm/IR/PatternMatch.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
114#include "llvm/IR/Verifier.h"
115#include "llvm/InitializePasses.h"
116#include "llvm/Pass.h"
117#include "llvm/Support/Casting.h"
118#include "llvm/Support/CommandLine.h"
119#include "llvm/Support/Compiler.h"
120#include "llvm/Support/Debug.h"
121#include "llvm/Support/ErrorHandling.h"
122#include "llvm/Support/KnownBits.h"
123#include "llvm/Support/SaveAndRestore.h"
124#include "llvm/Support/raw_ostream.h"
125#include <algorithm>
126#include <cassert>
127#include <climits>
128#include <cstddef>
129#include <cstdint>
130#include <cstdlib>
131#include <map>
132#include <memory>
133#include <tuple>
134#include <utility>
135#include <vector>
136
137using namespace llvm;
138
139#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
140
141STATISTIC(NumArrayLenItCounts,static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
}
142 "Number of trip counts computed with array length")static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
}
;
143STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
144 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
;
145STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
146 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
;
147STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
}
148 "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"
}
;
149
150static cl::opt<unsigned>
151MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152 cl::ZeroOrMore,
153 cl::desc("Maximum number of iterations SCEV will "
154 "symbolically execute a constant "
155 "derived loop"),
156 cl::init(100));
157
158// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
159static cl::opt<bool> VerifySCEV(
160 "verify-scev", cl::Hidden,
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162static cl::opt<bool> VerifySCEVStrict(
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
165static cl::opt<bool>
166 VerifySCEVMap("verify-scev-maps", cl::Hidden,
167 cl::desc("Verify no dangling value in ScalarEvolution's "
168 "ExprValueMap (slow)"));
169
170static cl::opt<bool> VerifyIR(
171 "scev-verify-ir", cl::Hidden,
172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173 cl::init(false));
174
175static cl::opt<unsigned> MulOpsInlineThreshold(
176 "scev-mulops-inline-threshold", cl::Hidden,
177 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178 cl::init(32));
179
180static cl::opt<unsigned> AddOpsInlineThreshold(
181 "scev-addops-inline-threshold", cl::Hidden,
182 cl::desc("Threshold for inlining addition operands into a SCEV"),
183 cl::init(500));
184
185static cl::opt<unsigned> MaxSCEVCompareDepth(
186 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188 cl::init(32));
189
190static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193 cl::init(2));
194
195static cl::opt<unsigned> MaxValueCompareDepth(
196 "scalar-evolution-max-value-compare-depth", cl::Hidden,
197 cl::desc("Maximum depth of recursive value complexity comparisons"),
198 cl::init(2));
199
200static cl::opt<unsigned>
201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202 cl::desc("Maximum depth of recursive arithmetics"),
203 cl::init(32));
204
205static cl::opt<unsigned> MaxConstantEvolvingDepth(
206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208
209static cl::opt<unsigned>
210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212 cl::init(8));
213
214static cl::opt<unsigned>
215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216 cl::desc("Max coefficients in AddRec during evolving"),
217 cl::init(8));
218
219static cl::opt<unsigned>
220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221 cl::desc("Size of the expression which is considered huge"),
222 cl::init(4096));
223
224static cl::opt<bool>
225ClassifyExpressions("scalar-evolution-classify-expressions",
226 cl::Hidden, cl::init(true),
227 cl::desc("When printing analysis, include information on every instruction"));
228
229
230//===----------------------------------------------------------------------===//
231// SCEV class definitions
232//===----------------------------------------------------------------------===//
233
234//===----------------------------------------------------------------------===//
235// Implementation of the SCEV class.
236//
237
238#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
239LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
240 print(dbgs());
241 dbgs() << '\n';
242}
243#endif
244
245void SCEV::print(raw_ostream &OS) const {
246 switch (static_cast<SCEVTypes>(getSCEVType())) {
247 case scConstant:
248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
249 return;
250 case scTruncate: {
251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
252 const SCEV *Op = Trunc->getOperand();
253 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
254 << *Trunc->getType() << ")";
255 return;
256 }
257 case scZeroExtend: {
258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
259 const SCEV *Op = ZExt->getOperand();
260 OS << "(zext " << *Op->getType() << " " << *Op << " to "
261 << *ZExt->getType() << ")";
262 return;
263 }
264 case scSignExtend: {
265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
266 const SCEV *Op = SExt->getOperand();
267 OS << "(sext " << *Op->getType() << " " << *Op << " to "
268 << *SExt->getType() << ")";
269 return;
270 }
271 case scAddRecExpr: {
272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
273 OS << "{" << *AR->getOperand(0);
274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
275 OS << ",+," << *AR->getOperand(i);
276 OS << "}<";
277 if (AR->hasNoUnsignedWrap())
278 OS << "nuw><";
279 if (AR->hasNoSignedWrap())
280 OS << "nsw><";
281 if (AR->hasNoSelfWrap() &&
282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
283 OS << "nw><";
284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
285 OS << ">";
286 return;
287 }
288 case scAddExpr:
289 case scMulExpr:
290 case scUMaxExpr:
291 case scSMaxExpr:
292 case scUMinExpr:
293 case scSMinExpr: {
294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
295 const char *OpStr = nullptr;
296 switch (NAry->getSCEVType()) {
297 case scAddExpr: OpStr = " + "; break;
298 case scMulExpr: OpStr = " * "; break;
299 case scUMaxExpr: OpStr = " umax "; break;
300 case scSMaxExpr: OpStr = " smax "; break;
301 case scUMinExpr:
302 OpStr = " umin ";
303 break;
304 case scSMinExpr:
305 OpStr = " smin ";
306 break;
307 }
308 OS << "(";
309 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
310 I != E; ++I) {
311 OS << **I;
312 if (std::next(I) != E)
313 OS << OpStr;
314 }
315 OS << ")";
316 switch (NAry->getSCEVType()) {
317 case scAddExpr:
318 case scMulExpr:
319 if (NAry->hasNoUnsignedWrap())
320 OS << "<nuw>";
321 if (NAry->hasNoSignedWrap())
322 OS << "<nsw>";
323 }
324 return;
325 }
326 case scUDivExpr: {
327 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
328 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
329 return;
330 }
331 case scUnknown: {
332 const SCEVUnknown *U = cast<SCEVUnknown>(this);
333 Type *AllocTy;
334 if (U->isSizeOf(AllocTy)) {
335 OS << "sizeof(" << *AllocTy << ")";
336 return;
337 }
338 if (U->isAlignOf(AllocTy)) {
339 OS << "alignof(" << *AllocTy << ")";
340 return;
341 }
342
343 Type *CTy;
344 Constant *FieldNo;
345 if (U->isOffsetOf(CTy, FieldNo)) {
346 OS << "offsetof(" << *CTy << ", ";
347 FieldNo->printAsOperand(OS, false);
348 OS << ")";
349 return;
350 }
351
352 // Otherwise just print it normally.
353 U->getValue()->printAsOperand(OS, false);
354 return;
355 }
356 case scCouldNotCompute:
357 OS << "***COULDNOTCOMPUTE***";
358 return;
359 }
360 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 360)
;
361}
362
363Type *SCEV::getType() const {
364 switch (static_cast<SCEVTypes>(getSCEVType())) {
365 case scConstant:
366 return cast<SCEVConstant>(this)->getType();
367 case scTruncate:
368 case scZeroExtend:
369 case scSignExtend:
370 return cast<SCEVCastExpr>(this)->getType();
371 case scAddRecExpr:
372 case scMulExpr:
373 case scUMaxExpr:
374 case scSMaxExpr:
375 case scUMinExpr:
376 case scSMinExpr:
377 return cast<SCEVNAryExpr>(this)->getType();
378 case scAddExpr:
379 return cast<SCEVAddExpr>(this)->getType();
380 case scUDivExpr:
381 return cast<SCEVUDivExpr>(this)->getType();
382 case scUnknown:
383 return cast<SCEVUnknown>(this)->getType();
384 case scCouldNotCompute:
385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 385)
;
386 }
387 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 387)
;
388}
389
390bool SCEV::isZero() const {
391 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
392 return SC->getValue()->isZero();
393 return false;
394}
395
396bool SCEV::isOne() const {
397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
398 return SC->getValue()->isOne();
399 return false;
400}
401
402bool SCEV::isAllOnesValue() const {
403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
404 return SC->getValue()->isMinusOne();
405 return false;
406}
407
408bool SCEV::isNonConstantNegative() const {
409 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
410 if (!Mul) return false;
411
412 // If there is a constant factor, it will be first.
413 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
414 if (!SC) return false;
415
416 // Return true if the value is negative, this matches things like (-42 * V).
417 return SC->getAPInt().isNegative();
418}
419
420SCEVCouldNotCompute::SCEVCouldNotCompute() :
421 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
422
423bool SCEVCouldNotCompute::classof(const SCEV *S) {
424 return S->getSCEVType() == scCouldNotCompute;
425}
426
427const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
428 FoldingSetNodeID ID;
429 ID.AddInteger(scConstant);
430 ID.AddPointer(V);
431 void *IP = nullptr;
432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
433 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
434 UniqueSCEVs.InsertNode(S, IP);
435 return S;
436}
437
438const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
439 return getConstant(ConstantInt::get(getContext(), Val));
440}
441
442const SCEV *
443ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
445 return getConstant(ConstantInt::get(ITy, V, isSigned));
446}
447
448SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
449 unsigned SCEVTy, const SCEV *op, Type *ty)
450 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
451
452SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
453 const SCEV *op, Type *ty)
454 : SCEVCastExpr(ID, scTruncate, op, ty) {
455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 456, __PRETTY_FUNCTION__))
456 "Cannot truncate non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 456, __PRETTY_FUNCTION__))
;
457}
458
459SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
460 const SCEV *op, Type *ty)
461 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 463, __PRETTY_FUNCTION__))
463 "Cannot zero extend non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 463, __PRETTY_FUNCTION__))
;
464}
465
466SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
467 const SCEV *op, Type *ty)
468 : SCEVCastExpr(ID, scSignExtend, op, ty) {
469 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 470, __PRETTY_FUNCTION__))
470 "Cannot sign extend non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 470, __PRETTY_FUNCTION__))
;
471}
472
473void SCEVUnknown::deleted() {
474 // Clear this SCEVUnknown from various maps.
475 SE->forgetMemoizedResults(this);
476
477 // Remove this SCEVUnknown from the uniquing map.
478 SE->UniqueSCEVs.RemoveNode(this);
479
480 // Release the value.
481 setValPtr(nullptr);
482}
483
484void SCEVUnknown::allUsesReplacedWith(Value *New) {
485 // Remove this SCEVUnknown from the uniquing map.
486 SE->UniqueSCEVs.RemoveNode(this);
487
488 // Update this SCEVUnknown to point to the new value. This is needed
489 // because there may still be outstanding SCEVs which still point to
490 // this SCEVUnknown.
491 setValPtr(New);
492}
493
494bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
495 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
496 if (VCE->getOpcode() == Instruction::PtrToInt)
497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
498 if (CE->getOpcode() == Instruction::GetElementPtr &&
499 CE->getOperand(0)->isNullValue() &&
500 CE->getNumOperands() == 2)
501 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
502 if (CI->isOne()) {
503 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
504 ->getElementType();
505 return true;
506 }
507
508 return false;
509}
510
511bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
512 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
513 if (VCE->getOpcode() == Instruction::PtrToInt)
514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
515 if (CE->getOpcode() == Instruction::GetElementPtr &&
516 CE->getOperand(0)->isNullValue()) {
517 Type *Ty =
518 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
519 if (StructType *STy = dyn_cast<StructType>(Ty))
520 if (!STy->isPacked() &&
521 CE->getNumOperands() == 3 &&
522 CE->getOperand(1)->isNullValue()) {
523 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
524 if (CI->isOne() &&
525 STy->getNumElements() == 2 &&
526 STy->getElementType(0)->isIntegerTy(1)) {
527 AllocTy = STy->getElementType(1);
528 return true;
529 }
530 }
531 }
532
533 return false;
534}
535
536bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
537 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
538 if (VCE->getOpcode() == Instruction::PtrToInt)
539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
540 if (CE->getOpcode() == Instruction::GetElementPtr &&
541 CE->getNumOperands() == 3 &&
542 CE->getOperand(0)->isNullValue() &&
543 CE->getOperand(1)->isNullValue()) {
544 Type *Ty =
545 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
546 // Ignore vector types here so that ScalarEvolutionExpander doesn't
547 // emit getelementptrs that index into vectors.
548 if (Ty->isStructTy() || Ty->isArrayTy()) {
549 CTy = Ty;
550 FieldNo = CE->getOperand(2);
551 return true;
552 }
553 }
554
555 return false;
556}
557
558//===----------------------------------------------------------------------===//
559// SCEV Utilities
560//===----------------------------------------------------------------------===//
561
562/// Compare the two values \p LV and \p RV in terms of their "complexity" where
563/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
564/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
565/// have been previously deemed to be "equally complex" by this routine. It is
566/// intended to avoid exponential time complexity in cases like:
567///
568/// %a = f(%x, %y)
569/// %b = f(%a, %a)
570/// %c = f(%b, %b)
571///
572/// %d = f(%x, %y)
573/// %e = f(%d, %d)
574/// %f = f(%e, %e)
575///
576/// CompareValueComplexity(%f, %c)
577///
578/// Since we do not continue running this routine on expression trees once we
579/// have seen unequal values, there is no need to track them in the cache.
580static int
581CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
582 const LoopInfo *const LI, Value *LV, Value *RV,
583 unsigned Depth) {
584 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
585 return 0;
586
587 // Order pointer values after integer values. This helps SCEVExpander form
588 // GEPs.
589 bool LIsPointer = LV->getType()->isPointerTy(),
590 RIsPointer = RV->getType()->isPointerTy();
591 if (LIsPointer != RIsPointer)
592 return (int)LIsPointer - (int)RIsPointer;
593
594 // Compare getValueID values.
595 unsigned LID = LV->getValueID(), RID = RV->getValueID();
596 if (LID != RID)
597 return (int)LID - (int)RID;
598
599 // Sort arguments by their position.
600 if (const auto *LA = dyn_cast<Argument>(LV)) {
601 const auto *RA = cast<Argument>(RV);
602 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
603 return (int)LArgNo - (int)RArgNo;
604 }
605
606 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
607 const auto *RGV = cast<GlobalValue>(RV);
608
609 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
610 auto LT = GV->getLinkage();
611 return !(GlobalValue::isPrivateLinkage(LT) ||
612 GlobalValue::isInternalLinkage(LT));
613 };
614
615 // Use the names to distinguish the two values, but only if the
616 // names are semantically important.
617 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
618 return LGV->getName().compare(RGV->getName());
619 }
620
621 // For instructions, compare their loop depth, and their operand count. This
622 // is pretty loose.
623 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
624 const auto *RInst = cast<Instruction>(RV);
625
626 // Compare loop depths.
627 const BasicBlock *LParent = LInst->getParent(),
628 *RParent = RInst->getParent();
629 if (LParent != RParent) {
630 unsigned LDepth = LI->getLoopDepth(LParent),
631 RDepth = LI->getLoopDepth(RParent);
632 if (LDepth != RDepth)
633 return (int)LDepth - (int)RDepth;
634 }
635
636 // Compare the number of operands.
637 unsigned LNumOps = LInst->getNumOperands(),
638 RNumOps = RInst->getNumOperands();
639 if (LNumOps != RNumOps)
640 return (int)LNumOps - (int)RNumOps;
641
642 for (unsigned Idx : seq(0u, LNumOps)) {
643 int Result =
644 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
645 RInst->getOperand(Idx), Depth + 1);
646 if (Result != 0)
647 return Result;
648 }
649 }
650
651 EqCacheValue.unionSets(LV, RV);
652 return 0;
653}
654
655// Return negative, zero, or positive, if LHS is less than, equal to, or greater
656// than RHS, respectively. A three-way result allows recursive comparisons to be
657// more efficient.
658static int CompareSCEVComplexity(
659 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
660 EquivalenceClasses<const Value *> &EqCacheValue,
661 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
662 DominatorTree &DT, unsigned Depth = 0) {
663 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
664 if (LHS == RHS)
665 return 0;
666
667 // Primarily, sort the SCEVs by their getSCEVType().
668 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
669 if (LType != RType)
670 return (int)LType - (int)RType;
671
672 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
673 return 0;
674 // Aside from the getSCEVType() ordering, the particular ordering
675 // isn't very important except that it's beneficial to be consistent,
676 // so that (a + b) and (b + a) don't end up as different expressions.
677 switch (static_cast<SCEVTypes>(LType)) {
678 case scUnknown: {
679 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
680 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
681
682 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
683 RU->getValue(), Depth + 1);
684 if (X == 0)
685 EqCacheSCEV.unionSets(LHS, RHS);
686 return X;
687 }
688
689 case scConstant: {
690 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
691 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
692
693 // Compare constant values.
694 const APInt &LA = LC->getAPInt();
695 const APInt &RA = RC->getAPInt();
696 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
697 if (LBitWidth != RBitWidth)
698 return (int)LBitWidth - (int)RBitWidth;
699 return LA.ult(RA) ? -1 : 1;
700 }
701
702 case scAddRecExpr: {
703 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
704 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
705
706 // There is always a dominance between two recs that are used by one SCEV,
707 // so we can safely sort recs by loop header dominance. We require such
708 // order in getAddExpr.
709 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
710 if (LLoop != RLoop) {
711 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
712 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 712, __PRETTY_FUNCTION__))
;
713 if (DT.dominates(LHead, RHead))
714 return 1;
715 else
716 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 717, __PRETTY_FUNCTION__))
717 "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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 717, __PRETTY_FUNCTION__))
;
718 return -1;
719 }
720
721 // Addrec complexity grows with operand count.
722 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
723 if (LNumOps != RNumOps)
724 return (int)LNumOps - (int)RNumOps;
725
726 // Lexicographically compare.
727 for (unsigned i = 0; i != LNumOps; ++i) {
728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
729 LA->getOperand(i), RA->getOperand(i), DT,
730 Depth + 1);
731 if (X != 0)
732 return X;
733 }
734 EqCacheSCEV.unionSets(LHS, RHS);
735 return 0;
736 }
737
738 case scAddExpr:
739 case scMulExpr:
740 case scSMaxExpr:
741 case scUMaxExpr:
742 case scSMinExpr:
743 case scUMinExpr: {
744 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
745 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
746
747 // Lexicographically compare n-ary expressions.
748 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
749 if (LNumOps != RNumOps)
750 return (int)LNumOps - (int)RNumOps;
751
752 for (unsigned i = 0; i != LNumOps; ++i) {
753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
754 LC->getOperand(i), RC->getOperand(i), DT,
755 Depth + 1);
756 if (X != 0)
757 return X;
758 }
759 EqCacheSCEV.unionSets(LHS, RHS);
760 return 0;
761 }
762
763 case scUDivExpr: {
764 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
765 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
766
767 // Lexicographically compare udiv expressions.
768 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
769 RC->getLHS(), DT, Depth + 1);
770 if (X != 0)
771 return X;
772 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
773 RC->getRHS(), DT, Depth + 1);
774 if (X == 0)
775 EqCacheSCEV.unionSets(LHS, RHS);
776 return X;
777 }
778
779 case scTruncate:
780 case scZeroExtend:
781 case scSignExtend: {
782 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
783 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
784
785 // Compare cast expressions by operand.
786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
787 LC->getOperand(), RC->getOperand(), DT,
788 Depth + 1);
789 if (X == 0)
790 EqCacheSCEV.unionSets(LHS, RHS);
791 return X;
792 }
793
794 case scCouldNotCompute:
795 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 795)
;
796 }
797 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 797)
;
798}
799
800/// Given a list of SCEV objects, order them by their complexity, and group
801/// objects of the same complexity together by value. When this routine is
802/// finished, we know that any duplicates in the vector are consecutive and that
803/// complexity is monotonically increasing.
804///
805/// Note that we go take special precautions to ensure that we get deterministic
806/// results from this routine. In other words, we don't want the results of
807/// this to depend on where the addresses of various SCEV objects happened to
808/// land in memory.
809static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
810 LoopInfo *LI, DominatorTree &DT) {
811 if (Ops.size() < 2) return; // Noop
812
813 EquivalenceClasses<const SCEV *> EqCacheSCEV;
814 EquivalenceClasses<const Value *> EqCacheValue;
815 if (Ops.size() == 2) {
816 // This is the common case, which also happens to be trivially simple.
817 // Special case it.
818 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
819 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
820 std::swap(LHS, RHS);
821 return;
822 }
823
824 // Do the rough sort by complexity.
825 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
826 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
827 0;
828 });
829
830 // Now that we are sorted by complexity, group elements of the same
831 // complexity. Note that this is, at worst, N^2, but the vector is likely to
832 // be extremely short in practice. Note that we take this approach because we
833 // do not want to depend on the addresses of the objects we are grouping.
834 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
835 const SCEV *S = Ops[i];
836 unsigned Complexity = S->getSCEVType();
837
838 // If there are any objects of the same complexity and same value as this
839 // one, group them.
840 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
841 if (Ops[j] == S) { // Found a duplicate.
842 // Move it to immediately after i'th element.
843 std::swap(Ops[i+1], Ops[j]);
844 ++i; // no need to rescan it.
845 if (i == e-2) return; // Done!
846 }
847 }
848 }
849}
850
851// Returns the size of the SCEV S.
852static inline int sizeOfSCEV(const SCEV *S) {
853 struct FindSCEVSize {
854 int Size = 0;
855
856 FindSCEVSize() = default;
857
858 bool follow(const SCEV *S) {
859 ++Size;
860 // Keep looking at all operands of S.
861 return true;
862 }
863
864 bool isDone() const {
865 return false;
866 }
867 };
868
869 FindSCEVSize F;
870 SCEVTraversal<FindSCEVSize> ST(F);
871 ST.visitAll(S);
872 return F.Size;
873}
874
875/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
876/// least HugeExprThreshold nodes).
877static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
878 return any_of(Ops, [](const SCEV *S) {
879 return S->getExpressionSize() >= HugeExprThreshold;
880 });
881}
882
883namespace {
884
885struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
886public:
887 // Computes the Quotient and Remainder of the division of Numerator by
888 // Denominator.
889 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
890 const SCEV *Denominator, const SCEV **Quotient,
891 const SCEV **Remainder) {
892 assert(Numerator && Denominator && "Uninitialized SCEV")((Numerator && Denominator && "Uninitialized SCEV"
) ? static_cast<void> (0) : __assert_fail ("Numerator && Denominator && \"Uninitialized SCEV\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 892, __PRETTY_FUNCTION__))
;
893
894 SCEVDivision D(SE, Numerator, Denominator);
895
896 // Check for the trivial case here to avoid having to check for it in the
897 // rest of the code.
898 if (Numerator == Denominator) {
899 *Quotient = D.One;
900 *Remainder = D.Zero;
901 return;
902 }
903
904 if (Numerator->isZero()) {
905 *Quotient = D.Zero;
906 *Remainder = D.Zero;
907 return;
908 }
909
910 // A simple case when N/1. The quotient is N.
911 if (Denominator->isOne()) {
912 *Quotient = Numerator;
913 *Remainder = D.Zero;
914 return;
915 }
916
917 // Split the Denominator when it is a product.
918 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
919 const SCEV *Q, *R;
920 *Quotient = Numerator;
921 for (const SCEV *Op : T->operands()) {
922 divide(SE, *Quotient, Op, &Q, &R);
923 *Quotient = Q;
924
925 // Bail out when the Numerator is not divisible by one of the terms of
926 // the Denominator.
927 if (!R->isZero()) {
928 *Quotient = D.Zero;
929 *Remainder = Numerator;
930 return;
931 }
932 }
933 *Remainder = D.Zero;
934 return;
935 }
936
937 D.visit(Numerator);
938 *Quotient = D.Quotient;
939 *Remainder = D.Remainder;
940 }
941
942 // Except in the trivial case described above, we do not know how to divide
943 // Expr by Denominator for the following functions with empty implementation.
944 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
945 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
946 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
947 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
948 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
949 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
950 void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
951 void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
952 void visitUnknown(const SCEVUnknown *Numerator) {}
953 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
954
955 void visitConstant(const SCEVConstant *Numerator) {
956 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
957 APInt NumeratorVal = Numerator->getAPInt();
958 APInt DenominatorVal = D->getAPInt();
959 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
960 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
961
962 if (NumeratorBW > DenominatorBW)
963 DenominatorVal = DenominatorVal.sext(NumeratorBW);
964 else if (NumeratorBW < DenominatorBW)
965 NumeratorVal = NumeratorVal.sext(DenominatorBW);
966
967 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
968 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
969 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
970 Quotient = SE.getConstant(QuotientVal);
971 Remainder = SE.getConstant(RemainderVal);
972 return;
973 }
974 }
975
976 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
977 const SCEV *StartQ, *StartR, *StepQ, *StepR;
978 if (!Numerator->isAffine())
979 return cannotDivide(Numerator);
980 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
981 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
982 // Bail out if the types do not match.
983 Type *Ty = Denominator->getType();
984 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
985 Ty != StepQ->getType() || Ty != StepR->getType())
986 return cannotDivide(Numerator);
987 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
988 Numerator->getNoWrapFlags());
989 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
990 Numerator->getNoWrapFlags());
991 }
992
993 void visitAddExpr(const SCEVAddExpr *Numerator) {
994 SmallVector<const SCEV *, 2> Qs, Rs;
995 Type *Ty = Denominator->getType();
996
997 for (const SCEV *Op : Numerator->operands()) {
998 const SCEV *Q, *R;
999 divide(SE, Op, Denominator, &Q, &R);
1000
1001 // Bail out if types do not match.
1002 if (Ty != Q->getType() || Ty != R->getType())
1003 return cannotDivide(Numerator);
1004
1005 Qs.push_back(Q);
1006 Rs.push_back(R);
1007 }
1008
1009 if (Qs.size() == 1) {
1010 Quotient = Qs[0];
1011 Remainder = Rs[0];
1012 return;
1013 }
1014
1015 Quotient = SE.getAddExpr(Qs);
1016 Remainder = SE.getAddExpr(Rs);
1017 }
1018
1019 void visitMulExpr(const SCEVMulExpr *Numerator) {
1020 SmallVector<const SCEV *, 2> Qs;
1021 Type *Ty = Denominator->getType();
1022
1023 bool FoundDenominatorTerm = false;
1024 for (const SCEV *Op : Numerator->operands()) {
1025 // Bail out if types do not match.
1026 if (Ty != Op->getType())
1027 return cannotDivide(Numerator);
1028
1029 if (FoundDenominatorTerm) {
1030 Qs.push_back(Op);
1031 continue;
1032 }
1033
1034 // Check whether Denominator divides one of the product operands.
1035 const SCEV *Q, *R;
1036 divide(SE, Op, Denominator, &Q, &R);
1037 if (!R->isZero()) {
1038 Qs.push_back(Op);
1039 continue;
1040 }
1041
1042 // Bail out if types do not match.
1043 if (Ty != Q->getType())
1044 return cannotDivide(Numerator);
1045
1046 FoundDenominatorTerm = true;
1047 Qs.push_back(Q);
1048 }
1049
1050 if (FoundDenominatorTerm) {
1051 Remainder = Zero;
1052 if (Qs.size() == 1)
1053 Quotient = Qs[0];
1054 else
1055 Quotient = SE.getMulExpr(Qs);
1056 return;
1057 }
1058
1059 if (!isa<SCEVUnknown>(Denominator))
1060 return cannotDivide(Numerator);
1061
1062 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1063 ValueToValueMap RewriteMap;
1064 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1065 cast<SCEVConstant>(Zero)->getValue();
1066 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1067
1068 if (Remainder->isZero()) {
1069 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1070 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1071 cast<SCEVConstant>(One)->getValue();
1072 Quotient =
1073 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1074 return;
1075 }
1076
1077 // Quotient is (Numerator - Remainder) divided by Denominator.
1078 const SCEV *Q, *R;
1079 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1080 // This SCEV does not seem to simplify: fail the division here.
1081 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1082 return cannotDivide(Numerator);
1083 divide(SE, Diff, Denominator, &Q, &R);
1084 if (R != Zero)
1085 return cannotDivide(Numerator);
1086 Quotient = Q;
1087 }
1088
1089private:
1090 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1091 const SCEV *Denominator)
1092 : SE(S), Denominator(Denominator) {
1093 Zero = SE.getZero(Denominator->getType());
1094 One = SE.getOne(Denominator->getType());
1095
1096 // We generally do not know how to divide Expr by Denominator. We
1097 // initialize the division to a "cannot divide" state to simplify the rest
1098 // of the code.
1099 cannotDivide(Numerator);
1100 }
1101
1102 // Convenience function for giving up on the division. We set the quotient to
1103 // be equal to zero and the remainder to be equal to the numerator.
1104 void cannotDivide(const SCEV *Numerator) {
1105 Quotient = Zero;
1106 Remainder = Numerator;
1107 }
1108
1109 ScalarEvolution &SE;
1110 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1111};
1112
1113} // end anonymous namespace
1114
1115//===----------------------------------------------------------------------===//
1116// Simple SCEV method implementations
1117//===----------------------------------------------------------------------===//
1118
1119/// Compute BC(It, K). The result has width W. Assume, K > 0.
1120static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1121 ScalarEvolution &SE,
1122 Type *ResultTy) {
1123 // Handle the simplest case efficiently.
1124 if (K == 1)
1125 return SE.getTruncateOrZeroExtend(It, ResultTy);
1126
1127 // We are using the following formula for BC(It, K):
1128 //
1129 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1130 //
1131 // Suppose, W is the bitwidth of the return value. We must be prepared for
1132 // overflow. Hence, we must assure that the result of our computation is
1133 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1134 // safe in modular arithmetic.
1135 //
1136 // However, this code doesn't use exactly that formula; the formula it uses
1137 // is something like the following, where T is the number of factors of 2 in
1138 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1139 // exponentiation:
1140 //
1141 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1142 //
1143 // This formula is trivially equivalent to the previous formula. However,
1144 // this formula can be implemented much more efficiently. The trick is that
1145 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1146 // arithmetic. To do exact division in modular arithmetic, all we have
1147 // to do is multiply by the inverse. Therefore, this step can be done at
1148 // width W.
1149 //
1150 // The next issue is how to safely do the division by 2^T. The way this
1151 // is done is by doing the multiplication step at a width of at least W + T
1152 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1153 // when we perform the division by 2^T (which is equivalent to a right shift
1154 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1155 // truncated out after the division by 2^T.
1156 //
1157 // In comparison to just directly using the first formula, this technique
1158 // is much more efficient; using the first formula requires W * K bits,
1159 // but this formula less than W + K bits. Also, the first formula requires
1160 // a division step, whereas this formula only requires multiplies and shifts.
1161 //
1162 // It doesn't matter whether the subtraction step is done in the calculation
1163 // width or the input iteration count's width; if the subtraction overflows,
1164 // the result must be zero anyway. We prefer here to do it in the width of
1165 // the induction variable because it helps a lot for certain cases; CodeGen
1166 // isn't smart enough to ignore the overflow, which leads to much less
1167 // efficient code if the width of the subtraction is wider than the native
1168 // register width.
1169 //
1170 // (It's possible to not widen at all by pulling out factors of 2 before
1171 // the multiplication; for example, K=2 can be calculated as
1172 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1173 // extra arithmetic, so it's not an obvious win, and it gets
1174 // much more complicated for K > 3.)
1175
1176 // Protection from insane SCEVs; this bound is conservative,
1177 // but it probably doesn't matter.
1178 if (K > 1000)
1179 return SE.getCouldNotCompute();
1180
1181 unsigned W = SE.getTypeSizeInBits(ResultTy);
1182
1183 // Calculate K! / 2^T and T; we divide out the factors of two before
1184 // multiplying for calculating K! / 2^T to avoid overflow.
1185 // Other overflow doesn't matter because we only care about the bottom
1186 // W bits of the result.
1187 APInt OddFactorial(W, 1);
1188 unsigned T = 1;
1189 for (unsigned i = 3; i <= K; ++i) {
1190 APInt Mult(W, i);
1191 unsigned TwoFactors = Mult.countTrailingZeros();
1192 T += TwoFactors;
1193 Mult.lshrInPlace(TwoFactors);
1194 OddFactorial *= Mult;
1195 }
1196
1197 // We need at least W + T bits for the multiplication step
1198 unsigned CalculationBits = W + T;
1199
1200 // Calculate 2^T, at width T+W.
1201 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1202
1203 // Calculate the multiplicative inverse of K! / 2^T;
1204 // this multiplication factor will perform the exact division by
1205 // K! / 2^T.
1206 APInt Mod = APInt::getSignedMinValue(W+1);
1207 APInt MultiplyFactor = OddFactorial.zext(W+1);
1208 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1209 MultiplyFactor = MultiplyFactor.trunc(W);
1210
1211 // Calculate the product, at width T+W
1212 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1213 CalculationBits);
1214 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1215 for (unsigned i = 1; i != K; ++i) {
1216 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1217 Dividend = SE.getMulExpr(Dividend,
1218 SE.getTruncateOrZeroExtend(S, CalculationTy));
1219 }
1220
1221 // Divide by 2^T
1222 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1223
1224 // Truncate the result, and divide by K! / 2^T.
1225
1226 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1227 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1228}
1229
1230/// Return the value of this chain of recurrences at the specified iteration
1231/// number. We can evaluate this recurrence by multiplying each element in the
1232/// chain by the binomial coefficient corresponding to it. In other words, we
1233/// can evaluate {A,+,B,+,C,+,D} as:
1234///
1235/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1236///
1237/// where BC(It, k) stands for binomial coefficient.
1238const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1239 ScalarEvolution &SE) const {
1240 const SCEV *Result = getStart();
1241 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1242 // The computation is correct in the face of overflow provided that the
1243 // multiplication is performed _after_ the evaluation of the binomial
1244 // coefficient.
1245 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1246 if (isa<SCEVCouldNotCompute>(Coeff))
1247 return Coeff;
1248
1249 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1250 }
1251 return Result;
1252}
1253
1254//===----------------------------------------------------------------------===//
1255// SCEV Expression folder implementations
1256//===----------------------------------------------------------------------===//
1257
1258const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1259 unsigned Depth) {
1260 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1261, __PRETTY_FUNCTION__))
1261 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1261, __PRETTY_FUNCTION__))
;
1262 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1263, __PRETTY_FUNCTION__))
1263 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1263, __PRETTY_FUNCTION__))
;
1264 Ty = getEffectiveSCEVType(Ty);
1265
1266 FoldingSetNodeID ID;
1267 ID.AddInteger(scTruncate);
1268 ID.AddPointer(Op);
1269 ID.AddPointer(Ty);
1270 void *IP = nullptr;
1271 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1272
1273 // Fold if the operand is constant.
1274 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1275 return getConstant(
1276 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1277
1278 // trunc(trunc(x)) --> trunc(x)
1279 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1280 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1281
1282 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1283 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1284 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1285
1286 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1287 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1288 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1289
1290 if (Depth > MaxCastDepth) {
1291 SCEV *S =
1292 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1293 UniqueSCEVs.InsertNode(S, IP);
1294 addToLoopUseLists(S);
1295 return S;
1296 }
1297
1298 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1299 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1300 // if after transforming we have at most one truncate, not counting truncates
1301 // that replace other casts.
1302 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1303 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1304 SmallVector<const SCEV *, 4> Operands;
1305 unsigned numTruncs = 0;
1306 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1307 ++i) {
1308 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1309 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1310 numTruncs++;
1311 Operands.push_back(S);
1312 }
1313 if (numTruncs < 2) {
1314 if (isa<SCEVAddExpr>(Op))
1315 return getAddExpr(Operands);
1316 else if (isa<SCEVMulExpr>(Op))
1317 return getMulExpr(Operands);
1318 else
1319 llvm_unreachable("Unexpected SCEV type for Op.")::llvm::llvm_unreachable_internal("Unexpected SCEV type for Op."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1319)
;
1320 }
1321 // Although we checked in the beginning that ID is not in the cache, it is
1322 // possible that during recursion and different modification ID was inserted
1323 // into the cache. So if we find it, just return it.
1324 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1325 return S;
1326 }
1327
1328 // If the input value is a chrec scev, truncate the chrec's operands.
1329 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1330 SmallVector<const SCEV *, 4> Operands;
1331 for (const SCEV *Op : AddRec->operands())
1332 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1333 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1334 }
1335
1336 // The cast wasn't folded; create an explicit cast node. We can reuse
1337 // the existing insert position since if we get here, we won't have
1338 // made any changes which would invalidate it.
1339 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1340 Op, Ty);
1341 UniqueSCEVs.InsertNode(S, IP);
1342 addToLoopUseLists(S);
1343 return S;
1344}
1345
1346// Get the limit of a recurrence such that incrementing by Step cannot cause
1347// signed overflow as long as the value of the recurrence within the
1348// loop does not exceed this limit before incrementing.
1349static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1350 ICmpInst::Predicate *Pred,
1351 ScalarEvolution *SE) {
1352 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1353 if (SE->isKnownPositive(Step)) {
1354 *Pred = ICmpInst::ICMP_SLT;
1355 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1356 SE->getSignedRangeMax(Step));
1357 }
1358 if (SE->isKnownNegative(Step)) {
1359 *Pred = ICmpInst::ICMP_SGT;
1360 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1361 SE->getSignedRangeMin(Step));
1362 }
1363 return nullptr;
1364}
1365
1366// Get the limit of a recurrence such that incrementing by Step cannot cause
1367// unsigned overflow as long as the value of the recurrence within the loop does
1368// not exceed this limit before incrementing.
1369static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1370 ICmpInst::Predicate *Pred,
1371 ScalarEvolution *SE) {
1372 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1373 *Pred = ICmpInst::ICMP_ULT;
1374
1375 return SE->getConstant(APInt::getMinValue(BitWidth) -
1376 SE->getUnsignedRangeMax(Step));
1377}
1378
1379namespace {
1380
1381struct ExtendOpTraitsBase {
1382 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1383 unsigned);
1384};
1385
1386// Used to make code generic over signed and unsigned overflow.
1387template <typename ExtendOp> struct ExtendOpTraits {
1388 // Members present:
1389 //
1390 // static const SCEV::NoWrapFlags WrapType;
1391 //
1392 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1393 //
1394 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1395 // ICmpInst::Predicate *Pred,
1396 // ScalarEvolution *SE);
1397};
1398
1399template <>
1400struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1401 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1402
1403 static const GetExtendExprTy GetExtendExpr;
1404
1405 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1406 ICmpInst::Predicate *Pred,
1407 ScalarEvolution *SE) {
1408 return getSignedOverflowLimitForStep(Step, Pred, SE);
1409 }
1410};
1411
1412const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1413 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1414
1415template <>
1416struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1417 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1418
1419 static const GetExtendExprTy GetExtendExpr;
1420
1421 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1422 ICmpInst::Predicate *Pred,
1423 ScalarEvolution *SE) {
1424 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1425 }
1426};
1427
1428const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1429 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1430
1431} // end anonymous namespace
1432
1433// The recurrence AR has been shown to have no signed/unsigned wrap or something
1434// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1435// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1436// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1437// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1438// expression "Step + sext/zext(PreIncAR)" is congruent with
1439// "sext/zext(PostIncAR)"
1440template <typename ExtendOpTy>
1441static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1442 ScalarEvolution *SE, unsigned Depth) {
1443 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1444 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1445
1446 const Loop *L = AR->getLoop();
1447 const SCEV *Start = AR->getStart();
1448 const SCEV *Step = AR->getStepRecurrence(*SE);
1449
1450 // Check for a simple looking step prior to loop entry.
1451 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1452 if (!SA)
1453 return nullptr;
1454
1455 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1456 // subtraction is expensive. For this purpose, perform a quick and dirty
1457 // difference, by checking for Step in the operand list.
1458 SmallVector<const SCEV *, 4> DiffOps;
1459 for (const SCEV *Op : SA->operands())
1460 if (Op != Step)
1461 DiffOps.push_back(Op);
1462
1463 if (DiffOps.size() == SA->getNumOperands())
1464 return nullptr;
1465
1466 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1467 // `Step`:
1468
1469 // 1. NSW/NUW flags on the step increment.
1470 auto PreStartFlags =
1471 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1472 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1473 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1474 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1475
1476 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1477 // "S+X does not sign/unsign-overflow".
1478 //
1479
1480 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1481 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1482 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1483 return PreStart;
1484
1485 // 2. Direct overflow check on the step operation's expression.
1486 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1487 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1488 const SCEV *OperandExtendedStart =
1489 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1490 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1491 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1492 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1493 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1494 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1495 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1496 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1497 }
1498 return PreStart;
1499 }
1500
1501 // 3. Loop precondition.
1502 ICmpInst::Predicate Pred;
1503 const SCEV *OverflowLimit =
1504 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1505
1506 if (OverflowLimit &&
1507 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1508 return PreStart;
1509
1510 return nullptr;
1511}
1512
1513// Get the normalized zero or sign extended expression for this AddRec's Start.
1514template <typename ExtendOpTy>
1515static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1516 ScalarEvolution *SE,
1517 unsigned Depth) {
1518 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1519
1520 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1521 if (!PreStart)
1522 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1523
1524 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1525 Depth),
1526 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1527}
1528
1529// Try to prove away overflow by looking at "nearby" add recurrences. A
1530// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1531// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1532//
1533// Formally:
1534//
1535// {S,+,X} == {S-T,+,X} + T
1536// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1537//
1538// If ({S-T,+,X} + T) does not overflow ... (1)
1539//
1540// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1541//
1542// If {S-T,+,X} does not overflow ... (2)
1543//
1544// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1545// == {Ext(S-T)+Ext(T),+,Ext(X)}
1546//
1547// If (S-T)+T does not overflow ... (3)
1548//
1549// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1550// == {Ext(S),+,Ext(X)} == LHS
1551//
1552// Thus, if (1), (2) and (3) are true for some T, then
1553// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1554//
1555// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1556// does not overflow" restricted to the 0th iteration. Therefore we only need
1557// to check for (1) and (2).
1558//
1559// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1560// is `Delta` (defined below).
1561template <typename ExtendOpTy>
1562bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1563 const SCEV *Step,
1564 const Loop *L) {
1565 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1566
1567 // We restrict `Start` to a constant to prevent SCEV from spending too much
1568 // time here. It is correct (but more expensive) to continue with a
1569 // non-constant `Start` and do a general SCEV subtraction to compute
1570 // `PreStart` below.
1571 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1572 if (!StartC)
1573 return false;
1574
1575 APInt StartAI = StartC->getAPInt();
1576
1577 for (unsigned Delta : {-2, -1, 1, 2}) {
1578 const SCEV *PreStart = getConstant(StartAI - Delta);
1579
1580 FoldingSetNodeID ID;
1581 ID.AddInteger(scAddRecExpr);
1582 ID.AddPointer(PreStart);
1583 ID.AddPointer(Step);
1584 ID.AddPointer(L);
1585 void *IP = nullptr;
1586 const auto *PreAR =
1587 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1588
1589 // Give up if we don't already have the add recurrence we need because
1590 // actually constructing an add recurrence is relatively expensive.
1591 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1592 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1593 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1594 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1595 DeltaS, &Pred, this);
1596 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1597 return true;
1598 }
1599 }
1600
1601 return false;
1602}
1603
1604// Finds an integer D for an expression (C + x + y + ...) such that the top
1605// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1606// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1607// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1608// the (C + x + y + ...) expression is \p WholeAddExpr.
1609static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1610 const SCEVConstant *ConstantTerm,
1611 const SCEVAddExpr *WholeAddExpr) {
1612 const APInt C = ConstantTerm->getAPInt();
1613 const unsigned BitWidth = C.getBitWidth();
1614 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1615 uint32_t TZ = BitWidth;
1616 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1617 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1618 if (TZ) {
1619 // Set D to be as many least significant bits of C as possible while still
1620 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1621 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1622 }
1623 return APInt(BitWidth, 0);
1624}
1625
1626// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1627// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1628// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1629// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1630static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1631 const APInt &ConstantStart,
1632 const SCEV *Step) {
1633 const unsigned BitWidth = ConstantStart.getBitWidth();
1634 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1635 if (TZ)
1636 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1637 : ConstantStart;
1638 return APInt(BitWidth, 0);
1639}
1640
1641const SCEV *
1642ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1643 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1644, __PRETTY_FUNCTION__))
1644 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1644, __PRETTY_FUNCTION__))
;
1645 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1646, __PRETTY_FUNCTION__))
1646 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1646, __PRETTY_FUNCTION__))
;
1647 Ty = getEffectiveSCEVType(Ty);
1648
1649 // Fold if the operand is constant.
1650 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1651 return getConstant(
1652 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1653
1654 // zext(zext(x)) --> zext(x)
1655 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1656 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1657
1658 // Before doing any expensive analysis, check to see if we've already
1659 // computed a SCEV for this Op and Ty.
1660 FoldingSetNodeID ID;
1661 ID.AddInteger(scZeroExtend);
1662 ID.AddPointer(Op);
1663 ID.AddPointer(Ty);
1664 void *IP = nullptr;
1665 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1666 if (Depth > MaxCastDepth) {
1667 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1668 Op, Ty);
1669 UniqueSCEVs.InsertNode(S, IP);
1670 addToLoopUseLists(S);
1671 return S;
1672 }
1673
1674 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1675 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1676 // It's possible the bits taken off by the truncate were all zero bits. If
1677 // so, we should be able to simplify this further.
1678 const SCEV *X = ST->getOperand();
1679 ConstantRange CR = getUnsignedRange(X);
1680 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1681 unsigned NewBits = getTypeSizeInBits(Ty);
1682 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1683 CR.zextOrTrunc(NewBits)))
1684 return getTruncateOrZeroExtend(X, Ty, Depth);
1685 }
1686
1687 // If the input value is a chrec scev, and we can prove that the value
1688 // did not overflow the old, smaller, value, we can zero extend all of the
1689 // operands (often constants). This allows analysis of something like
1690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1691 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1692 if (AR->isAffine()) {
1693 const SCEV *Start = AR->getStart();
1694 const SCEV *Step = AR->getStepRecurrence(*this);
1695 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1696 const Loop *L = AR->getLoop();
1697
1698 if (!AR->hasNoUnsignedWrap()) {
1699 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1700 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1701 }
1702
1703 // If we have special knowledge that this addrec won't overflow,
1704 // we don't need to do any further analysis.
1705 if (AR->hasNoUnsignedWrap())
1706 return getAddRecExpr(
1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1708 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1709
1710 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1711 // Note that this serves two purposes: It filters out loops that are
1712 // simply not analyzable, and it covers the case where this code is
1713 // being called from within backedge-taken count analysis, such that
1714 // attempting to ask for the backedge-taken count would likely result
1715 // in infinite recursion. In the later case, the analysis code will
1716 // cope with a conservative value, and it will take care to purge
1717 // that value once it has finished.
1718 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1719 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1720 // Manually compute the final value for AR, checking for
1721 // overflow.
1722
1723 // Check whether the backedge-taken count can be losslessly casted to
1724 // the addrec's type. The count is always unsigned.
1725 const SCEV *CastedMaxBECount =
1726 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1727 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1728 CastedMaxBECount, MaxBECount->getType(), Depth);
1729 if (MaxBECount == RecastedMaxBECount) {
1730 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1731 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1732 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1733 SCEV::FlagAnyWrap, Depth + 1);
1734 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1735 SCEV::FlagAnyWrap,
1736 Depth + 1),
1737 WideTy, Depth + 1);
1738 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1739 const SCEV *WideMaxBECount =
1740 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1741 const SCEV *OperandExtendedAdd =
1742 getAddExpr(WideStart,
1743 getMulExpr(WideMaxBECount,
1744 getZeroExtendExpr(Step, WideTy, Depth + 1),
1745 SCEV::FlagAnyWrap, Depth + 1),
1746 SCEV::FlagAnyWrap, Depth + 1);
1747 if (ZAdd == OperandExtendedAdd) {
1748 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1750 // Return the expression with the addrec on the outside.
1751 return getAddRecExpr(
1752 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1753 Depth + 1),
1754 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1755 AR->getNoWrapFlags());
1756 }
1757 // Similar to above, only this time treat the step value as signed.
1758 // This covers loops that count down.
1759 OperandExtendedAdd =
1760 getAddExpr(WideStart,
1761 getMulExpr(WideMaxBECount,
1762 getSignExtendExpr(Step, WideTy, Depth + 1),
1763 SCEV::FlagAnyWrap, Depth + 1),
1764 SCEV::FlagAnyWrap, Depth + 1);
1765 if (ZAdd == OperandExtendedAdd) {
1766 // Cache knowledge of AR NW, which is propagated to this AddRec.
1767 // Negative step causes unsigned wrap, but it still can't self-wrap.
1768 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1769 // Return the expression with the addrec on the outside.
1770 return getAddRecExpr(
1771 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1772 Depth + 1),
1773 getSignExtendExpr(Step, Ty, Depth + 1), L,
1774 AR->getNoWrapFlags());
1775 }
1776 }
1777 }
1778
1779 // Normally, in the cases we can prove no-overflow via a
1780 // backedge guarding condition, we can also compute a backedge
1781 // taken count for the loop. The exceptions are assumptions and
1782 // guards present in the loop -- SCEV is not great at exploiting
1783 // these to compute max backedge taken counts, but can still use
1784 // these to prove lack of overflow. Use this fact to avoid
1785 // doing extra work that may not pay off.
1786 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1787 !AC.assumptions().empty()) {
1788 // If the backedge is guarded by a comparison with the pre-inc
1789 // value the addrec is safe. Also, if the entry is guarded by
1790 // a comparison with the start value and the backedge is
1791 // guarded by a comparison with the post-inc value, the addrec
1792 // is safe.
1793 if (isKnownPositive(Step)) {
1794 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1795 getUnsignedRangeMax(Step));
1796 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1797 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1798 // Cache knowledge of AR NUW, which is propagated to this
1799 // AddRec.
1800 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1801 // Return the expression with the addrec on the outside.
1802 return getAddRecExpr(
1803 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1804 Depth + 1),
1805 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1806 AR->getNoWrapFlags());
1807 }
1808 } else if (isKnownNegative(Step)) {
1809 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1810 getSignedRangeMin(Step));
1811 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1812 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1813 // Cache knowledge of AR NW, which is propagated to this
1814 // AddRec. Negative step causes unsigned wrap, but it
1815 // still can't self-wrap.
1816 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1817 // Return the expression with the addrec on the outside.
1818 return getAddRecExpr(
1819 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1820 Depth + 1),
1821 getSignExtendExpr(Step, Ty, Depth + 1), L,
1822 AR->getNoWrapFlags());
1823 }
1824 }
1825 }
1826
1827 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1828 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1829 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1830 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1831 const APInt &C = SC->getAPInt();
1832 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1833 if (D != 0) {
1834 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1835 const SCEV *SResidual =
1836 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1837 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1838 return getAddExpr(SZExtD, SZExtR,
1839 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1840 Depth + 1);
1841 }
1842 }
1843
1844 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1845 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1846 return getAddRecExpr(
1847 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1848 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1849 }
1850 }
1851
1852 // zext(A % B) --> zext(A) % zext(B)
1853 {
1854 const SCEV *LHS;
1855 const SCEV *RHS;
1856 if (matchURem(Op, LHS, RHS))
1857 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1858 getZeroExtendExpr(RHS, Ty, Depth + 1));
1859 }
1860
1861 // zext(A / B) --> zext(A) / zext(B).
1862 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1863 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1864 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1865
1866 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1867 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1868 if (SA->hasNoUnsignedWrap()) {
1869 // If the addition does not unsign overflow then we can, by definition,
1870 // commute the zero extension with the addition operation.
1871 SmallVector<const SCEV *, 4> Ops;
1872 for (const auto *Op : SA->operands())
1873 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1874 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1875 }
1876
1877 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1878 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1879 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1880 //
1881 // Often address arithmetics contain expressions like
1882 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1883 // This transformation is useful while proving that such expressions are
1884 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1885 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1886 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1887 if (D != 0) {
1888 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1889 const SCEV *SResidual =
1890 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1891 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1892 return getAddExpr(SZExtD, SZExtR,
1893 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1894 Depth + 1);
1895 }
1896 }
1897 }
1898
1899 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1900 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1901 if (SM->hasNoUnsignedWrap()) {
1902 // If the multiply does not unsign overflow then we can, by definition,
1903 // commute the zero extension with the multiply operation.
1904 SmallVector<const SCEV *, 4> Ops;
1905 for (const auto *Op : SM->operands())
1906 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1907 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1908 }
1909
1910 // zext(2^K * (trunc X to iN)) to iM ->
1911 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1912 //
1913 // Proof:
1914 //
1915 // zext(2^K * (trunc X to iN)) to iM
1916 // = zext((trunc X to iN) << K) to iM
1917 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1918 // (because shl removes the top K bits)
1919 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1920 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1921 //
1922 if (SM->getNumOperands() == 2)
1923 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1924 if (MulLHS->getAPInt().isPowerOf2())
1925 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1926 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1927 MulLHS->getAPInt().logBase2();
1928 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1929 return getMulExpr(
1930 getZeroExtendExpr(MulLHS, Ty),
1931 getZeroExtendExpr(
1932 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1933 SCEV::FlagNUW, Depth + 1);
1934 }
1935 }
1936
1937 // The cast wasn't folded; create an explicit cast node.
1938 // Recompute the insert position, as it may have been invalidated.
1939 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1940 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1941 Op, Ty);
1942 UniqueSCEVs.InsertNode(S, IP);
1943 addToLoopUseLists(S);
1944 return S;
1945}
1946
1947const SCEV *
1948ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1949 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1950, __PRETTY_FUNCTION__))
1950 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1950, __PRETTY_FUNCTION__))
;
1951 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1952, __PRETTY_FUNCTION__))
1952 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1952, __PRETTY_FUNCTION__))
;
1953 Ty = getEffectiveSCEVType(Ty);
1954
1955 // Fold if the operand is constant.
1956 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1957 return getConstant(
1958 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1959
1960 // sext(sext(x)) --> sext(x)
1961 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1962 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1963
1964 // sext(zext(x)) --> zext(x)
1965 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1966 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1967
1968 // Before doing any expensive analysis, check to see if we've already
1969 // computed a SCEV for this Op and Ty.
1970 FoldingSetNodeID ID;
1971 ID.AddInteger(scSignExtend);
1972 ID.AddPointer(Op);
1973 ID.AddPointer(Ty);
1974 void *IP = nullptr;
1975 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1976 // Limit recursion depth.
1977 if (Depth > MaxCastDepth) {
1978 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1979 Op, Ty);
1980 UniqueSCEVs.InsertNode(S, IP);
1981 addToLoopUseLists(S);
1982 return S;
1983 }
1984
1985 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1986 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1987 // It's possible the bits taken off by the truncate were all sign bits. If
1988 // so, we should be able to simplify this further.
1989 const SCEV *X = ST->getOperand();
1990 ConstantRange CR = getSignedRange(X);
1991 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1992 unsigned NewBits = getTypeSizeInBits(Ty);
1993 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1994 CR.sextOrTrunc(NewBits)))
1995 return getTruncateOrSignExtend(X, Ty, Depth);
1996 }
1997
1998 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1999 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2000 if (SA->hasNoSignedWrap()) {
2001 // If the addition does not sign overflow then we can, by definition,
2002 // commute the sign extension with the addition operation.
2003 SmallVector<const SCEV *, 4> Ops;
2004 for (const auto *Op : SA->operands())
2005 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2006 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2007 }
2008
2009 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2010 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2011 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2012 //
2013 // For instance, this will bring two seemingly different expressions:
2014 // 1 + sext(5 + 20 * %x + 24 * %y) and
2015 // sext(6 + 20 * %x + 24 * %y)
2016 // to the same form:
2017 // 2 + sext(4 + 20 * %x + 24 * %y)
2018 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2019 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2020 if (D != 0) {
2021 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2022 const SCEV *SResidual =
2023 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2024 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2025 return getAddExpr(SSExtD, SSExtR,
2026 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2027 Depth + 1);
2028 }
2029 }
2030 }
2031 // If the input value is a chrec scev, and we can prove that the value
2032 // did not overflow the old, smaller, value, we can sign extend all of the
2033 // operands (often constants). This allows analysis of something like
2034 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2035 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2036 if (AR->isAffine()) {
2037 const SCEV *Start = AR->getStart();
2038 const SCEV *Step = AR->getStepRecurrence(*this);
2039 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2040 const Loop *L = AR->getLoop();
2041
2042 if (!AR->hasNoSignedWrap()) {
2043 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2044 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2045 }
2046
2047 // If we have special knowledge that this addrec won't overflow,
2048 // we don't need to do any further analysis.
2049 if (AR->hasNoSignedWrap())
2050 return getAddRecExpr(
2051 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2052 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2053
2054 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2055 // Note that this serves two purposes: It filters out loops that are
2056 // simply not analyzable, and it covers the case where this code is
2057 // being called from within backedge-taken count analysis, such that
2058 // attempting to ask for the backedge-taken count would likely result
2059 // in infinite recursion. In the later case, the analysis code will
2060 // cope with a conservative value, and it will take care to purge
2061 // that value once it has finished.
2062 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2063 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2064 // Manually compute the final value for AR, checking for
2065 // overflow.
2066
2067 // Check whether the backedge-taken count can be losslessly casted to
2068 // the addrec's type. The count is always unsigned.
2069 const SCEV *CastedMaxBECount =
2070 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2071 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2072 CastedMaxBECount, MaxBECount->getType(), Depth);
2073 if (MaxBECount == RecastedMaxBECount) {
2074 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2075 // Check whether Start+Step*MaxBECount has no signed overflow.
2076 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2077 SCEV::FlagAnyWrap, Depth + 1);
2078 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2079 SCEV::FlagAnyWrap,
2080 Depth + 1),
2081 WideTy, Depth + 1);
2082 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2083 const SCEV *WideMaxBECount =
2084 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2085 const SCEV *OperandExtendedAdd =
2086 getAddExpr(WideStart,
2087 getMulExpr(WideMaxBECount,
2088 getSignExtendExpr(Step, WideTy, Depth + 1),
2089 SCEV::FlagAnyWrap, Depth + 1),
2090 SCEV::FlagAnyWrap, Depth + 1);
2091 if (SAdd == OperandExtendedAdd) {
2092 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2093 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2094 // Return the expression with the addrec on the outside.
2095 return getAddRecExpr(
2096 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2097 Depth + 1),
2098 getSignExtendExpr(Step, Ty, Depth + 1), L,
2099 AR->getNoWrapFlags());
2100 }
2101 // Similar to above, only this time treat the step value as unsigned.
2102 // This covers loops that count up with an unsigned step.
2103 OperandExtendedAdd =
2104 getAddExpr(WideStart,
2105 getMulExpr(WideMaxBECount,
2106 getZeroExtendExpr(Step, WideTy, Depth + 1),
2107 SCEV::FlagAnyWrap, Depth + 1),
2108 SCEV::FlagAnyWrap, Depth + 1);
2109 if (SAdd == OperandExtendedAdd) {
2110 // If AR wraps around then
2111 //
2112 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2113 // => SAdd != OperandExtendedAdd
2114 //
2115 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2116 // (SAdd == OperandExtendedAdd => AR is NW)
2117
2118 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2119
2120 // Return the expression with the addrec on the outside.
2121 return getAddRecExpr(
2122 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2123 Depth + 1),
2124 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2125 AR->getNoWrapFlags());
2126 }
2127 }
2128 }
2129
2130 // Normally, in the cases we can prove no-overflow via a
2131 // backedge guarding condition, we can also compute a backedge
2132 // taken count for the loop. The exceptions are assumptions and
2133 // guards present in the loop -- SCEV is not great at exploiting
2134 // these to compute max backedge taken counts, but can still use
2135 // these to prove lack of overflow. Use this fact to avoid
2136 // doing extra work that may not pay off.
2137
2138 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2139 !AC.assumptions().empty()) {
2140 // If the backedge is guarded by a comparison with the pre-inc
2141 // value the addrec is safe. Also, if the entry is guarded by
2142 // a comparison with the start value and the backedge is
2143 // guarded by a comparison with the post-inc value, the addrec
2144 // is safe.
2145 ICmpInst::Predicate Pred;
2146 const SCEV *OverflowLimit =
2147 getSignedOverflowLimitForStep(Step, &Pred, this);
2148 if (OverflowLimit &&
2149 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2150 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2151 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2152 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2153 return getAddRecExpr(
2154 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2155 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2156 }
2157 }
2158
2159 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2160 // if D + (C - D + Step * n) could be proven to not signed wrap
2161 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2162 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2163 const APInt &C = SC->getAPInt();
2164 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2165 if (D != 0) {
2166 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2167 const SCEV *SResidual =
2168 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2169 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2170 return getAddExpr(SSExtD, SSExtR,
2171 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2172 Depth + 1);
2173 }
2174 }
2175
2176 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2177 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2178 return getAddRecExpr(
2179 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2180 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2181 }
2182 }
2183
2184 // If the input value is provably positive and we could not simplify
2185 // away the sext build a zext instead.
2186 if (isKnownNonNegative(Op))
2187 return getZeroExtendExpr(Op, Ty, Depth + 1);
2188
2189 // The cast wasn't folded; create an explicit cast node.
2190 // Recompute the insert position, as it may have been invalidated.
2191 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2192 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2193 Op, Ty);
2194 UniqueSCEVs.InsertNode(S, IP);
2195 addToLoopUseLists(S);
2196 return S;
2197}
2198
2199/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2200/// unspecified bits out to the given type.
2201const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2202 Type *Ty) {
2203 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2204, __PRETTY_FUNCTION__))
2204 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2204, __PRETTY_FUNCTION__))
;
2205 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2206, __PRETTY_FUNCTION__))
2206 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2206, __PRETTY_FUNCTION__))
;
2207 Ty = getEffectiveSCEVType(Ty);
2208
2209 // Sign-extend negative constants.
2210 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2211 if (SC->getAPInt().isNegative())
2212 return getSignExtendExpr(Op, Ty);
2213
2214 // Peel off a truncate cast.
2215 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2216 const SCEV *NewOp = T->getOperand();
2217 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2218 return getAnyExtendExpr(NewOp, Ty);
2219 return getTruncateOrNoop(NewOp, Ty);
2220 }
2221
2222 // Next try a zext cast. If the cast is folded, use it.
2223 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2224 if (!isa<SCEVZeroExtendExpr>(ZExt))
2225 return ZExt;
2226
2227 // Next try a sext cast. If the cast is folded, use it.
2228 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2229 if (!isa<SCEVSignExtendExpr>(SExt))
2230 return SExt;
2231
2232 // Force the cast to be folded into the operands of an addrec.
2233 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2234 SmallVector<const SCEV *, 4> Ops;
2235 for (const SCEV *Op : AR->operands())
2236 Ops.push_back(getAnyExtendExpr(Op, Ty));
2237 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2238 }
2239
2240 // If the expression is obviously signed, use the sext cast value.
2241 if (isa<SCEVSMaxExpr>(Op))
2242 return SExt;
2243
2244 // Absent any other information, use the zext cast value.
2245 return ZExt;
2246}
2247
2248/// Process the given Ops list, which is a list of operands to be added under
2249/// the given scale, update the given map. This is a helper function for
2250/// getAddRecExpr. As an example of what it does, given a sequence of operands
2251/// that would form an add expression like this:
2252///
2253/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2254///
2255/// where A and B are constants, update the map with these values:
2256///
2257/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2258///
2259/// and add 13 + A*B*29 to AccumulatedConstant.
2260/// This will allow getAddRecExpr to produce this:
2261///
2262/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2263///
2264/// This form often exposes folding opportunities that are hidden in
2265/// the original operand list.
2266///
2267/// Return true iff it appears that any interesting folding opportunities
2268/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2269/// the common case where no interesting opportunities are present, and
2270/// is also used as a check to avoid infinite recursion.
2271static bool
2272CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2273 SmallVectorImpl<const SCEV *> &NewOps,
2274 APInt &AccumulatedConstant,
2275 const SCEV *const *Ops, size_t NumOperands,
2276 const APInt &Scale,
2277 ScalarEvolution &SE) {
2278 bool Interesting = false;
2279
2280 // Iterate over the add operands. They are sorted, with constants first.
2281 unsigned i = 0;
2282 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2283 ++i;
2284 // Pull a buried constant out to the outside.
2285 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2286 Interesting = true;
2287 AccumulatedConstant += Scale * C->getAPInt();
2288 }
2289
2290 // Next comes everything else. We're especially interested in multiplies
2291 // here, but they're in the middle, so just visit the rest with one loop.
2292 for (; i != NumOperands; ++i) {
2293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2294 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2295 APInt NewScale =
2296 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2297 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2298 // A multiplication of a constant with another add; recurse.
2299 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2300 Interesting |=
2301 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2302 Add->op_begin(), Add->getNumOperands(),
2303 NewScale, SE);
2304 } else {
2305 // A multiplication of a constant with some other value. Update
2306 // the map.
2307 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2308 const SCEV *Key = SE.getMulExpr(MulOps);
2309 auto Pair = M.insert({Key, NewScale});
2310 if (Pair.second) {
2311 NewOps.push_back(Pair.first->first);
2312 } else {
2313 Pair.first->second += NewScale;
2314 // The map already had an entry for this value, which may indicate
2315 // a folding opportunity.
2316 Interesting = true;
2317 }
2318 }
2319 } else {
2320 // An ordinary operand. Update the map.
2321 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2322 M.insert({Ops[i], Scale});
2323 if (Pair.second) {
2324 NewOps.push_back(Pair.first->first);
2325 } else {
2326 Pair.first->second += Scale;
2327 // The map already had an entry for this value, which may indicate
2328 // a folding opportunity.
2329 Interesting = true;
2330 }
2331 }
2332 }
2333
2334 return Interesting;
2335}
2336
2337// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2338// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2339// can't-overflow flags for the operation if possible.
2340static SCEV::NoWrapFlags
2341StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2342 const ArrayRef<const SCEV *> Ops,
2343 SCEV::NoWrapFlags Flags) {
2344 using namespace std::placeholders;
2345
2346 using OBO = OverflowingBinaryOperator;
2347
2348 bool CanAnalyze =
2349 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2350 (void)CanAnalyze;
2351 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2351, __PRETTY_FUNCTION__))
;
2352
2353 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2354 SCEV::NoWrapFlags SignOrUnsignWrap =
2355 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2356
2357 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2358 auto IsKnownNonNegative = [&](const SCEV *S) {
2359 return SE->isKnownNonNegative(S);
2360 };
2361
2362 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2363 Flags =
2364 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2365
2366 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2367
2368 if (SignOrUnsignWrap != SignOrUnsignMask &&
2369 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2370 isa<SCEVConstant>(Ops[0])) {
2371
2372 auto Opcode = [&] {
2373 switch (Type) {
2374 case scAddExpr:
2375 return Instruction::Add;
2376 case scMulExpr:
2377 return Instruction::Mul;
2378 default:
2379 llvm_unreachable("Unexpected SCEV op.")::llvm::llvm_unreachable_internal("Unexpected SCEV op.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2379)
;
2380 }
2381 }();
2382
2383 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2384
2385 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2386 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2387 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2388 Opcode, C, OBO::NoSignedWrap);
2389 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2390 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2391 }
2392
2393 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2394 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2395 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2396 Opcode, C, OBO::NoUnsignedWrap);
2397 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2398 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2399 }
2400 }
2401
2402 return Flags;
2403}
2404
2405bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2406 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2407}
2408
2409/// Get a canonical add expression, or something simpler if possible.
2410const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2411 SCEV::NoWrapFlags Flags,
2412 unsigned Depth) {
2413 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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2414, __PRETTY_FUNCTION__))
2414 "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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2414, __PRETTY_FUNCTION__))
;
2415 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2415, __PRETTY_FUNCTION__))
;
2416 if (Ops.size() == 1) return Ops[0];
2417#ifndef NDEBUG
2418 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2419 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2420 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2421, __PRETTY_FUNCTION__))
2421 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2421, __PRETTY_FUNCTION__))
;
2422#endif
2423
2424 // Sort by complexity, this groups all similar expression types together.
2425 GroupByComplexity(Ops, &LI, DT);
2426
2427 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2428
2429 // If there are any constants, fold them together.
2430 unsigned Idx = 0;
2431 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2432 ++Idx;
2433 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2433, __PRETTY_FUNCTION__))
;
2434 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2435 // We found two constants, fold them together!
2436 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2437 if (Ops.size() == 2) return Ops[0];
2438 Ops.erase(Ops.begin()+1); // Erase the folded element
2439 LHSC = cast<SCEVConstant>(Ops[0]);
2440 }
2441
2442 // If we are left with a constant zero being added, strip it off.
2443 if (LHSC->getValue()->isZero()) {
2444 Ops.erase(Ops.begin());
2445 --Idx;
2446 }
2447
2448 if (Ops.size() == 1) return Ops[0];
2449 }
2450
2451 // Limit recursion calls depth.
2452 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2453 return getOrCreateAddExpr(Ops, Flags);
2454
2455 // Okay, check to see if the same value occurs in the operand list more than
2456 // once. If so, merge them together into an multiply expression. Since we
2457 // sorted the list, these values are required to be adjacent.
2458 Type *Ty = Ops[0]->getType();
2459 bool FoundMatch = false;
2460 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2461 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2462 // Scan ahead to count how many equal operands there are.
2463 unsigned Count = 2;
2464 while (i+Count != e && Ops[i+Count] == Ops[i])
2465 ++Count;
2466 // Merge the values into a multiply.
2467 const SCEV *Scale = getConstant(Ty, Count);
2468 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2469 if (Ops.size() == Count)
2470 return Mul;
2471 Ops[i] = Mul;
2472 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2473 --i; e -= Count - 1;
2474 FoundMatch = true;
2475 }
2476 if (FoundMatch)
2477 return getAddExpr(Ops, Flags, Depth + 1);
2478
2479 // Check for truncates. If all the operands are truncated from the same
2480 // type, see if factoring out the truncate would permit the result to be
2481 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2482 // if the contents of the resulting outer trunc fold to something simple.
2483 auto FindTruncSrcType = [&]() -> Type * {
2484 // We're ultimately looking to fold an addrec of truncs and muls of only
2485 // constants and truncs, so if we find any other types of SCEV
2486 // as operands of the addrec then we bail and return nullptr here.
2487 // Otherwise, we return the type of the operand of a trunc that we find.
2488 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2489 return T->getOperand()->getType();
2490 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2491 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2492 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2493 return T->getOperand()->getType();
2494 }
2495 return nullptr;
2496 };
2497 if (auto *SrcType = FindTruncSrcType()) {
2498 SmallVector<const SCEV *, 8> LargeOps;
2499 bool Ok = true;
2500 // Check all the operands to see if they can be represented in the
2501 // source type of the truncate.
2502 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2503 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2504 if (T->getOperand()->getType() != SrcType) {
2505 Ok = false;
2506 break;
2507 }
2508 LargeOps.push_back(T->getOperand());
2509 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2510 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2511 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2512 SmallVector<const SCEV *, 8> LargeMulOps;
2513 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2514 if (const SCEVTruncateExpr *T =
2515 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2516 if (T->getOperand()->getType() != SrcType) {
2517 Ok = false;
2518 break;
2519 }
2520 LargeMulOps.push_back(T->getOperand());
2521 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2522 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2523 } else {
2524 Ok = false;
2525 break;
2526 }
2527 }
2528 if (Ok)
2529 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2530 } else {
2531 Ok = false;
2532 break;
2533 }
2534 }
2535 if (Ok) {
2536 // Evaluate the expression in the larger type.
2537 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2538 // If it folds to something simple, use it. Otherwise, don't.
2539 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2540 return getTruncateExpr(Fold, Ty);
2541 }
2542 }
2543
2544 // Skip past any other cast SCEVs.
2545 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2546 ++Idx;
2547
2548 // If there are add operands they would be next.
2549 if (Idx < Ops.size()) {
2550 bool DeletedAdd = false;
2551 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2552 if (Ops.size() > AddOpsInlineThreshold ||
2553 Add->getNumOperands() > AddOpsInlineThreshold)
2554 break;
2555 // If we have an add, expand the add operands onto the end of the operands
2556 // list.
2557 Ops.erase(Ops.begin()+Idx);
2558 Ops.append(Add->op_begin(), Add->op_end());
2559 DeletedAdd = true;
2560 }
2561
2562 // If we deleted at least one add, we added operands to the end of the list,
2563 // and they are not necessarily sorted. Recurse to resort and resimplify
2564 // any operands we just acquired.
2565 if (DeletedAdd)
2566 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2567 }
2568
2569 // Skip over the add expression until we get to a multiply.
2570 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2571 ++Idx;
2572
2573 // Check to see if there are any folding opportunities present with
2574 // operands multiplied by constant values.
2575 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2576 uint64_t BitWidth = getTypeSizeInBits(Ty);
2577 DenseMap<const SCEV *, APInt> M;
2578 SmallVector<const SCEV *, 8> NewOps;
2579 APInt AccumulatedConstant(BitWidth, 0);
2580 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2581 Ops.data(), Ops.size(),
2582 APInt(BitWidth, 1), *this)) {
2583 struct APIntCompare {
2584 bool operator()(const APInt &LHS, const APInt &RHS) const {
2585 return LHS.ult(RHS);
2586 }
2587 };
2588
2589 // Some interesting folding opportunity is present, so its worthwhile to
2590 // re-generate the operands list. Group the operands by constant scale,
2591 // to avoid multiplying by the same constant scale multiple times.
2592 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2593 for (const SCEV *NewOp : NewOps)
2594 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2595 // Re-generate the operands list.
2596 Ops.clear();
2597 if (AccumulatedConstant != 0)
2598 Ops.push_back(getConstant(AccumulatedConstant));
2599 for (auto &MulOp : MulOpLists)
2600 if (MulOp.first != 0)
2601 Ops.push_back(getMulExpr(
2602 getConstant(MulOp.first),
2603 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2604 SCEV::FlagAnyWrap, Depth + 1));
2605 if (Ops.empty())
2606 return getZero(Ty);
2607 if (Ops.size() == 1)
2608 return Ops[0];
2609 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2610 }
2611 }
2612
2613 // If we are adding something to a multiply expression, make sure the
2614 // something is not already an operand of the multiply. If so, merge it into
2615 // the multiply.
2616 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2617 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2618 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2619 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2620 if (isa<SCEVConstant>(MulOpSCEV))
2621 continue;
2622 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2623 if (MulOpSCEV == Ops[AddOp]) {
2624 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2625 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2626 if (Mul->getNumOperands() != 2) {
2627 // If the multiply has more than two operands, we must get the
2628 // Y*Z term.
2629 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2630 Mul->op_begin()+MulOp);
2631 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2632 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2633 }
2634 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2635 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2636 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2637 SCEV::FlagAnyWrap, Depth + 1);
2638 if (Ops.size() == 2) return OuterMul;
2639 if (AddOp < Idx) {
2640 Ops.erase(Ops.begin()+AddOp);
2641 Ops.erase(Ops.begin()+Idx-1);
2642 } else {
2643 Ops.erase(Ops.begin()+Idx);
2644 Ops.erase(Ops.begin()+AddOp-1);
2645 }
2646 Ops.push_back(OuterMul);
2647 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2648 }
2649
2650 // Check this multiply against other multiplies being added together.
2651 for (unsigned OtherMulIdx = Idx+1;
2652 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2653 ++OtherMulIdx) {
2654 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2655 // If MulOp occurs in OtherMul, we can fold the two multiplies
2656 // together.
2657 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2658 OMulOp != e; ++OMulOp)
2659 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2660 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2661 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2662 if (Mul->getNumOperands() != 2) {
2663 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2664 Mul->op_begin()+MulOp);
2665 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2666 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2667 }
2668 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2669 if (OtherMul->getNumOperands() != 2) {
2670 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2671 OtherMul->op_begin()+OMulOp);
2672 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2673 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2674 }
2675 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2676 const SCEV *InnerMulSum =
2677 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2678 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2679 SCEV::FlagAnyWrap, Depth + 1);
2680 if (Ops.size() == 2) return OuterMul;
2681 Ops.erase(Ops.begin()+Idx);
2682 Ops.erase(Ops.begin()+OtherMulIdx-1);
2683 Ops.push_back(OuterMul);
2684 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2685 }
2686 }
2687 }
2688 }
2689
2690 // If there are any add recurrences in the operands list, see if any other
2691 // added values are loop invariant. If so, we can fold them into the
2692 // recurrence.
2693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2694 ++Idx;
2695
2696 // Scan over all recurrences, trying to fold loop invariants into them.
2697 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2698 // Scan all of the other operands to this add and add them to the vector if
2699 // they are loop invariant w.r.t. the recurrence.
2700 SmallVector<const SCEV *, 8> LIOps;
2701 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2702 const Loop *AddRecLoop = AddRec->getLoop();
2703 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2704 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2705 LIOps.push_back(Ops[i]);
2706 Ops.erase(Ops.begin()+i);
2707 --i; --e;
2708 }
2709
2710 // If we found some loop invariants, fold them into the recurrence.
2711 if (!LIOps.empty()) {
2712 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2713 LIOps.push_back(AddRec->getStart());
2714
2715 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2716 AddRec->op_end());
2717 // This follows from the fact that the no-wrap flags on the outer add
2718 // expression are applicable on the 0th iteration, when the add recurrence
2719 // will be equal to its start value.
2720 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2721
2722 // Build the new addrec. Propagate the NUW and NSW flags if both the
2723 // outer add and the inner addrec are guaranteed to have no overflow.
2724 // Always propagate NW.
2725 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2726 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2727
2728 // If all of the other operands were loop invariant, we are done.
2729 if (Ops.size() == 1) return NewRec;
2730
2731 // Otherwise, add the folded AddRec by the non-invariant parts.
2732 for (unsigned i = 0;; ++i)
2733 if (Ops[i] == AddRec) {
2734 Ops[i] = NewRec;
2735 break;
2736 }
2737 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2738 }
2739
2740 // Okay, if there weren't any loop invariants to be folded, check to see if
2741 // there are multiple AddRec's with the same loop induction variable being
2742 // added together. If so, we can fold them.
2743 for (unsigned OtherIdx = Idx+1;
2744 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2745 ++OtherIdx) {
2746 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2747 // so that the 1st found AddRecExpr is dominated by all others.
2748 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2751, __PRETTY_FUNCTION__))
2749 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2751, __PRETTY_FUNCTION__))
2750 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2751, __PRETTY_FUNCTION__))
2751 "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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2751, __PRETTY_FUNCTION__))
;
2752 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2753 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2754 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2755 AddRec->op_end());
2756 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2757 ++OtherIdx) {
2758 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2759 if (OtherAddRec->getLoop() == AddRecLoop) {
2760 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2761 i != e; ++i) {
2762 if (i >= AddRecOps.size()) {
2763 AddRecOps.append(OtherAddRec->op_begin()+i,
2764 OtherAddRec->op_end());
2765 break;
2766 }
2767 SmallVector<const SCEV *, 2> TwoOps = {
2768 AddRecOps[i], OtherAddRec->getOperand(i)};
2769 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2770 }
2771 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2772 }
2773 }
2774 // Step size has changed, so we cannot guarantee no self-wraparound.
2775 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2776 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2777 }
2778 }
2779
2780 // Otherwise couldn't fold anything into this recurrence. Move onto the
2781 // next one.
2782 }
2783
2784 // Okay, it looks like we really DO need an add expr. Check to see if we
2785 // already have one, otherwise create a new one.
2786 return getOrCreateAddExpr(Ops, Flags);
2787}
2788
2789const SCEV *
2790ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2791 SCEV::NoWrapFlags Flags) {
2792 FoldingSetNodeID ID;
2793 ID.AddInteger(scAddExpr);
2794 for (const SCEV *Op : Ops)
2795 ID.AddPointer(Op);
2796 void *IP = nullptr;
2797 SCEVAddExpr *S =
2798 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2799 if (!S) {
2800 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2801 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2802 S = new (SCEVAllocator)
2803 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2804 UniqueSCEVs.InsertNode(S, IP);
2805 addToLoopUseLists(S);
2806 }
2807 S->setNoWrapFlags(Flags);
2808 return S;
2809}
2810
2811const SCEV *
2812ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2813 const Loop *L, SCEV::NoWrapFlags Flags) {
2814 FoldingSetNodeID ID;
2815 ID.AddInteger(scAddRecExpr);
2816 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2817 ID.AddPointer(Ops[i]);
2818 ID.AddPointer(L);
2819 void *IP = nullptr;
2820 SCEVAddRecExpr *S =
2821 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2822 if (!S) {
2823 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2824 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2825 S = new (SCEVAllocator)
2826 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2827 UniqueSCEVs.InsertNode(S, IP);
2828 addToLoopUseLists(S);
2829 }
2830 S->setNoWrapFlags(Flags);
2831 return S;
2832}
2833
2834const SCEV *
2835ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2836 SCEV::NoWrapFlags Flags) {
2837 FoldingSetNodeID ID;
2838 ID.AddInteger(scMulExpr);
2839 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2840 ID.AddPointer(Ops[i]);
2841 void *IP = nullptr;
2842 SCEVMulExpr *S =
2843 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2844 if (!S) {
2845 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2846 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2847 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2848 O, Ops.size());
2849 UniqueSCEVs.InsertNode(S, IP);
2850 addToLoopUseLists(S);
2851 }
2852 S->setNoWrapFlags(Flags);
2853 return S;
2854}
2855
2856static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2857 uint64_t k = i*j;
2858 if (j > 1 && k / j != i) Overflow = true;
2859 return k;
2860}
2861
2862/// Compute the result of "n choose k", the binomial coefficient. If an
2863/// intermediate computation overflows, Overflow will be set and the return will
2864/// be garbage. Overflow is not cleared on absence of overflow.
2865static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2866 // We use the multiplicative formula:
2867 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2868 // At each iteration, we take the n-th term of the numeral and divide by the
2869 // (k-n)th term of the denominator. This division will always produce an
2870 // integral result, and helps reduce the chance of overflow in the
2871 // intermediate computations. However, we can still overflow even when the
2872 // final result would fit.
2873
2874 if (n == 0 || n == k) return 1;
2875 if (k > n) return 0;
2876
2877 if (k > n/2)
2878 k = n-k;
2879
2880 uint64_t r = 1;
2881 for (uint64_t i = 1; i <= k; ++i) {
2882 r = umul_ov(r, n-(i-1), Overflow);
2883 r /= i;
2884 }
2885 return r;
2886}
2887
2888/// Determine if any of the operands in this SCEV are a constant or if
2889/// any of the add or multiply expressions in this SCEV contain a constant.
2890static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2891 struct FindConstantInAddMulChain {
2892 bool FoundConstant = false;
2893
2894 bool follow(const SCEV *S) {
2895 FoundConstant |= isa<SCEVConstant>(S);
2896 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2897 }
2898
2899 bool isDone() const {
2900 return FoundConstant;
2901 }
2902 };
2903
2904 FindConstantInAddMulChain F;
2905 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2906 ST.visitAll(StartExpr);
2907 return F.FoundConstant;
2908}
2909
2910/// Get a canonical multiply expression, or something simpler if possible.
2911const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2912 SCEV::NoWrapFlags Flags,
2913 unsigned Depth) {
2914 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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2915, __PRETTY_FUNCTION__))
2915 "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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2915, __PRETTY_FUNCTION__))
;
2916 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2916, __PRETTY_FUNCTION__))
;
2917 if (Ops.size() == 1) return Ops[0];
2918#ifndef NDEBUG
2919 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2920 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2921 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2922, __PRETTY_FUNCTION__))
2922 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2922, __PRETTY_FUNCTION__))
;
2923#endif
2924
2925 // Sort by complexity, this groups all similar expression types together.
2926 GroupByComplexity(Ops, &LI, DT);
2927
2928 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2929
2930 // Limit recursion calls depth.
2931 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2932 return getOrCreateMulExpr(Ops, Flags);
2933
2934 // If there are any constants, fold them together.
2935 unsigned Idx = 0;
2936 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2937
2938 if (Ops.size() == 2)
2939 // C1*(C2+V) -> C1*C2 + C1*V
2940 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2941 // If any of Add's ops are Adds or Muls with a constant, apply this
2942 // transformation as well.
2943 //
2944 // TODO: There are some cases where this transformation is not
2945 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2946 // this transformation should be narrowed down.
2947 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2948 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2949 SCEV::FlagAnyWrap, Depth + 1),
2950 getMulExpr(LHSC, Add->getOperand(1),
2951 SCEV::FlagAnyWrap, Depth + 1),
2952 SCEV::FlagAnyWrap, Depth + 1);
2953
2954 ++Idx;
2955 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2956 // We found two constants, fold them together!
2957 ConstantInt *Fold =
2958 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2959 Ops[0] = getConstant(Fold);
2960 Ops.erase(Ops.begin()+1); // Erase the folded element
2961 if (Ops.size() == 1) return Ops[0];
2962 LHSC = cast<SCEVConstant>(Ops[0]);
2963 }
2964
2965 // If we are left with a constant one being multiplied, strip it off.
2966 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2967 Ops.erase(Ops.begin());
2968 --Idx;
2969 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2970 // If we have a multiply of zero, it will always be zero.
2971 return Ops[0];
2972 } else if (Ops[0]->isAllOnesValue()) {
2973 // If we have a mul by -1 of an add, try distributing the -1 among the
2974 // add operands.
2975 if (Ops.size() == 2) {
2976 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2977 SmallVector<const SCEV *, 4> NewOps;
2978 bool AnyFolded = false;
2979 for (const SCEV *AddOp : Add->operands()) {
2980 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2981 Depth + 1);
2982 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2983 NewOps.push_back(Mul);
2984 }
2985 if (AnyFolded)
2986 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2987 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2988 // Negation preserves a recurrence's no self-wrap property.
2989 SmallVector<const SCEV *, 4> Operands;
2990 for (const SCEV *AddRecOp : AddRec->operands())
2991 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2992 Depth + 1));
2993
2994 return getAddRecExpr(Operands, AddRec->getLoop(),
2995 AddRec->getNoWrapFlags(SCEV::FlagNW));
2996 }
2997 }
2998 }
2999
3000 if (Ops.size() == 1)
3001 return Ops[0];
3002 }
3003
3004 // Skip over the add expression until we get to a multiply.
3005 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3006 ++Idx;
3007
3008 // If there are mul operands inline them all into this expression.
3009 if (Idx < Ops.size()) {
3010 bool DeletedMul = false;
3011 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3012 if (Ops.size() > MulOpsInlineThreshold)
3013 break;
3014 // If we have an mul, expand the mul operands onto the end of the
3015 // operands list.
3016 Ops.erase(Ops.begin()+Idx);
3017 Ops.append(Mul->op_begin(), Mul->op_end());
3018 DeletedMul = true;
3019 }
3020
3021 // If we deleted at least one mul, we added operands to the end of the
3022 // list, and they are not necessarily sorted. Recurse to resort and
3023 // resimplify any operands we just acquired.
3024 if (DeletedMul)
3025 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3026 }
3027
3028 // If there are any add recurrences in the operands list, see if any other
3029 // added values are loop invariant. If so, we can fold them into the
3030 // recurrence.
3031 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3032 ++Idx;
3033
3034 // Scan over all recurrences, trying to fold loop invariants into them.
3035 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3036 // Scan all of the other operands to this mul and add them to the vector
3037 // if they are loop invariant w.r.t. the recurrence.
3038 SmallVector<const SCEV *, 8> LIOps;
3039 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3040 const Loop *AddRecLoop = AddRec->getLoop();
3041 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3042 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3043 LIOps.push_back(Ops[i]);
3044 Ops.erase(Ops.begin()+i);
3045 --i; --e;
3046 }
3047
3048 // If we found some loop invariants, fold them into the recurrence.
3049 if (!LIOps.empty()) {
3050 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3051 SmallVector<const SCEV *, 4> NewOps;
3052 NewOps.reserve(AddRec->getNumOperands());
3053 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3054 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3055 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3056 SCEV::FlagAnyWrap, Depth + 1));
3057
3058 // Build the new addrec. Propagate the NUW and NSW flags if both the
3059 // outer mul and the inner addrec are guaranteed to have no overflow.
3060 //
3061 // No self-wrap cannot be guaranteed after changing the step size, but
3062 // will be inferred if either NUW or NSW is true.
3063 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3064 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3065
3066 // If all of the other operands were loop invariant, we are done.
3067 if (Ops.size() == 1) return NewRec;
3068
3069 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3070 for (unsigned i = 0;; ++i)
3071 if (Ops[i] == AddRec) {
3072 Ops[i] = NewRec;
3073 break;
3074 }
3075 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3076 }
3077
3078 // Okay, if there weren't any loop invariants to be folded, check to see
3079 // if there are multiple AddRec's with the same loop induction variable
3080 // being multiplied together. If so, we can fold them.
3081
3082 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3083 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3084 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3085 // ]]],+,...up to x=2n}.
3086 // Note that the arguments to choose() are always integers with values
3087 // known at compile time, never SCEV objects.
3088 //
3089 // The implementation avoids pointless extra computations when the two
3090 // addrec's are of different length (mathematically, it's equivalent to
3091 // an infinite stream of zeros on the right).
3092 bool OpsModified = false;
3093 for (unsigned OtherIdx = Idx+1;
3094 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3095 ++OtherIdx) {
3096 const SCEVAddRecExpr *OtherAddRec =
3097 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3098 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3099 continue;
3100
3101 // Limit max number of arguments to avoid creation of unreasonably big
3102 // SCEVAddRecs with very complex operands.
3103 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3104 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3105 continue;
3106
3107 bool Overflow = false;
3108 Type *Ty = AddRec->getType();
3109 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3110 SmallVector<const SCEV*, 7> AddRecOps;
3111 for (int x = 0, xe = AddRec->getNumOperands() +
3112 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3113 SmallVector <const SCEV *, 7> SumOps;
3114 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3115 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3116 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3117 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3118 z < ze && !Overflow; ++z) {
3119 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3120 uint64_t Coeff;
3121 if (LargerThan64Bits)
3122 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3123 else
3124 Coeff = Coeff1*Coeff2;
3125 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3126 const SCEV *Term1 = AddRec->getOperand(y-z);
3127 const SCEV *Term2 = OtherAddRec->getOperand(z);
3128 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3129 SCEV::FlagAnyWrap, Depth + 1));
3130 }
3131 }
3132 if (SumOps.empty())
3133 SumOps.push_back(getZero(Ty));
3134 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3135 }
3136 if (!Overflow) {
3137 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3138 SCEV::FlagAnyWrap);
3139 if (Ops.size() == 2) return NewAddRec;
3140 Ops[Idx] = NewAddRec;
3141 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3142 OpsModified = true;
3143 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3144 if (!AddRec)
3145 break;
3146 }
3147 }
3148 if (OpsModified)
3149 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3150
3151 // Otherwise couldn't fold anything into this recurrence. Move onto the
3152 // next one.
3153 }
3154
3155 // Okay, it looks like we really DO need an mul expr. Check to see if we
3156 // already have one, otherwise create a new one.
3157 return getOrCreateMulExpr(Ops, Flags);
3158}
3159
3160/// Represents an unsigned remainder expression based on unsigned division.
3161const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3162 const SCEV *RHS) {
3163 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3165, __PRETTY_FUNCTION__))
3164 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3165, __PRETTY_FUNCTION__))
3165 "SCEVURemExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3165, __PRETTY_FUNCTION__))
;
3166
3167 // Short-circuit easy cases
3168 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3169 // If constant is one, the result is trivial
3170 if (RHSC->getValue()->isOne())
3171 return getZero(LHS->getType()); // X urem 1 --> 0
3172
3173 // If constant is a power of two, fold into a zext(trunc(LHS)).
3174 if (RHSC->getAPInt().isPowerOf2()) {
3175 Type *FullTy = LHS->getType();
3176 Type *TruncTy =
3177 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3178 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3179 }
3180 }
3181
3182 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3183 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3184 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3185 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3186}
3187
3188/// Get a canonical unsigned division expression, or something simpler if
3189/// possible.
3190const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3191 const SCEV *RHS) {
3192 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3194, __PRETTY_FUNCTION__))
3193 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3194, __PRETTY_FUNCTION__))
3194 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3194, __PRETTY_FUNCTION__))
;
3195
3196 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3197 if (RHSC->getValue()->isOne())
3198 return LHS; // X udiv 1 --> x
3199 // If the denominator is zero, the result of the udiv is undefined. Don't
3200 // try to analyze it, because the resolution chosen here may differ from
3201 // the resolution chosen in other parts of the compiler.
3202 if (!RHSC->getValue()->isZero()) {
3203 // Determine if the division can be folded into the operands of
3204 // its operands.
3205 // TODO: Generalize this to non-constants by using known-bits information.
3206 Type *Ty = LHS->getType();
3207 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3208 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3209 // For non-power-of-two values, effectively round the value up to the
3210 // nearest power of two.
3211 if (!RHSC->getAPInt().isPowerOf2())
3212 ++MaxShiftAmt;
3213 IntegerType *ExtTy =
3214 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3215 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3216 if (const SCEVConstant *Step =
3217 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3218 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3219 const APInt &StepInt = Step->getAPInt();
3220 const APInt &DivInt = RHSC->getAPInt();
3221 if (!StepInt.urem(DivInt) &&
3222 getZeroExtendExpr(AR, ExtTy) ==
3223 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3224 getZeroExtendExpr(Step, ExtTy),
3225 AR->getLoop(), SCEV::FlagAnyWrap)) {
3226 SmallVector<const SCEV *, 4> Operands;
3227 for (const SCEV *Op : AR->operands())
3228 Operands.push_back(getUDivExpr(Op, RHS));
3229 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3230 }
3231 /// Get a canonical UDivExpr for a recurrence.
3232 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3233 // We can currently only fold X%N if X is constant.
3234 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3235 if (StartC && !DivInt.urem(StepInt) &&
3236 getZeroExtendExpr(AR, ExtTy) ==
3237 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3238 getZeroExtendExpr(Step, ExtTy),
3239 AR->getLoop(), SCEV::FlagAnyWrap)) {
3240 const APInt &StartInt = StartC->getAPInt();
3241 const APInt &StartRem = StartInt.urem(StepInt);
3242 if (StartRem != 0)
3243 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3244 AR->getLoop(), SCEV::FlagNW);
3245 }
3246 }
3247 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3248 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3249 SmallVector<const SCEV *, 4> Operands;
3250 for (const SCEV *Op : M->operands())
3251 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3252 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3253 // Find an operand that's safely divisible.
3254 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3255 const SCEV *Op = M->getOperand(i);
3256 const SCEV *Div = getUDivExpr(Op, RHSC);
3257 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3258 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3259 M->op_end());
3260 Operands[i] = Div;
3261 return getMulExpr(Operands);
3262 }
3263 }
3264 }
3265
3266 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3267 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3268 if (auto *DivisorConstant =
3269 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3270 bool Overflow = false;
3271 APInt NewRHS =
3272 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3273 if (Overflow) {
3274 return getConstant(RHSC->getType(), 0, false);
3275 }
3276 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3277 }
3278 }
3279
3280 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3281 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3282 SmallVector<const SCEV *, 4> Operands;
3283 for (const SCEV *Op : A->operands())
3284 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3285 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3286 Operands.clear();
3287 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3288 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3289 if (isa<SCEVUDivExpr>(Op) ||
3290 getMulExpr(Op, RHS) != A->getOperand(i))
3291 break;
3292 Operands.push_back(Op);
3293 }
3294 if (Operands.size() == A->getNumOperands())
3295 return getAddExpr(Operands);
3296 }
3297 }
3298
3299 // Fold if both operands are constant.
3300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3301 Constant *LHSCV = LHSC->getValue();
3302 Constant *RHSCV = RHSC->getValue();
3303 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3304 RHSCV)));
3305 }
3306 }
3307 }
3308
3309 FoldingSetNodeID ID;
3310 ID.AddInteger(scUDivExpr);
3311 ID.AddPointer(LHS);
3312 ID.AddPointer(RHS);
3313 void *IP = nullptr;
3314 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3315 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3316 LHS, RHS);
3317 UniqueSCEVs.InsertNode(S, IP);
3318 addToLoopUseLists(S);
3319 return S;
3320}
3321
3322static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3323 APInt A = C1->getAPInt().abs();
3324 APInt B = C2->getAPInt().abs();
3325 uint32_t ABW = A.getBitWidth();
3326 uint32_t BBW = B.getBitWidth();
3327
3328 if (ABW > BBW)
3329 B = B.zext(ABW);
3330 else if (ABW < BBW)
3331 A = A.zext(BBW);
3332
3333 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3334}
3335
3336/// Get a canonical unsigned division expression, or something simpler if
3337/// possible. There is no representation for an exact udiv in SCEV IR, but we
3338/// can attempt to remove factors from the LHS and RHS. We can't do this when
3339/// it's not exact because the udiv may be clearing bits.
3340const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3341 const SCEV *RHS) {
3342 // TODO: we could try to find factors in all sorts of things, but for now we
3343 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3344 // end of this file for inspiration.
3345
3346 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3347 if (!Mul || !Mul->hasNoUnsignedWrap())
3348 return getUDivExpr(LHS, RHS);
3349
3350 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3351 // If the mulexpr multiplies by a constant, then that constant must be the
3352 // first element of the mulexpr.
3353 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3354 if (LHSCst == RHSCst) {
3355 SmallVector<const SCEV *, 2> Operands;
3356 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3357 return getMulExpr(Operands);
3358 }
3359
3360 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3361 // that there's a factor provided by one of the other terms. We need to
3362 // check.
3363 APInt Factor = gcd(LHSCst, RHSCst);
3364 if (!Factor.isIntN(1)) {
3365 LHSCst =
3366 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3367 RHSCst =
3368 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3369 SmallVector<const SCEV *, 2> Operands;
3370 Operands.push_back(LHSCst);
3371 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3372 LHS = getMulExpr(Operands);
3373 RHS = RHSCst;
3374 Mul = dyn_cast<SCEVMulExpr>(LHS);
3375 if (!Mul)
3376 return getUDivExactExpr(LHS, RHS);
3377 }
3378 }
3379 }
3380
3381 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3382 if (Mul->getOperand(i) == RHS) {
3383 SmallVector<const SCEV *, 2> Operands;
3384 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3385 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3386 return getMulExpr(Operands);
3387 }
3388 }
3389
3390 return getUDivExpr(LHS, RHS);
3391}
3392
3393/// Get an add recurrence expression for the specified loop. Simplify the
3394/// expression as much as possible.
3395const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3396 const Loop *L,
3397 SCEV::NoWrapFlags Flags) {
3398 SmallVector<const SCEV *, 4> Operands;
3399 Operands.push_back(Start);
3400 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3401 if (StepChrec->getLoop() == L) {
3402 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3403 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3404 }
3405
3406 Operands.push_back(Step);
3407 return getAddRecExpr(Operands, L, Flags);
3408}
3409
3410/// Get an add recurrence expression for the specified loop. Simplify the
3411/// expression as much as possible.
3412const SCEV *
3413ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3414 const Loop *L, SCEV::NoWrapFlags Flags) {
3415 if (Operands.size() == 1) return Operands[0];
3416#ifndef NDEBUG
3417 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3418 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3419 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3420, __PRETTY_FUNCTION__))
3420 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3420, __PRETTY_FUNCTION__))
;
3421 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3422 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3423, __PRETTY_FUNCTION__))
3423 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3423, __PRETTY_FUNCTION__))
;
3424#endif
3425
3426 if (Operands.back()->isZero()) {
3427 Operands.pop_back();
3428 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3429 }
3430
3431 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3432 // use that information to infer NUW and NSW flags. However, computing a
3433 // BE count requires calling getAddRecExpr, so we may not yet have a
3434 // meaningful BE count at this point (and if we don't, we'd be stuck
3435 // with a SCEVCouldNotCompute as the cached BE count).
3436
3437 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3438
3439 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3440 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3441 const Loop *NestedLoop = NestedAR->getLoop();
3442 if (L->contains(NestedLoop)
3443 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3444 : (!NestedLoop->contains(L) &&
3445 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3446 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3447 NestedAR->op_end());
3448 Operands[0] = NestedAR->getStart();
3449 // AddRecs require their operands be loop-invariant with respect to their
3450 // loops. Don't perform this transformation if it would break this
3451 // requirement.
3452 bool AllInvariant = all_of(
3453 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3454
3455 if (AllInvariant) {
3456 // Create a recurrence for the outer loop with the same step size.
3457 //
3458 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3459 // inner recurrence has the same property.
3460 SCEV::NoWrapFlags OuterFlags =
3461 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3462
3463 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3464 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3465 return isLoopInvariant(Op, NestedLoop);
3466 });
3467
3468 if (AllInvariant) {
3469 // Ok, both add recurrences are valid after the transformation.
3470 //
3471 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3472 // the outer recurrence has the same property.
3473 SCEV::NoWrapFlags InnerFlags =
3474 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3475 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3476 }
3477 }
3478 // Reset Operands to its original state.
3479 Operands[0] = NestedAR;
3480 }
3481 }
3482
3483 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3484 // already have one, otherwise create a new one.
3485 return getOrCreateAddRecExpr(Operands, L, Flags);
3486}
3487
3488const SCEV *
3489ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3490 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3491 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3492 // getSCEV(Base)->getType() has the same address space as Base->getType()
3493 // because SCEV::getType() preserves the address space.
3494 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3495 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3496 // instruction to its SCEV, because the Instruction may be guarded by control
3497 // flow and the no-overflow bits may not be valid for the expression in any
3498 // context. This can be fixed similarly to how these flags are handled for
3499 // adds.
3500 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3501 : SCEV::FlagAnyWrap;
3502
3503 const SCEV *TotalOffset = getZero(IntIdxTy);
3504 // The array size is unimportant. The first thing we do on CurTy is getting
3505 // its element type.
3506 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3507 for (const SCEV *IndexExpr : IndexExprs) {
3508 // Compute the (potentially symbolic) offset in bytes for this index.
3509 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3510 // For a struct, add the member offset.
3511 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3512 unsigned FieldNo = Index->getZExtValue();
3513 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3514
3515 // Add the field offset to the running total offset.
3516 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3517
3518 // Update CurTy to the type of the field at Index.
3519 CurTy = STy->getTypeAtIndex(Index);
3520 } else {
3521 // Update CurTy to its element type.
3522 CurTy = cast<SequentialType>(CurTy)->getElementType();
3523 // For an array, add the element offset, explicitly scaled.
3524 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3525 // Getelementptr indices are signed.
3526 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3527
3528 // Multiply the index by the element size to compute the element offset.
3529 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3530
3531 // Add the element offset to the running total offset.
3532 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3533 }
3534 }
3535
3536 // Add the total offset from all the GEP indices to the base.
3537 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3538}
3539
3540std::tuple<const SCEV *, FoldingSetNodeID, void *>
3541ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3542 ArrayRef<const SCEV *> Ops) {
3543 FoldingSetNodeID ID;
3544 void *IP = nullptr;
3545 ID.AddInteger(SCEVType);
3546 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3547 ID.AddPointer(Ops[i]);
3548 return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3549 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3550}
3551
3552const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind,
3553 SmallVectorImpl<const SCEV *> &Ops) {
3554 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!")((!Ops.empty() && "Cannot get empty (u|s)(min|max)!")
? static_cast<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty (u|s)(min|max)!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3554, __PRETTY_FUNCTION__))
;
3555 if (Ops.size() == 1) return Ops[0];
3556#ifndef NDEBUG
3557 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3558 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3559 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"Operand types don't match!") ? static_cast<void> (0) :
__assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3560, __PRETTY_FUNCTION__))
3560 "Operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"Operand types don't match!") ? static_cast<void> (0) :
__assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3560, __PRETTY_FUNCTION__))
;
3561#endif
3562
3563 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3564 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3565
3566 // Sort by complexity, this groups all similar expression types together.
3567 GroupByComplexity(Ops, &LI, DT);
3568
3569 // Check if we have created the same expression before.
3570 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3571 return S;
3572 }
3573
3574 // If there are any constants, fold them together.
3575 unsigned Idx = 0;
3576 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3577 ++Idx;
3578 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3578, __PRETTY_FUNCTION__))
;
3579 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3580 if (Kind == scSMaxExpr)
3581 return APIntOps::smax(LHS, RHS);
3582 else if (Kind == scSMinExpr)
3583 return APIntOps::smin(LHS, RHS);
3584 else if (Kind == scUMaxExpr)
3585 return APIntOps::umax(LHS, RHS);
3586 else if (Kind == scUMinExpr)
3587 return APIntOps::umin(LHS, RHS);
3588 llvm_unreachable("Unknown SCEV min/max opcode")::llvm::llvm_unreachable_internal("Unknown SCEV min/max opcode"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3588)
;
3589 };
3590
3591 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3592 // We found two constants, fold them together!
3593 ConstantInt *Fold = ConstantInt::get(
3594 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3595 Ops[0] = getConstant(Fold);
3596 Ops.erase(Ops.begin()+1); // Erase the folded element
3597 if (Ops.size() == 1) return Ops[0];
3598 LHSC = cast<SCEVConstant>(Ops[0]);
3599 }
3600
3601 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3602 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3603
3604 if (IsMax ? IsMinV : IsMaxV) {
3605 // If we are left with a constant minimum(/maximum)-int, strip it off.
3606 Ops.erase(Ops.begin());
3607 --Idx;
3608 } else if (IsMax ? IsMaxV : IsMinV) {
3609 // If we have a max(/min) with a constant maximum(/minimum)-int,
3610 // it will always be the extremum.
3611 return LHSC;
3612 }
3613
3614 if (Ops.size() == 1) return Ops[0];
3615 }
3616
3617 // Find the first operation of the same kind
3618 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3619 ++Idx;
3620
3621 // Check to see if one of the operands is of the same kind. If so, expand its
3622 // operands onto our operand list, and recurse to simplify.
3623 if (Idx < Ops.size()) {
3624 bool DeletedAny = false;
3625 while (Ops[Idx]->getSCEVType() == Kind) {
3626 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3627 Ops.erase(Ops.begin()+Idx);
3628 Ops.append(SMME->op_begin(), SMME->op_end());
3629 DeletedAny = true;
3630 }
3631
3632 if (DeletedAny)
3633 return getMinMaxExpr(Kind, Ops);
3634 }
3635
3636 // Okay, check to see if the same value occurs in the operand list twice. If
3637 // so, delete one. Since we sorted the list, these values are required to
3638 // be adjacent.
3639 llvm::CmpInst::Predicate GEPred =
3640 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3641 llvm::CmpInst::Predicate LEPred =
3642 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3643 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3644 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3645 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3646 if (Ops[i] == Ops[i + 1] ||
3647 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3648 // X op Y op Y --> X op Y
3649 // X op Y --> X, if we know X, Y are ordered appropriately
3650 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3651 --i;
3652 --e;
3653 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3654 Ops[i + 1])) {
3655 // X op Y --> Y, if we know X, Y are ordered appropriately
3656 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3657 --i;
3658 --e;
3659 }
3660 }
3661
3662 if (Ops.size() == 1) return Ops[0];
3663
3664 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3664, __PRETTY_FUNCTION__))
;
3665
3666 // Okay, it looks like we really DO need an expr. Check to see if we
3667 // already have one, otherwise create a new one.
3668 const SCEV *ExistingSCEV;
3669 FoldingSetNodeID ID;
3670 void *IP;
3671 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3672 if (ExistingSCEV)
3673 return ExistingSCEV;
3674 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3675 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3676 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3677 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3678
3679 UniqueSCEVs.InsertNode(S, IP);
3680 addToLoopUseLists(S);
3681 return S;
3682}
3683
3684const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3685 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3686 return getSMaxExpr(Ops);
3687}
3688
3689const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3690 return getMinMaxExpr(scSMaxExpr, Ops);
3691}
3692
3693const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3694 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3695 return getUMaxExpr(Ops);
3696}
3697
3698const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3699 return getMinMaxExpr(scUMaxExpr, Ops);
3700}
3701
3702const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3703 const SCEV *RHS) {
3704 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3705 return getSMinExpr(Ops);
3706}
3707
3708const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3709 return getMinMaxExpr(scSMinExpr, Ops);
3710}
3711
3712const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3713 const SCEV *RHS) {
3714 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3715 return getUMinExpr(Ops);
3716}
3717
3718const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3719 return getMinMaxExpr(scUMinExpr, Ops);
3720}
3721
3722const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3723 // We can bypass creating a target-independent
3724 // constant expression and then folding it back into a ConstantInt.
3725 // This is just a compile-time optimization.
3726 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3727}
3728
3729const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3730 StructType *STy,
3731 unsigned FieldNo) {
3732 // We can bypass creating a target-independent
3733 // constant expression and then folding it back into a ConstantInt.
3734 // This is just a compile-time optimization.
3735 return getConstant(
3736 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3737}
3738
3739const SCEV *ScalarEvolution::getUnknown(Value *V) {
3740 // Don't attempt to do anything other than create a SCEVUnknown object
3741 // here. createSCEV only calls getUnknown after checking for all other
3742 // interesting possibilities, and any other code that calls getUnknown
3743 // is doing so in order to hide a value from SCEV canonicalization.
3744
3745 FoldingSetNodeID ID;
3746 ID.AddInteger(scUnknown);
3747 ID.AddPointer(V);
3748 void *IP = nullptr;
3749 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3750 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3751, __PRETTY_FUNCTION__))
3751 "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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3751, __PRETTY_FUNCTION__))
;
3752 return S;
3753 }
3754 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3755 FirstUnknown);
3756 FirstUnknown = cast<SCEVUnknown>(S);
3757 UniqueSCEVs.InsertNode(S, IP);
3758 return S;
3759}
3760
3761//===----------------------------------------------------------------------===//
3762// Basic SCEV Analysis and PHI Idiom Recognition Code
3763//
3764
3765/// Test if values of the given type are analyzable within the SCEV
3766/// framework. This primarily includes integer types, and it can optionally
3767/// include pointer types if the ScalarEvolution class has access to
3768/// target-specific information.
3769bool ScalarEvolution::isSCEVable(Type *Ty) const {
3770 // Integers and pointers are always SCEVable.
3771 return Ty->isIntOrPtrTy();
2
Calling 'Type::isIntOrPtrTy'
4
Returning from 'Type::isIntOrPtrTy'
5
Returning the value 1, which participates in a condition later
3772}
3773
3774/// Return the size in bits of the specified type, for which isSCEVable must
3775/// return true.
3776uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3777 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3777, __PRETTY_FUNCTION__))
;
3778 if (Ty->isPointerTy())
3779 return getDataLayout().getIndexTypeSizeInBits(Ty);
3780 return getDataLayout().getTypeSizeInBits(Ty);
3781}
3782
3783/// Return a type with the same bitwidth as the given type and which represents
3784/// how SCEV will treat the given type, for which isSCEVable must return
3785/// true. For pointer types, this is the pointer index sized integer type.
3786Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3787 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3787, __PRETTY_FUNCTION__))
;
3788
3789 if (Ty->isIntegerTy())
3790 return Ty;
3791
3792 // The only other support type is pointer.
3793 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3793, __PRETTY_FUNCTION__))
;
3794 return getDataLayout().getIndexType(Ty);
3795}
3796
3797Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3798 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3799}
3800
3801const SCEV *ScalarEvolution::getCouldNotCompute() {
3802 return CouldNotCompute.get();
3803}
3804
3805bool ScalarEvolution::checkValidity(const SCEV *S) const {
3806 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3807 auto *SU = dyn_cast<SCEVUnknown>(S);
3808 return SU && SU->getValue() == nullptr;
3809 });
3810
3811 return !ContainsNulls;
3812}
3813
3814bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3815 HasRecMapType::iterator I = HasRecMap.find(S);
3816 if (I != HasRecMap.end())
3817 return I->second;
3818
3819 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3820 HasRecMap.insert({S, FoundAddRec});
3821 return FoundAddRec;
3822}
3823
3824/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3825/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3826/// offset I, then return {S', I}, else return {\p S, nullptr}.
3827static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3828 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3829 if (!Add)
3830 return {S, nullptr};
3831
3832 if (Add->getNumOperands() != 2)
3833 return {S, nullptr};
3834
3835 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3836 if (!ConstOp)
3837 return {S, nullptr};
3838
3839 return {Add->getOperand(1), ConstOp->getValue()};
3840}
3841
3842/// Return the ValueOffsetPair set for \p S. \p S can be represented
3843/// by the value and offset from any ValueOffsetPair in the set.
3844SetVector<ScalarEvolution::ValueOffsetPair> *
3845ScalarEvolution::getSCEVValues(const SCEV *S) {
3846 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3847 if (SI == ExprValueMap.end())
3848 return nullptr;
3849#ifndef NDEBUG
3850 if (VerifySCEVMap) {
3851 // Check there is no dangling Value in the set returned.
3852 for (const auto &VE : SI->second)
3853 assert(ValueExprMap.count(VE.first))((ValueExprMap.count(VE.first)) ? static_cast<void> (0)
: __assert_fail ("ValueExprMap.count(VE.first)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3853, __PRETTY_FUNCTION__))
;
3854 }
3855#endif
3856 return &SI->second;
3857}
3858
3859/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3860/// cannot be used separately. eraseValueFromMap should be used to remove
3861/// V from ValueExprMap and ExprValueMap at the same time.
3862void ScalarEvolution::eraseValueFromMap(Value *V) {
3863 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3864 if (I != ValueExprMap.end()) {
3865 const SCEV *S = I->second;
3866 // Remove {V, 0} from the set of ExprValueMap[S]
3867 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3868 SV->remove({V, nullptr});
3869
3870 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3871 const SCEV *Stripped;
3872 ConstantInt *Offset;
3873 std::tie(Stripped, Offset) = splitAddExpr(S);
3874 if (Offset != nullptr) {
3875 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3876 SV->remove({V, Offset});
3877 }
3878 ValueExprMap.erase(V);
3879 }
3880}
3881
3882/// Check whether value has nuw/nsw/exact set but SCEV does not.
3883/// TODO: In reality it is better to check the poison recursively
3884/// but this is better than nothing.
3885static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3886 if (auto *I = dyn_cast<Instruction>(V)) {
3887 if (isa<OverflowingBinaryOperator>(I)) {
3888 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3889 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3890 return true;
3891 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3892 return true;
3893 }
3894 } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3895 return true;
3896 }
3897 return false;
3898}
3899
3900/// Return an existing SCEV if it exists, otherwise analyze the expression and
3901/// create a new one.
3902const SCEV *ScalarEvolution::getSCEV(Value *V) {
3903 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3903, __PRETTY_FUNCTION__))
;
3904
3905 const SCEV *S = getExistingSCEV(V);
3906 if (S == nullptr) {
3907 S = createSCEV(V);
3908 // During PHI resolution, it is possible to create two SCEVs for the same
3909 // V, so it is needed to double check whether V->S is inserted into
3910 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3911 std::pair<ValueExprMapType::iterator, bool> Pair =
3912 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3913 if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3914 ExprValueMap[S].insert({V, nullptr});
3915
3916 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3917 // ExprValueMap.
3918 const SCEV *Stripped = S;
3919 ConstantInt *Offset = nullptr;
3920 std::tie(Stripped, Offset) = splitAddExpr(S);
3921 // If stripped is SCEVUnknown, don't bother to save
3922 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3923 // increase the complexity of the expansion code.
3924 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3925 // because it may generate add/sub instead of GEP in SCEV expansion.
3926 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3927 !isa<GetElementPtrInst>(V))
3928 ExprValueMap[Stripped].insert({V, Offset});
3929 }
3930 }
3931 return S;
3932}
3933
3934const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3935 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3935, __PRETTY_FUNCTION__))
;
3936
3937 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3938 if (I != ValueExprMap.end()) {
3939 const SCEV *S = I->second;
3940 if (checkValidity(S))
3941 return S;
3942 eraseValueFromMap(V);
3943 forgetMemoizedResults(S);
3944 }
3945 return nullptr;
3946}
3947
3948/// Return a SCEV corresponding to -V = -1*V
3949const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3950 SCEV::NoWrapFlags Flags) {
3951 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3952 return getConstant(
3953 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3954
3955 Type *Ty = V->getType();
3956 Ty = getEffectiveSCEVType(Ty);
3957 return getMulExpr(
3958 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3959}
3960
3961/// If Expr computes ~A, return A else return nullptr
3962static const SCEV *MatchNotExpr(const SCEV *Expr) {
3963 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3964 if (!Add || Add->getNumOperands() != 2 ||
3965 !Add->getOperand(0)->isAllOnesValue())
3966 return nullptr;
3967
3968 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3969 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3970 !AddRHS->getOperand(0)->isAllOnesValue())
3971 return nullptr;
3972
3973 return AddRHS->getOperand(1);
3974}
3975
3976/// Return a SCEV corresponding to ~V = -1-V
3977const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3978 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3979 return getConstant(
3980 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3981
3982 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3983 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3984 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3985 SmallVector<const SCEV *, 2> MatchedOperands;
3986 for (const SCEV *Operand : MME->operands()) {
3987 const SCEV *Matched = MatchNotExpr(Operand);
3988 if (!Matched)
3989 return (const SCEV *)nullptr;
3990 MatchedOperands.push_back(Matched);
3991 }
3992 return getMinMaxExpr(
3993 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3994 MatchedOperands);
3995 };
3996 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3997 return Replaced;
3998 }
3999
4000 Type *Ty = V->getType();
4001 Ty = getEffectiveSCEVType(Ty);
4002 const SCEV *AllOnes =
4003 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
4004 return getMinusSCEV(AllOnes, V);
4005}
4006
4007const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4008 SCEV::NoWrapFlags Flags,
4009 unsigned Depth) {
4010 // Fast path: X - X --> 0.
4011 if (LHS == RHS)
4012 return getZero(LHS->getType());
4013
4014 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4015 // makes it so that we cannot make much use of NUW.
4016 auto AddFlags = SCEV::FlagAnyWrap;
4017 const bool RHSIsNotMinSigned =
4018 !getSignedRangeMin(RHS).isMinSignedValue();
4019 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4020 // Let M be the minimum representable signed value. Then (-1)*RHS
4021 // signed-wraps if and only if RHS is M. That can happen even for
4022 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4023 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4024 // (-1)*RHS, we need to prove that RHS != M.
4025 //
4026 // If LHS is non-negative and we know that LHS - RHS does not
4027 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4028 // either by proving that RHS > M or that LHS >= 0.
4029 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4030 AddFlags = SCEV::FlagNSW;
4031 }
4032 }
4033
4034 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4035 // RHS is NSW and LHS >= 0.
4036 //
4037 // The difficulty here is that the NSW flag may have been proven
4038 // relative to a loop that is to be found in a recurrence in LHS and
4039 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4040 // larger scope than intended.
4041 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4042
4043 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4044}
4045
4046const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4047 unsigned Depth) {
4048 Type *SrcTy = V->getType();
4049 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4050, __PRETTY_FUNCTION__))
4050 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4050, __PRETTY_FUNCTION__))
;
4051 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4052 return V; // No conversion
4053 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4054 return getTruncateExpr(V, Ty, Depth);
4055 return getZeroExtendExpr(V, Ty, Depth);
4056}
4057
4058const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4059 unsigned Depth) {
4060 Type *SrcTy = V->getType();
4061 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4062, __PRETTY_FUNCTION__))
4062 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4062, __PRETTY_FUNCTION__))
;
4063 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4064 return V; // No conversion
4065 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4066 return getTruncateExpr(V, Ty, Depth);
4067 return getSignExtendExpr(V, Ty, Depth);
4068}
4069
4070const SCEV *
4071ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4072 Type *SrcTy = V->getType();
4073 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4074, __PRETTY_FUNCTION__))
4074 "Cannot noop or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4074, __PRETTY_FUNCTION__))
;
4075 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4076, __PRETTY_FUNCTION__))
4076 "getNoopOrZeroExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4076, __PRETTY_FUNCTION__))
;
4077 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4078 return V; // No conversion
4079 return getZeroExtendExpr(V, Ty);
4080}
4081
4082const SCEV *
4083ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4084 Type *SrcTy = V->getType();
4085 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4086, __PRETTY_FUNCTION__))
4086 "Cannot noop or sign extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4086, __PRETTY_FUNCTION__))
;
4087 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4088, __PRETTY_FUNCTION__))
4088 "getNoopOrSignExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4088, __PRETTY_FUNCTION__))
;
4089 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4090 return V; // No conversion
4091 return getSignExtendExpr(V, Ty);
4092}
4093
4094const SCEV *
4095ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4096 Type *SrcTy = V->getType();
4097 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4098, __PRETTY_FUNCTION__))
4098 "Cannot noop or any extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4098, __PRETTY_FUNCTION__))
;
4099 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4100, __PRETTY_FUNCTION__))
4100 "getNoopOrAnyExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4100, __PRETTY_FUNCTION__))
;
4101 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4102 return V; // No conversion
4103 return getAnyExtendExpr(V, Ty);
4104}
4105
4106const SCEV *
4107ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4108 Type *SrcTy = V->getType();
4109 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4110, __PRETTY_FUNCTION__))
4110 "Cannot truncate or noop with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4110, __PRETTY_FUNCTION__))
;
4111 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!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4112, __PRETTY_FUNCTION__))
4112 "getTruncateOrNoop cannot extend!")((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4112, __PRETTY_FUNCTION__))
;
4113 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4114 return V; // No conversion
4115 return getTruncateExpr(V, Ty);
4116}
4117
4118const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4119 const SCEV *RHS) {
4120 const SCEV *PromotedLHS = LHS;
4121 const SCEV *PromotedRHS = RHS;
4122
4123 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4124 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4125 else
4126 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4127
4128 return getUMaxExpr(PromotedLHS, PromotedRHS);
4129}
4130
4131const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4132 const SCEV *RHS) {
4133 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4134 return getUMinFromMismatchedTypes(Ops);
4135}
4136
4137const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4138 SmallVectorImpl<const SCEV *> &Ops) {
4139 assert(!Ops.empty() && "At least one operand must be!")((!Ops.empty() && "At least one operand must be!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"At least one operand must be!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4139, __PRETTY_FUNCTION__))
;
4140 // Trivial case.
4141 if (Ops.size() == 1)
4142 return Ops[0];
4143
4144 // Find the max type first.
4145 Type *MaxType = nullptr;
4146 for (auto *S : Ops)
4147 if (MaxType)
4148 MaxType = getWiderType(MaxType, S->getType());
4149 else
4150 MaxType = S->getType();
4151
4152 // Extend all ops to max type.
4153 SmallVector<const SCEV *, 2> PromotedOps;
4154 for (auto *S : Ops)
4155 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4156
4157 // Generate umin.
4158 return getUMinExpr(PromotedOps);
4159}
4160
4161const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4162 // A pointer operand may evaluate to a nonpointer expression, such as null.
4163 if (!V->getType()->isPointerTy())
4164 return V;
4165
4166 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4167 return getPointerBase(Cast->getOperand());
4168 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4169 const SCEV *PtrOp = nullptr;
4170 for (const SCEV *NAryOp : NAry->operands()) {
4171 if (NAryOp->getType()->isPointerTy()) {
4172 // Cannot find the base of an expression with multiple pointer operands.
4173 if (PtrOp)
4174 return V;
4175 PtrOp = NAryOp;
4176 }
4177 }
4178 if (!PtrOp)
4179 return V;
4180 return getPointerBase(PtrOp);
4181 }
4182 return V;
4183}
4184
4185/// Push users of the given Instruction onto the given Worklist.
4186static void
4187PushDefUseChildren(Instruction *I,
4188 SmallVectorImpl<Instruction *> &Worklist) {
4189 // Push the def-use children onto the Worklist stack.
4190 for (User *U : I->users())
4191 Worklist.push_back(cast<Instruction>(U));
4192}
4193
4194void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4195 SmallVector<Instruction *, 16> Worklist;
4196 PushDefUseChildren(PN, Worklist);
4197
4198 SmallPtrSet<Instruction *, 8> Visited;
4199 Visited.insert(PN);
4200 while (!Worklist.empty()) {
4201 Instruction *I = Worklist.pop_back_val();
4202 if (!Visited.insert(I).second)
4203 continue;
4204
4205 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4206 if (It != ValueExprMap.end()) {
4207 const SCEV *Old = It->second;
4208
4209 // Short-circuit the def-use traversal if the symbolic name
4210 // ceases to appear in expressions.
4211 if (Old != SymName && !hasOperand(Old, SymName))
4212 continue;
4213
4214 // SCEVUnknown for a PHI either means that it has an unrecognized
4215 // structure, it's a PHI that's in the progress of being computed
4216 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4217 // additional loop trip count information isn't going to change anything.
4218 // In the second case, createNodeForPHI will perform the necessary
4219 // updates on its own when it gets to that point. In the third, we do
4220 // want to forget the SCEVUnknown.
4221 if (!isa<PHINode>(I) ||
4222 !isa<SCEVUnknown>(Old) ||
4223 (I != PN && Old == SymName)) {
4224 eraseValueFromMap(It->first);
4225 forgetMemoizedResults(Old);
4226 }
4227 }
4228
4229 PushDefUseChildren(I, Worklist);
4230 }
4231}
4232
4233namespace {
4234
4235/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4236/// expression in case its Loop is L. If it is not L then
4237/// if IgnoreOtherLoops is true then use AddRec itself
4238/// otherwise rewrite cannot be done.
4239/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4240class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4241public:
4242 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4243 bool IgnoreOtherLoops = true) {
4244 SCEVInitRewriter Rewriter(L, SE);
4245 const SCEV *Result = Rewriter.visit(S);
4246 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4247 return SE.getCouldNotCompute();
4248 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4249 ? SE.getCouldNotCompute()
4250 : Result;
4251 }
4252
4253 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4254 if (!SE.isLoopInvariant(Expr, L))
4255 SeenLoopVariantSCEVUnknown = true;
4256 return Expr;
4257 }
4258
4259 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4260 // Only re-write AddRecExprs for this loop.
4261 if (Expr->getLoop() == L)
4262 return Expr->getStart();
4263 SeenOtherLoops = true;
4264 return Expr;
4265 }
4266
4267 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4268
4269 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4270
4271private:
4272 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4273 : SCEVRewriteVisitor(SE), L(L) {}
4274
4275 const Loop *L;
4276 bool SeenLoopVariantSCEVUnknown = false;
4277 bool SeenOtherLoops = false;
4278};
4279
4280/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4281/// increment expression in case its Loop is L. If it is not L then
4282/// use AddRec itself.
4283/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4284class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4285public:
4286 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4287 SCEVPostIncRewriter Rewriter(L, SE);
4288 const SCEV *Result = Rewriter.visit(S);
4289 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4290 ? SE.getCouldNotCompute()
4291 : Result;
4292 }
4293
4294 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4295 if (!SE.isLoopInvariant(Expr, L))
4296 SeenLoopVariantSCEVUnknown = true;
4297 return Expr;
4298 }
4299
4300 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4301 // Only re-write AddRecExprs for this loop.
4302 if (Expr->getLoop() == L)
4303 return Expr->getPostIncExpr(SE);
4304 SeenOtherLoops = true;
4305 return Expr;
4306 }
4307
4308 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4309
4310 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4311
4312private:
4313 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4314 : SCEVRewriteVisitor(SE), L(L) {}
4315
4316 const Loop *L;
4317 bool SeenLoopVariantSCEVUnknown = false;
4318 bool SeenOtherLoops = false;
4319};
4320
4321/// This class evaluates the compare condition by matching it against the
4322/// condition of loop latch. If there is a match we assume a true value
4323/// for the condition while building SCEV nodes.
4324class SCEVBackedgeConditionFolder
4325 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4326public:
4327 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4328 ScalarEvolution &SE) {
4329 bool IsPosBECond = false;
4330 Value *BECond = nullptr;
4331 if (BasicBlock *Latch = L->getLoopLatch()) {
4332 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4333 if (BI && BI->isConditional()) {
4334 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4335, __PRETTY_FUNCTION__))
4335 "Both outgoing branches should not target same header!")((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4335, __PRETTY_FUNCTION__))
;
4336 BECond = BI->getCondition();
4337 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4338 } else {
4339 return S;
4340 }
4341 }
4342 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4343 return Rewriter.visit(S);
4344 }
4345
4346 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4347 const SCEV *Result = Expr;
4348 bool InvariantF = SE.isLoopInvariant(Expr, L);
4349
4350 if (!InvariantF) {
4351 Instruction *I = cast<Instruction>(Expr->getValue());
4352 switch (I->getOpcode()) {
4353 case Instruction::Select: {
4354 SelectInst *SI = cast<SelectInst>(I);
4355 Optional<const SCEV *> Res =
4356 compareWithBackedgeCondition(SI->getCondition());
4357 if (Res.hasValue()) {
4358 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4359 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4360 }
4361 break;
4362 }
4363 default: {
4364 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4365 if (Res.hasValue())
4366 Result = Res.getValue();
4367 break;
4368 }
4369 }
4370 }
4371 return Result;
4372 }
4373
4374private:
4375 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4376 bool IsPosBECond, ScalarEvolution &SE)
4377 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4378 IsPositiveBECond(IsPosBECond) {}
4379
4380 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4381
4382 const Loop *L;
4383 /// Loop back condition.
4384 Value *BackedgeCond = nullptr;
4385 /// Set to true if loop back is on positive branch condition.
4386 bool IsPositiveBECond;
4387};
4388
4389Optional<const SCEV *>
4390SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4391
4392 // If value matches the backedge condition for loop latch,
4393 // then return a constant evolution node based on loopback
4394 // branch taken.
4395 if (BackedgeCond == IC)
4396 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4397 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4398 return None;
4399}
4400
4401class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4402public:
4403 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4404 ScalarEvolution &SE) {
4405 SCEVShiftRewriter Rewriter(L, SE);
4406 const SCEV *Result = Rewriter.visit(S);
4407 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4408 }
4409
4410 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4411 // Only allow AddRecExprs for this loop.
4412 if (!SE.isLoopInvariant(Expr, L))
4413 Valid = false;
4414 return Expr;
4415 }
4416
4417 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4418 if (Expr->getLoop() == L && Expr->isAffine())
4419 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4420 Valid = false;
4421 return Expr;
4422 }
4423
4424 bool isValid() { return Valid; }
4425
4426private:
4427 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4428 : SCEVRewriteVisitor(SE), L(L) {}
4429
4430 const Loop *L;
4431 bool Valid = true;
4432};
4433
4434} // end anonymous namespace
4435
4436SCEV::NoWrapFlags
4437ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4438 if (!AR->isAffine())
4439 return SCEV::FlagAnyWrap;
4440
4441 using OBO = OverflowingBinaryOperator;
4442
4443 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4444
4445 if (!AR->hasNoSignedWrap()) {
4446 ConstantRange AddRecRange = getSignedRange(AR);
4447 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4448
4449 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4450 Instruction::Add, IncRange, OBO::NoSignedWrap);
4451 if (NSWRegion.contains(AddRecRange))
4452 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4453 }
4454
4455 if (!AR->hasNoUnsignedWrap()) {
4456 ConstantRange AddRecRange = getUnsignedRange(AR);
4457 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4458
4459 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4460 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4461 if (NUWRegion.contains(AddRecRange))
4462 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4463 }
4464
4465 return Result;
4466}
4467
4468namespace {
4469
4470/// Represents an abstract binary operation. This may exist as a
4471/// normal instruction or constant expression, or may have been
4472/// derived from an expression tree.
4473struct BinaryOp {
4474 unsigned Opcode;
4475 Value *LHS;
4476 Value *RHS;
4477 bool IsNSW = false;
4478 bool IsNUW = false;
4479
4480 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4481 /// constant expression.
4482 Operator *Op = nullptr;
4483
4484 explicit BinaryOp(Operator *Op)
4485 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4486 Op(Op) {
4487 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4488 IsNSW = OBO->hasNoSignedWrap();
4489 IsNUW = OBO->hasNoUnsignedWrap();
4490 }
4491 }
4492
4493 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4494 bool IsNUW = false)
4495 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4496};
4497
4498} // end anonymous namespace
4499
4500/// Try to map \p V into a BinaryOp, and return \c None on failure.
4501static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4502 auto *Op = dyn_cast<Operator>(V);
20
Assuming 'V' is a 'Operator'
4503 if (!Op
20.1
'Op' is non-null
20.1
'Op' is non-null
20.1
'Op' is non-null
20.1
'Op' is non-null
20.1
'Op' is non-null
)
21
Taking false branch
4504 return None;
4505
4506 // Implementation detail: all the cleverness here should happen without
4507 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4508 // SCEV expressions when possible, and we should not break that.
4509
4510 switch (Op->getOpcode()) {
22
Control jumps to 'case ExtractValue:' at line 4548
4511 case Instruction::Add:
4512 case Instruction::Sub:
4513 case Instruction::Mul:
4514 case Instruction::UDiv:
4515 case Instruction::URem:
4516 case Instruction::And:
4517 case Instruction::Or:
4518 case Instruction::AShr:
4519 case Instruction::Shl:
4520 return BinaryOp(Op);
4521
4522 case Instruction::Xor:
4523 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4524 // If the RHS of the xor is a signmask, then this is just an add.
4525 // Instcombine turns add of signmask into xor as a strength reduction step.
4526 if (RHSC->getValue().isSignMask())
4527 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4528 return BinaryOp(Op);
4529
4530 case Instruction::LShr:
4531 // Turn logical shift right of a constant into a unsigned divide.
4532 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4533 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4534
4535 // If the shift count is not less than the bitwidth, the result of
4536 // the shift is undefined. Don't try to analyze it, because the
4537 // resolution chosen here may differ from the resolution chosen in
4538 // other parts of the compiler.
4539 if (SA->getValue().ult(BitWidth)) {
4540 Constant *X =
4541 ConstantInt::get(SA->getContext(),
4542 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4543 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4544 }
4545 }
4546 return BinaryOp(Op);
4547
4548 case Instruction::ExtractValue: {
4549 auto *EVI = cast<ExtractValueInst>(Op);
23
'Op' is a 'ExtractValueInst'
4550 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
24
Assuming the condition is false
25
Assuming the condition is false
26
Taking false branch
4551 break;
4552
4553 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4554 if (!WO)
27
Assuming 'WO' is non-null
28
Taking false branch
4555 break;
4556
4557 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4558 bool Signed = WO->isSigned();
4559 // TODO: Should add nuw/nsw flags for mul as well.
4560 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
29
Assuming 'BinOp' is not equal to Mul, which participates in a condition later
30
Assuming the condition is false
31
Taking false branch
4561 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4562
4563 // Now that we know that all uses of the arithmetic-result component of
4564 // CI are guarded by the overflow check, we can go ahead and pretend
4565 // that the arithmetic is non-overflowing.
4566 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
33
Calling constructor for 'Optional<(anonymous namespace)::BinaryOp>'
38
Returning from constructor for 'Optional<(anonymous namespace)::BinaryOp>'
4567 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
32
Assuming 'Signed' is true
4568 }
4569
4570 default:
4571 break;
4572 }
4573
4574 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4575 // semantics as a Sub, return a binary sub expression.
4576 if (auto *II = dyn_cast<IntrinsicInst>(V))
4577 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4578 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4579
4580 return None;
4581}
4582
4583/// Helper function to createAddRecFromPHIWithCasts. We have a phi
4584/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4585/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4586/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4587/// follows one of the following patterns:
4588/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4589/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4590/// If the SCEV expression of \p Op conforms with one of the expected patterns
4591/// we return the type of the truncation operation, and indicate whether the
4592/// truncated type should be treated as signed/unsigned by setting
4593/// \p Signed to true/false, respectively.
4594static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4595 bool &Signed, ScalarEvolution &SE) {
4596 // The case where Op == SymbolicPHI (that is, with no type conversions on
4597 // the way) is handled by the regular add recurrence creating logic and
4598 // would have already been triggered in createAddRecForPHI. Reaching it here
4599 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4600 // because one of the other operands of the SCEVAddExpr updating this PHI is
4601 // not invariant).
4602 //
4603 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4604 // this case predicates that allow us to prove that Op == SymbolicPHI will
4605 // be added.
4606 if (Op == SymbolicPHI)
4607 return nullptr;
4608
4609 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4610 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4611 if (SourceBits != NewBits)
4612 return nullptr;
4613
4614 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4615 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4616 if (!SExt && !ZExt)
4617 return nullptr;
4618 const SCEVTruncateExpr *Trunc =
4619 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4620 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4621 if (!Trunc)
4622 return nullptr;
4623 const SCEV *X = Trunc->getOperand();
4624 if (X != SymbolicPHI)
4625 return nullptr;
4626 Signed = SExt != nullptr;
4627 return Trunc->getType();
4628}
4629
4630static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4631 if (!PN->getType()->isIntegerTy())
4632 return nullptr;
4633 const Loop *L = LI.getLoopFor(PN->getParent());
4634 if (!L || L->getHeader() != PN->getParent())
4635 return nullptr;
4636 return L;
4637}
4638
4639// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4640// computation that updates the phi follows the following pattern:
4641// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4642// which correspond to a phi->trunc->sext/zext->add->phi update chain.
4643// If so, try to see if it can be rewritten as an AddRecExpr under some
4644// Predicates. If successful, return them as a pair. Also cache the results
4645// of the analysis.
4646//
4647// Example usage scenario:
4648// Say the Rewriter is called for the following SCEV:
4649// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4650// where:
4651// %X = phi i64 (%Start, %BEValue)
4652// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4653// and call this function with %SymbolicPHI = %X.
4654//
4655// The analysis will find that the value coming around the backedge has
4656// the following SCEV:
4657// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4658// Upon concluding that this matches the desired pattern, the function
4659// will return the pair {NewAddRec, SmallPredsVec} where:
4660// NewAddRec = {%Start,+,%Step}
4661// SmallPredsVec = {P1, P2, P3} as follows:
4662// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4663// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4664// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4665// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4666// under the predicates {P1,P2,P3}.
4667// This predicated rewrite will be cached in PredicatedSCEVRewrites:
4668// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4669//
4670// TODO's:
4671//
4672// 1) Extend the Induction descriptor to also support inductions that involve
4673// casts: When needed (namely, when we are called in the context of the
4674// vectorizer induction analysis), a Set of cast instructions will be
4675// populated by this method, and provided back to isInductionPHI. This is
4676// needed to allow the vectorizer to properly record them to be ignored by
4677// the cost model and to avoid vectorizing them (otherwise these casts,
4678// which are redundant under the runtime overflow checks, will be
4679// vectorized, which can be costly).
4680//
4681// 2) Support additional induction/PHISCEV patterns: We also want to support
4682// inductions where the sext-trunc / zext-trunc operations (partly) occur
4683// after the induction update operation (the induction increment):
4684//
4685// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4686// which correspond to a phi->add->trunc->sext/zext->phi update chain.
4687//
4688// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4689// which correspond to a phi->trunc->add->sext/zext->phi update chain.
4690//
4691// 3) Outline common code with createAddRecFromPHI to avoid duplication.
4692Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4693ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4694 SmallVector<const SCEVPredicate *, 3> Predicates;
4695
4696 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4697 // return an AddRec expression under some predicate.
4698
4699 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4700 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4701 assert(L && "Expecting an integer loop header phi")((L && "Expecting an integer loop header phi") ? static_cast
<void> (0) : __assert_fail ("L && \"Expecting an integer loop header phi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4701, __PRETTY_FUNCTION__))
;
4702
4703 // The loop may have multiple entrances or multiple exits; we can analyze
4704 // this phi as an addrec if it has a unique entry value and a unique
4705 // backedge value.
4706 Value *BEValueV = nullptr, *StartValueV = nullptr;
4707 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4708 Value *V = PN->getIncomingValue(i);
4709 if (L->contains(PN->getIncomingBlock(i))) {
4710 if (!BEValueV) {
4711 BEValueV = V;
4712 } else if (BEValueV != V) {
4713 BEValueV = nullptr;
4714 break;
4715 }
4716 } else if (!StartValueV) {
4717 StartValueV = V;
4718 } else if (StartValueV != V) {
4719 StartValueV = nullptr;
4720 break;
4721 }
4722 }
4723 if (!BEValueV || !StartValueV)
4724 return None;
4725
4726 const SCEV *BEValue = getSCEV(BEValueV);
4727
4728 // If the value coming around the backedge is an add with the symbolic
4729 // value we just inserted, possibly with casts that we can ignore under
4730 // an appropriate runtime guard, then we found a simple induction variable!
4731 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4732 if (!Add)
4733 return None;
4734
4735 // If there is a single occurrence of the symbolic value, possibly
4736 // casted, replace it with a recurrence.
4737 unsigned FoundIndex = Add->getNumOperands();
4738 Type *TruncTy = nullptr;
4739 bool Signed;
4740 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4741 if ((TruncTy =
4742 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4743 if (FoundIndex == e) {
4744 FoundIndex = i;
4745 break;
4746 }
4747
4748 if (FoundIndex == Add->getNumOperands())
4749 return None;
4750
4751 // Create an add with everything but the specified operand.
4752 SmallVector<const SCEV *, 8> Ops;
4753 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4754 if (i != FoundIndex)
4755 Ops.push_back(Add->getOperand(i));
4756 const SCEV *Accum = getAddExpr(Ops);
4757
4758 // The runtime checks will not be valid if the step amount is
4759 // varying inside the loop.
4760 if (!isLoopInvariant(Accum, L))
4761 return None;
4762
4763 // *** Part2: Create the predicates
4764
4765 // Analysis was successful: we have a phi-with-cast pattern for which we
4766 // can return an AddRec expression under the following predicates:
4767 //
4768 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4769 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4770 // P2: An Equal predicate that guarantees that
4771 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4772 // P3: An Equal predicate that guarantees that
4773 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4774 //
4775 // As we next prove, the above predicates guarantee that:
4776 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4777 //
4778 //
4779 // More formally, we want to prove that:
4780 // Expr(i+1) = Start + (i+1) * Accum
4781 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4782 //
4783 // Given that:
4784 // 1) Expr(0) = Start
4785 // 2) Expr(1) = Start + Accum
4786 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4787 // 3) Induction hypothesis (step i):
4788 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4789 //
4790 // Proof:
4791 // Expr(i+1) =
4792 // = Start + (i+1)*Accum
4793 // = (Start + i*Accum) + Accum
4794 // = Expr(i) + Accum
4795 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4796 // :: from step i
4797 //
4798 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4799 //
4800 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4801 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4802 // + Accum :: from P3
4803 //
4804 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4805 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4806 //
4807 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4808 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4809 //
4810 // By induction, the same applies to all iterations 1<=i<n:
4811 //
4812
4813 // Create a truncated addrec for which we will add a no overflow check (P1).
4814 const SCEV *StartVal = getSCEV(StartValueV);
4815 const SCEV *PHISCEV =
4816 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4817 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4818
4819 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4820 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4821 // will be constant.
4822 //
4823 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4824 // add P1.
4825 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4826 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4827 Signed ? SCEVWrapPredicate::IncrementNSSW
4828 : SCEVWrapPredicate::IncrementNUSW;
4829 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4830 Predicates.push_back(AddRecPred);
4831 }
4832
4833 // Create the Equal Predicates P2,P3:
4834
4835 // It is possible that the predicates P2 and/or P3 are computable at
4836 // compile time due to StartVal and/or Accum being constants.
4837 // If either one is, then we can check that now and escape if either P2
4838 // or P3 is false.
4839
4840 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4841 // for each of StartVal and Accum
4842 auto getExtendedExpr = [&](const SCEV *Expr,
4843 bool CreateSignExtend) -> const SCEV * {
4844 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant")((isLoopInvariant(Expr, L) && "Expr is expected to be invariant"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Expr, L) && \"Expr is expected to be invariant\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4844, __PRETTY_FUNCTION__))
;
4845 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4846 const SCEV *ExtendedExpr =
4847 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4848 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4849 return ExtendedExpr;
4850 };
4851
4852 // Given:
4853 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4854 // = getExtendedExpr(Expr)
4855 // Determine whether the predicate P: Expr == ExtendedExpr
4856 // is known to be false at compile time
4857 auto PredIsKnownFalse = [&](const SCEV *Expr,
4858 const SCEV *ExtendedExpr) -> bool {
4859 return Expr != ExtendedExpr &&
4860 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4861 };
4862
4863 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4864 if (PredIsKnownFalse(StartVal, StartExtended)) {
4865 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P2 is compile-time false\n"
;; } } while (false)
;
4866 return None;
4867 }
4868
4869 // The Step is always Signed (because the overflow checks are either
4870 // NSSW or NUSW)
4871 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4872 if (PredIsKnownFalse(Accum, AccumExtended)) {
4873 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P3 is compile-time false\n"
;; } } while (false)
;
4874 return None;
4875 }
4876
4877 auto AppendPredicate = [&](const SCEV *Expr,
4878 const SCEV *ExtendedExpr) -> void {
4879 if (Expr != ExtendedExpr &&
4880 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4881 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4882 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "Added Predicate: " <<
*Pred; } } while (false)
;
4883 Predicates.push_back(Pred);
4884 }
4885 };
4886
4887 AppendPredicate(StartVal, StartExtended);
4888 AppendPredicate(Accum, AccumExtended);
4889
4890 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4891 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4892 // into NewAR if it will also add the runtime overflow checks specified in
4893 // Predicates.
4894 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4895
4896 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4897 std::make_pair(NewAR, Predicates);
4898 // Remember the result of the analysis for this SCEV at this locayyytion.
4899 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4900 return PredRewrite;
4901}
4902
4903Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4904ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4905 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4906 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4907 if (!L)
4908 return None;
4909
4910 // Check to see if we already analyzed this PHI.
4911 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4912 if (I != PredicatedSCEVRewrites.end()) {
4913 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4914 I->second;
4915 // Analysis was done before and failed to create an AddRec:
4916 if (Rewrite.first == SymbolicPHI)
4917 return None;
4918 // Analysis was done before and succeeded to create an AddRec under
4919 // a predicate:
4920 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec")((isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVAddRecExpr>(Rewrite.first) && \"Expected an AddRec\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4920, __PRETTY_FUNCTION__))
;
4921 assert(!(Rewrite.second).empty() && "Expected to find Predicates")((!(Rewrite.second).empty() && "Expected to find Predicates"
) ? static_cast<void> (0) : __assert_fail ("!(Rewrite.second).empty() && \"Expected to find Predicates\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4921, __PRETTY_FUNCTION__))
;
4922 return Rewrite;
4923 }
4924
4925 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4926 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4927
4928 // Record in the cache that the analysis failed
4929 if (!Rewrite) {
4930 SmallVector<const SCEVPredicate *, 3> Predicates;
4931 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4932 return None;
4933 }
4934
4935 return Rewrite;
4936}
4937
4938// FIXME: This utility is currently required because the Rewriter currently
4939// does not rewrite this expression:
4940// {0, +, (sext ix (trunc iy to ix) to iy)}
4941// into {0, +, %step},
4942// even when the following Equal predicate exists:
4943// "%step == (sext ix (trunc iy to ix) to iy)".
4944bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4945 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4946 if (AR1 == AR2)
4947 return true;
4948
4949 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4950 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4951 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4952 return false;
4953 return true;
4954 };
4955
4956 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4957 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4958 return false;
4959 return true;
4960}
4961
4962/// A helper function for createAddRecFromPHI to handle simple cases.
4963///
4964/// This function tries to find an AddRec expression for the simplest (yet most
4965/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4966/// If it fails, createAddRecFromPHI will use a more general, but slow,
4967/// technique for finding the AddRec expression.
4968const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4969 Value *BEValueV,
4970 Value *StartValueV) {
4971 const Loop *L = LI.getLoopFor(PN->getParent());
4972 assert(L && L->getHeader() == PN->getParent())((L && L->getHeader() == PN->getParent()) ? static_cast
<void> (0) : __assert_fail ("L && L->getHeader() == PN->getParent()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4972, __PRETTY_FUNCTION__))
;
4973 assert(BEValueV && StartValueV)((BEValueV && StartValueV) ? static_cast<void> (
0) : __assert_fail ("BEValueV && StartValueV", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4973, __PRETTY_FUNCTION__))
;
4974
4975 auto BO = MatchBinaryOp(BEValueV, DT);
4976 if (!BO)
4977 return nullptr;
4978
4979 if (BO->Opcode != Instruction::Add)
4980 return nullptr;
4981
4982 const SCEV *Accum = nullptr;
4983 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4984 Accum = getSCEV(BO->RHS);
4985 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4986 Accum = getSCEV(BO->LHS);
4987
4988 if (!Accum)
4989 return nullptr;
4990
4991 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4992 if (BO->IsNUW)
4993 Flags = setFlags(Flags, SCEV::FlagNUW);
4994 if (BO->IsNSW)
4995 Flags = setFlags(Flags, SCEV::FlagNSW);
4996
4997 const SCEV *StartVal = getSCEV(StartValueV);
4998 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4999
5000 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5001
5002 // We can add Flags to the post-inc expression only if we
5003 // know that it is *undefined behavior* for BEValueV to
5004 // overflow.
5005 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5006 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5007 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5008
5009 return PHISCEV;
5010}
5011
5012const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5013 const Loop *L = LI.getLoopFor(PN->getParent());
5014 if (!L || L->getHeader() != PN->getParent())
5015 return nullptr;
5016
5017 // The loop may have multiple entrances or multiple exits; we can analyze
5018 // this phi as an addrec if it has a unique entry value and a unique
5019 // backedge value.
5020 Value *BEValueV = nullptr, *StartValueV = nullptr;
5021 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5022 Value *V = PN->getIncomingValue(i);
5023 if (L->contains(PN->getIncomingBlock(i))) {
5024 if (!BEValueV) {
5025 BEValueV = V;
5026 } else if (BEValueV != V) {
5027 BEValueV = nullptr;
5028 break;
5029 }
5030 } else if (!StartValueV) {
5031 StartValueV = V;
5032 } else if (StartValueV != V) {
5033 StartValueV = nullptr;
5034 break;
5035 }
5036 }
5037 if (!BEValueV || !StartValueV)
5038 return nullptr;
5039
5040 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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5041, __PRETTY_FUNCTION__))
5041 "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?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5041, __PRETTY_FUNCTION__))
;
5042
5043 // First, try to find AddRec expression without creating a fictituos symbolic
5044 // value for PN.
5045 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5046 return S;
5047
5048 // Handle PHI node value symbolically.
5049 const SCEV *SymbolicName = getUnknown(PN);
5050 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5051
5052 // Using this symbolic name for the PHI, analyze the value coming around
5053 // the back-edge.
5054 const SCEV *BEValue = getSCEV(BEValueV);
5055
5056 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5057 // has a special value for the first iteration of the loop.
5058
5059 // If the value coming around the backedge is an add with the symbolic
5060 // value we just inserted, then we found a simple induction variable!
5061 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5062 // If there is a single occurrence of the symbolic value, replace it
5063 // with a recurrence.
5064 unsigned FoundIndex = Add->getNumOperands();
5065 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5066 if (Add->getOperand(i) == SymbolicName)
5067 if (FoundIndex == e) {
5068 FoundIndex = i;
5069 break;
5070 }
5071
5072 if (FoundIndex != Add->getNumOperands()) {
5073 // Create an add with everything but the specified operand.
5074 SmallVector<const SCEV *, 8> Ops;
5075 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5076 if (i != FoundIndex)
5077 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5078 L, *this));
5079 const SCEV *Accum = getAddExpr(Ops);
5080
5081 // This is not a valid addrec if the step amount is varying each
5082 // loop iteration, but is not itself an addrec in this loop.
5083 if (isLoopInvariant(Accum, L) ||
5084 (isa<SCEVAddRecExpr>(Accum) &&
5085 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5086 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5087
5088 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5089 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5090 if (BO->IsNUW)
5091 Flags = setFlags(Flags, SCEV::FlagNUW);
5092 if (BO->IsNSW)
5093 Flags = setFlags(Flags, SCEV::FlagNSW);
5094 }
5095 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5096 // If the increment is an inbounds GEP, then we know the address
5097 // space cannot be wrapped around. We cannot make any guarantee
5098 // about signed or unsigned overflow because pointers are
5099 // unsigned but we may have a negative index from the base
5100 // pointer. We can guarantee that no unsigned wrap occurs if the
5101 // indices form a positive value.
5102 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5103 Flags = setFlags(Flags, SCEV::FlagNW);
5104
5105 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5106 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5107 Flags = setFlags(Flags, SCEV::FlagNUW);
5108 }
5109
5110 // We cannot transfer nuw and nsw flags from subtraction
5111 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5112 // for instance.
5113 }
5114
5115 const SCEV *StartVal = getSCEV(StartValueV);
5116 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5117
5118 // Okay, for the entire analysis of this edge we assumed the PHI
5119 // to be symbolic. We now need to go back and purge all of the
5120 // entries for the scalars that use the symbolic expression.
5121 forgetSymbolicName(PN, SymbolicName);
5122 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5123
5124 // We can add Flags to the post-inc expression only if we
5125 // know that it is *undefined behavior* for BEValueV to
5126 // overflow.
5127 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5128 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5129 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5130
5131 return PHISCEV;
5132 }
5133 }
5134 } else {
5135 // Otherwise, this could be a loop like this:
5136 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5137 // In this case, j = {1,+,1} and BEValue is j.
5138 // Because the other in-value of i (0) fits the evolution of BEValue
5139 // i really is an addrec evolution.
5140 //
5141 // We can generalize this saying that i is the shifted value of BEValue
5142 // by one iteration:
5143 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5144 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5145 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5146 if (Shifted != getCouldNotCompute() &&
5147 Start != getCouldNotCompute()) {
5148 const SCEV *StartVal = getSCEV(StartValueV);
5149 if (Start == StartVal) {
5150 // Okay, for the entire analysis of this edge we assumed the PHI
5151 // to be symbolic. We now need to go back and purge all of the
5152 // entries for the scalars that use the symbolic expression.
5153 forgetSymbolicName(PN, SymbolicName);
5154 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5155 return Shifted;
5156 }
5157 }
5158 }
5159
5160 // Remove the temporary PHI node SCEV that has been inserted while intending
5161 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5162 // as it will prevent later (possibly simpler) SCEV expressions to be added
5163 // to the ValueExprMap.
5164 eraseValueFromMap(PN);
5165
5166 return nullptr;
5167}
5168
5169// Checks if the SCEV S is available at BB. S is considered available at BB
5170// if S can be materialized at BB without introducing a fault.
5171static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5172 BasicBlock *BB) {
5173 struct CheckAvailable {
5174 bool TraversalDone = false;
5175 bool Available = true;
5176
5177 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5178 BasicBlock *BB = nullptr;
5179 DominatorTree &DT;
5180
5181 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5182 : L(L), BB(BB), DT(DT) {}
5183
5184 bool setUnavailable() {
5185 TraversalDone = true;
5186 Available = false;
5187 return false;
5188 }
5189
5190 bool follow(const SCEV *S) {
5191 switch (S->getSCEVType()) {
5192 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5193 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5194 case scUMinExpr:
5195 case scSMinExpr:
5196 // These expressions are available if their operand(s) is/are.
5197 return true;
5198
5199 case scAddRecExpr: {
5200 // We allow add recurrences that are on the loop BB is in, or some
5201 // outer loop. This guarantees availability because the value of the
5202 // add recurrence at BB is simply the "current" value of the induction
5203 // variable. We can relax this in the future; for instance an add
5204 // recurrence on a sibling dominating loop is also available at BB.
5205 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5206 if (L && (ARLoop == L || ARLoop->contains(L)))
5207 return true;
5208
5209 return setUnavailable();
5210 }
5211
5212 case scUnknown: {
5213 // For SCEVUnknown, we check for simple dominance.
5214 const auto *SU = cast<SCEVUnknown>(S);
5215 Value *V = SU->getValue();
5216
5217 if (isa<Argument>(V))
5218 return false;
5219
5220 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5221 return false;
5222
5223 return setUnavailable();
5224 }
5225
5226 case scUDivExpr:
5227 case scCouldNotCompute:
5228 // We do not try to smart about these at all.
5229 return setUnavailable();
5230 }
5231 llvm_unreachable("switch should be fully covered!")::llvm::llvm_unreachable_internal("switch should be fully covered!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5231)
;
5232 }
5233
5234 bool isDone() { return TraversalDone; }
5235 };
5236
5237 CheckAvailable CA(L, BB, DT);
5238 SCEVTraversal<CheckAvailable> ST(CA);
5239
5240 ST.visitAll(S);
5241 return CA.Available;
5242}
5243
5244// Try to match a control flow sequence that branches out at BI and merges back
5245// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5246// match.
5247static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5248 Value *&C, Value *&LHS, Value *&RHS) {
5249 C = BI->getCondition();
5250
5251 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5252 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5253
5254 if (!LeftEdge.isSingleEdge())
5255 return false;
5256
5257 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()\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5257, __PRETTY_FUNCTION__))
;
5258
5259 Use &LeftUse = Merge->getOperandUse(0);
5260 Use &RightUse = Merge->getOperandUse(1);
5261
5262 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5263 LHS = LeftUse;
5264 RHS = RightUse;
5265 return true;
5266 }
5267
5268 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5269 LHS = RightUse;
5270 RHS = LeftUse;
5271 return true;
5272 }
5273
5274 return false;
5275}
5276
5277const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5278 auto IsReachable =
5279 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5280 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5281 const Loop *L = LI.getLoopFor(PN->getParent());
5282
5283 // We don't want to break LCSSA, even in a SCEV expression tree.
5284 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5285 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5286 return nullptr;
5287
5288 // Try to match
5289 //
5290 // br %cond, label %left, label %right
5291 // left:
5292 // br label %merge
5293 // right:
5294 // br label %merge
5295 // merge:
5296 // V = phi [ %x, %left ], [ %y, %right ]
5297 //
5298 // as "select %cond, %x, %y"
5299
5300 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5301 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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5301, __PRETTY_FUNCTION__))
;
5302
5303 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5304 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5305
5306 if (BI && BI->isConditional() &&
5307 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5308 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5309 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5310 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5311 }
5312
5313 return nullptr;
5314}
5315
5316const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5317 if (const SCEV *S = createAddRecFromPHI(PN))
5318 return S;
5319
5320 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5321 return S;
5322
5323 // If the PHI has a single incoming value, follow that value, unless the
5324 // PHI's incoming blocks are in a different loop, in which case doing so
5325 // risks breaking LCSSA form. Instcombine would normally zap these, but
5326 // it doesn't have DominatorTree information, so it may miss cases.
5327 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5328 if (LI.replacementPreservesLCSSAForm(PN, V))
5329 return getSCEV(V);
5330
5331 // If it's not a loop phi, we can't handle it yet.
5332 return getUnknown(PN);
5333}
5334
5335const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5336 Value *Cond,
5337 Value *TrueVal,
5338 Value *FalseVal) {
5339 // Handle "constant" branch or select. This can occur for instance when a
5340 // loop pass transforms an inner loop and moves on to process the outer loop.
5341 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5342 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5343
5344 // Try to match some simple smax or umax patterns.
5345 auto *ICI = dyn_cast<ICmpInst>(Cond);
5346 if (!ICI)
5347 return getUnknown(I);
5348
5349 Value *LHS = ICI->getOperand(0);
5350 Value *RHS = ICI->getOperand(1);
5351
5352 switch (ICI->getPredicate()) {
5353 case ICmpInst::ICMP_SLT:
5354 case ICmpInst::ICMP_SLE:
5355 std::swap(LHS, RHS);
5356 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5357 case ICmpInst::ICMP_SGT:
5358 case ICmpInst::ICMP_SGE:
5359 // a >s b ? a+x : b+x -> smax(a, b)+x
5360 // a >s b ? b+x : a+x -> smin(a, b)+x
5361 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5362 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5363 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5364 const SCEV *LA = getSCEV(TrueVal);
5365 const SCEV *RA = getSCEV(FalseVal);
5366 const SCEV *LDiff = getMinusSCEV(LA, LS);
5367 const SCEV *RDiff = getMinusSCEV(RA, RS);
5368 if (LDiff == RDiff)
5369 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5370 LDiff = getMinusSCEV(LA, RS);
5371 RDiff = getMinusSCEV(RA, LS);
5372 if (LDiff == RDiff)
5373 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5374 }
5375 break;
5376 case ICmpInst::ICMP_ULT:
5377 case ICmpInst::ICMP_ULE:
5378 std::swap(LHS, RHS);
5379 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5380 case ICmpInst::ICMP_UGT:
5381 case ICmpInst::ICMP_UGE:
5382 // a >u b ? a+x : b+x -> umax(a, b)+x
5383 // a >u b ? b+x : a+x -> umin(a, b)+x
5384 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5385 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5386 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5387 const SCEV *LA = getSCEV(TrueVal);
5388 const SCEV *RA = getSCEV(FalseVal);
5389 const SCEV *LDiff = getMinusSCEV(LA, LS);
5390 const SCEV *RDiff = getMinusSCEV(RA, RS);
5391 if (LDiff == RDiff)
5392 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5393 LDiff = getMinusSCEV(LA, RS);
5394 RDiff = getMinusSCEV(RA, LS);
5395 if (LDiff == RDiff)
5396 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5397 }
5398 break;
5399 case ICmpInst::ICMP_NE:
5400 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5401 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5402 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5403 const SCEV *One = getOne(I->getType());
5404 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5405 const SCEV *LA = getSCEV(TrueVal);
5406 const SCEV *RA = getSCEV(FalseVal);
5407 const SCEV *LDiff = getMinusSCEV(LA, LS);
5408 const SCEV *RDiff = getMinusSCEV(RA, One);
5409 if (LDiff == RDiff)
5410 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5411 }
5412 break;
5413 case ICmpInst::ICMP_EQ:
5414 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5415 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5416 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5417 const SCEV *One = getOne(I->getType());
5418 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5419 const SCEV *LA = getSCEV(TrueVal);
5420 const SCEV *RA = getSCEV(FalseVal);
5421 const SCEV *LDiff = getMinusSCEV(LA, One);
5422 const SCEV *RDiff = getMinusSCEV(RA, LS);
5423 if (LDiff == RDiff)
5424 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5425 }
5426 break;
5427 default:
5428 break;
5429 }
5430
5431 return getUnknown(I);
5432}
5433
5434/// Expand GEP instructions into add and multiply operations. This allows them
5435/// to be analyzed by regular SCEV code.
5436const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5437 // Don't attempt to analyze GEPs over unsized objects.
5438 if (!GEP->getSourceElementType()->isSized())
5439 return getUnknown(GEP);
5440
5441 SmallVector<const SCEV *, 4> IndexExprs;
5442 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5443 IndexExprs.push_back(getSCEV(*Index));
5444 return getGEPExpr(GEP, IndexExprs);
5445}
5446
5447uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5448 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5449 return C->getAPInt().countTrailingZeros();
5450
5451 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5452 return std::min(GetMinTrailingZeros(T->getOperand()),
5453 (uint32_t)getTypeSizeInBits(T->getType()));
5454
5455 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5456 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5457 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5458 ? getTypeSizeInBits(E->getType())
5459 : OpRes;
5460 }
5461
5462 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5463 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5464 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5465 ? getTypeSizeInBits(E->getType())
5466 : OpRes;
5467 }
5468
5469 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5470 // The result is the min of all operands results.
5471 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5472 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5473 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5474 return MinOpRes;
5475 }
5476
5477 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5478 // The result is the sum of all operands results.
5479 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5480 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5481 for (unsigned i = 1, e = M->getNumOperands();
5482 SumOpRes != BitWidth && i != e; ++i)
5483 SumOpRes =
5484 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5485 return SumOpRes;
5486 }
5487
5488 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5489 // The result is the min of all operands results.
5490 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5491 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5492 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5493 return MinOpRes;
5494 }
5495
5496 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5497 // The result is the min of all operands results.
5498 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5499 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5500 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5501 return MinOpRes;
5502 }
5503
5504 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5505 // The result is the min of all operands results.
5506 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5507 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5508 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5509 return MinOpRes;
5510 }
5511
5512 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5513 // For a SCEVUnknown, ask ValueTracking.
5514 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5515 return Known.countMinTrailingZeros();
5516 }
5517
5518 // SCEVUDivExpr
5519 return 0;
5520}
5521
5522uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5523 auto I = MinTrailingZerosCache.find(S);
5524 if (I != MinTrailingZerosCache.end())
5525 return I->second;
5526
5527 uint32_t Result = GetMinTrailingZerosImpl(S);
5528 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5529 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\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5529, __PRETTY_FUNCTION__))
;
5530 return InsertPair.first->second;
5531}
5532
5533/// Helper method to assign a range to V from metadata present in the IR.
5534static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5535 if (Instruction *I = dyn_cast<Instruction>(V))
5536 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5537 return getConstantRangeFromMetadata(*MD);
5538
5539 return None;
5540}
5541
5542/// Determine the range for a particular SCEV. If SignHint is
5543/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5544/// with a "cleaner" unsigned (resp. signed) representation.
5545const ConstantRange &
5546ScalarEvolution::getRangeRef(const SCEV *S,
5547 ScalarEvolution::RangeSignHint SignHint) {
5548 DenseMap<const SCEV *, ConstantRange> &Cache =
5549 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5550 : SignedRanges;
5551 ConstantRange::PreferredRangeType RangeType =
5552 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5553 ? ConstantRange::Unsigned : ConstantRange::Signed;
5554
5555 // See if we've computed this range already.
5556 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5557 if (I != Cache.end())
5558 return I->second;
5559
5560 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5561 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5562
5563 unsigned BitWidth = getTypeSizeInBits(S->getType());
5564 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5565 using OBO = OverflowingBinaryOperator;
5566
5567 // If the value has known zeros, the maximum value will have those known zeros
5568 // as well.
5569 uint32_t TZ = GetMinTrailingZeros(S);
5570 if (TZ != 0) {
5571 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5572 ConservativeResult =
5573 ConstantRange(APInt::getMinValue(BitWidth),
5574 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5575 else
5576 ConservativeResult = ConstantRange(
5577 APInt::getSignedMinValue(BitWidth),
5578 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5579 }
5580
5581 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5582 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5583 unsigned WrapType = OBO::AnyWrap;
5584 if (Add->hasNoSignedWrap())
5585 WrapType |= OBO::NoSignedWrap;
5586 if (Add->hasNoUnsignedWrap())
5587 WrapType |= OBO::NoUnsignedWrap;
5588 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5589 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5590 WrapType, RangeType);
5591 return setRange(Add, SignHint,
5592 ConservativeResult.intersectWith(X, RangeType));
5593 }
5594
5595 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5596 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5597 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5598 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5599 return setRange(Mul, SignHint,
5600 ConservativeResult.intersectWith(X, RangeType));
5601 }
5602
5603 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5604 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5605 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5606 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5607 return setRange(SMax, SignHint,
5608 ConservativeResult.intersectWith(X, RangeType));
5609 }
5610
5611 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5612 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5613 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5614 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5615 return setRange(UMax, SignHint,
5616 ConservativeResult.intersectWith(X, RangeType));
5617 }
5618
5619 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5620 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5621 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5622 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5623 return setRange(SMin, SignHint,
5624 ConservativeResult.intersectWith(X, RangeType));
5625 }
5626
5627 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5628 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5629 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5630 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5631 return setRange(UMin, SignHint,
5632 ConservativeResult.intersectWith(X, RangeType));
5633 }
5634
5635 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5636 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5637 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5638 return setRange(UDiv, SignHint,
5639 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5640 }
5641
5642 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5643 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5644 return setRange(ZExt, SignHint,
5645 ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5646 RangeType));
5647 }
5648
5649 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5650 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5651 return setRange(SExt, SignHint,
5652 ConservativeResult.intersectWith(X.signExtend(BitWidth),
5653 RangeType));
5654 }
5655
5656 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5657 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5658 return setRange(Trunc, SignHint,
5659 ConservativeResult.intersectWith(X.truncate(BitWidth),
5660 RangeType));
5661 }
5662
5663 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5664 // If there's no unsigned wrap, the value will never be less than its
5665 // initial value.
5666 if (AddRec->hasNoUnsignedWrap()) {
5667 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5668 if (!UnsignedMinValue.isNullValue())
5669 ConservativeResult = ConservativeResult.intersectWith(
5670 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5671 }
5672
5673 // If there's no signed wrap, and all the operands except initial value have
5674 // the same sign or zero, the value won't ever be:
5675 // 1: smaller than initial value if operands are non negative,
5676 // 2: bigger than initial value if operands are non positive.
5677 // For both cases, value can not cross signed min/max boundary.
5678 if (AddRec->hasNoSignedWrap()) {
5679 bool AllNonNeg = true;
5680 bool AllNonPos = true;
5681 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5682 if (!isKnownNonNegative(AddRec->getOperand(i)))
5683 AllNonNeg = false;
5684 if (!isKnownNonPositive(AddRec->getOperand(i)))
5685 AllNonPos = false;
5686 }
5687 if (AllNonNeg)
5688 ConservativeResult = ConservativeResult.intersectWith(
5689 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5690 APInt::getSignedMinValue(BitWidth)),
5691 RangeType);
5692 else if (AllNonPos)
5693 ConservativeResult = ConservativeResult.intersectWith(
5694 ConstantRange::getNonEmpty(
5695 APInt::getSignedMinValue(BitWidth),
5696 getSignedRangeMax(AddRec->getStart()) + 1),
5697 RangeType);
5698 }
5699
5700 // TODO: non-affine addrec
5701 if (AddRec->isAffine()) {
5702 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5703 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5704 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5705 auto RangeFromAffine = getRangeForAffineAR(
5706 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5707 BitWidth);
5708 if (!RangeFromAffine.isFullSet())
5709