Bug Summary

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