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