Bug Summary

File:llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 10537, column 32
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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ScalarEvolution.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/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-14/lib/clang/14.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-command-line-argument -Wno-unknown-warning-option -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-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -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-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Analysis/ScalarEvolution.cpp

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