Bug Summary

File:lib/Analysis/ScalarEvolution.cpp
Warning:line 10494, column 15
Value stored to 'MaxBECount' during its initialization is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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