Bug Summary

File:llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 10169, column 35
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 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Analysis -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Analysis/ScalarEvolution.cpp

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