Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 4432, column 32
Dereference of null pointer (loaded from variable 'PtrOp')

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