Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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-12/lib/clang/12.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-12~++20200917111122+b03c2b8395b/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp

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